C Sharp AS Keyword vs Explicit Cast

posted on 1/5/2015 6:38 PM by Eric Butler


I came across something in C# the other day, and it's something I haven't put much thought into, but I figured I would try to understand the differences between an explicit cast, and using the AS keyword. 

//our string object
var str = "This is a string";

//now, we shove it into an Object
object obj = str;

//we can get it back by doing an explicit cast
var str1 = (string)obj;
Console.WriteLine(str1);

//or get it back using the "as" keyword
var str2 = obj as string;
Console.WriteLine(str2);

If we run this example in a simple console application, we won't see any noticeable differences. Both will convert our object back to a string.

But what about performance?

In the same application, I created a simple for loop, which repeated the cast operation 10 million times while performing a ToString operation. The result was nearly identical for both operations. I ran this several times.

Using 'as' keyword took 00:00:00.0732140

Explicit cast took 00:00:00.0714824

So what ARE the differences?

The explicit cast operation, (string)obj will throw an InvalidCastException if the object we are casting is not the destination type, in this case, a string. However, the "as" keyword will not throw this exception. The value is tested first to see if it is of the type you are casting. If the object is not of the type you are trying to cast, the value will be returned as null.

But, another difference is that the "as" keyword will only work for reference types like string, List, etc. and cannot be used for value types like int, float, etc.

Choosing which method to use will depend on you. If you know that your value will always be of a specific type, you generally have no need to use the "as" keyword. But, using it can give you a bit of syntactic sugar:

var a = ((string)obj).ToString();

vs

var a = (obj as string).ToString();

Personally, I tend to prefer the second example in this case, because it makes the code just slightly more readable, but other than that, both will cast your object. If you do not know what the type will be at runtime, then you can always test your value by doing something like this:

//test value to see if its a string
var a = (obj as string);

if (a != null) {
//do something
}

Using either method will depend on your preference and need.



As a thank-you, please consider sending a small donation. You can contribute as much as you'd like.

Comments

Log in to leave a comment

Log In