C# Typecasting: Use ‘as’ instead of the normal Cast

csharpWe are all used to casting from one type to another in different languages that we use. In all C-like languages (C,C++,C#,Java etc) we use this simple format.

Okay I am using an overly trivial example here but I think you get the point.

Now imagine the following example. We are given an enumerable form of data through the network, in JSON format let’s say, We are aware that this enumerable has different forms of data, some are objects, some are strings, some are ints etc. Bear with me here, I know this is a crazy scenario which has no meaning but let’s suspend our disbelief for a moment and go through with it. So let’s say we have the following Enumerable

Now let’s say we want to print all these to a log file. But only those that are of a string type and nothing else. If it’s a number we would not print it, if it’s a CustomObject or anything else, we will not print it.

So how would we solve this? Well one solution would be to check the type of each item and if it is a string print it right? Something like the following

Another way, a really bad way, was to type cast the item in a try/catch and if no exception is thrown, print it. Something like the following

Ignoring the fact that this will also print the numbers as they can be cast to strings, this method relies on throwing exceptions. A pattern that is really heavy on resources and costs a lot.


A different approach would be to use the ‘as’ operator. The ‘as’ operator can be used to replace the classic type casting. The only difference is that the ‘as’ operator returns null if the casting fails instead of throwing an exception. So all we have to do is check for null value. If it is not null then conversion was successful.

Now in a completely different scenario in which we are converting from one object type to another, and as we said before we wish to remove nulls from our designs another useful way would be the following

Thus if our conversion fails we simply create a new instance of the AnotherObject and use an “empty” object instead of passing a null value around.

On a final note, in order for as conversion to work for your custom classes you will have to implement implicit or explicit type conversions as explained here


Please follow and like us:

Leave a Reply