What is the difference between "(type)object" and "object as type"?

object myObject = "Hello World.";  
string myString = myObject as string;  

object myObject = "Hello World.";  
string myString = (string)myObject;  

I constantly forget the difference between these two usages of type conversion so I decided to throw up a quick blog post about it. Hopefully writing an explanation will cement it in my brain.

Using the as keyword will return the string value of the object if it is a string. If it is not a string it will simply return null. Explicit casting will throw an exception rather than return null.

object myObject = 123;  
string myString = myObject as string;  
// myString = null

object myObject = 123;  
string myString = (string)myObject;  
// throws an exception

Chev

Read more posts by this author.

comments powered by Disqus