2

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?

Community
  • 1
  • 1
CatDadCode
  • 58,507
  • 61
  • 212
  • 318
  • See my article on the subject: http://blogs.msdn.com/b/ericlippert/archive/2009/10/08/what-s-the-difference-between-as-and-cast-operators.aspx – Eric Lippert Sep 12 '11 at 20:40

3 Answers3

6

"as" will set the result to null if it fails.

Explicit cast will throw an exception if it fails.

Leon
  • 3,311
  • 23
  • 20
3
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.

Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • Does this mean `(string)myInt` would return a string value of myInt but `myInt as string` would return null? – CatDadCode Sep 12 '11 at 18:59
  • It looks for explicit conversions, no? – dlev Sep 12 '11 at 18:59
  • @Alex: If there is an implicit conversion method from the source type to destination type, then yes, it will return string value of myInt. – Nawaz Sep 12 '11 at 19:02
  • @Nawaz Sorry, let me rephrase: if there is an implicit conversion from the source type to `string`, the cast is superfluous anyway. If there is an `explicit` conversion defined, that is the one that will be used. 'explicit' or 'implicit' isn't really relevant, since defining either one will cause that code to be invoked. – dlev Sep 12 '11 at 19:06
1

The cast will throw an exception if the object cannot be cast to the target type. as will just return null.

Achim
  • 15,415
  • 15
  • 80
  • 144