Search code examples
c#objecttypescastingstrong-typing

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


Possible Duplicate:
Direct casting vs 'as' operator?
Casting vs using the 'as' keyword in the CLR

object myObject = "Hello world.";
var myString = myObject as string;

object myObject = "Hello world.";
var myString = (string)myObject;

I have seen type conversion done both ways. What is the difference?


Solution

  • var myString = myObject as string;
    

    It only checks the runtime type of myobject. If its string, only then it cast as string, else simply returns null.

    var myString = (string)myObject;
    

    This also looks for implicit conversion to string from the source type. If neither the runtime type is string, nor there is implicit conversion, then it throws exception.

    Read Item 3: Prefer the is or as Operators to Casts from Effective C# by Bill Wagner.