a blog for those who code

Tuesday 5 August 2014

Casting with is and as operators in C#

In this post we will show you how you can cast from one type to another using is and as operators.Sometimes it is too necessary for us while developing to cast an object to various type.
Suppose you want to cast an object to any of its base types you don't have to write any special syntax for that, since it considers safe implicit conversions. But if you want to cast an object to any of its derived types, you actually need to explicitly cast that object.

Object o = new Int32(); // No cast needed as Object is a base type of Int32
Int32 i = (Int32) o; // Cast required as Int32 is derived from Object.

Suppose you are doing something like,

StringBuilder sb = new StringBuilder();
object o = sb;
StreamReader sr = (StreamRader) o; // This line will throw an exception as "Unhandled Exception: System.InvalidCastException"

You will get InvalidCastException if CLR don't allow you to proceed with the cast like in the above case. Since Type Safety is an extremely important part of the CLR, at run time you might get this type of error "Unhandled Exception: System.InvalidCastException".

Casting with is Operator
The is operator checks whether an object is compatible with a given type, and it gives result as Boolean (true or false). The plus point of using is operator over the normal casting is that, the is operator will never throw an exception.
For example,
Int32 i = new Int32();
Boolean bool1 = (i is Int32); // bool1 is true
Boolean bool2 = (i is DateTime); // bool2 is false

If in the above example 'i' is null then is operator will always return false.

The problem with is operator is that, CLR is actually checking the object's type twice. The is operator first checks to see if the type is compatible. If it does, then on doing the actual casting, it again checks the compatibility.

Casting with as Operator
To improve the performance while casting and to handle the exception you can use as operator while doing the casting.
Object o = new Object();
Int32 i = o as Int32;
if(i != null) {
}

In the above code CLR checks if Object o is compatible with the Int32 type, if it is as will return a non-null reference to the same object. If it is not compatible, the as operator will return null. Thus before doing anything you need to check if the casted object (i in this case) is null or not.

Please Like and Share the Blog, if you find it interesting and helpful.

No comments:

Post a Comment