tags:

views:

96

answers:

4
+4  A: 

as will return null if variable isn't actually of that type (String in this case). The cast will throw an exception.

jeffamaphone
as will return null if variable isn't actually of that type **or a derived type** (String in this case). The cast will throw an exception.
Mehrdad Afshari
Beat me to it. Keep in mind that `as` will not work on value types. `int i = obj as int;` will not compile. The `as` keyword must be used with a reference type or nullable type as @Mehrdad Afshari said.
Matt Davis
@Matt: it works. You need to use a nullable type: `int? i = obj as int?;`
Mehrdad Afshari
+5  A: 

A cast can do three things:

  • Perform a user-defined conversion
  • Perform an unboxing conversion
  • Perform a reference conversion

An as operation is almost always a reference conversion, the only exception being unboxing to a nullable type:

object x = "hello";
int? y = x as int?; // y is null afterwards

Then there's the behaviour with conversions which fail at execution time. So the differences are:

  • Casts performing reference conversions or unboxing will throw InvalidCastException on failure; as will result in the null value of the target type instead
  • Casts can perform user-defined conversions; as can't
  • Casts can unbox to non-nullable value types; as can only be used for unboxing if the target type is a nullable value type
Jon Skeet
+2  A: 

Here is the link to Eric Lippert's blog on casting in C#. I'd summarize it, but it's pretty short and he'll explain it much better than me.

http://blogs.msdn.com/ericlippert/archive/2009/10/08/what-s-the-difference-between-as-and-cast-operators.aspx

And here is his post on the cast operator:

http://blogs.msdn.com/ericlippert/archive/2009/03/19/representation-and-identity.aspx

Kevin
A: 

There are a lot of different ways to cast in C#.

This will try to cast the reference to a String reference. If the cast fails, it throws an exception:

string text = (String) variable;

This will try to cast the reference to a String reference. If the cast fails, it will return a null reference to be assigned to the variable:

string text = varible as String;

This will cast a string reference to an object reference, which is a safe casting as String inherits from Object:

object text = (object)"1337";

Casting to a parent class can also be done implicitly:

object text = "1337";

This will box a value inside an object, then unbox it to a plain value again:

int value = 42;
object boxed = (object)value;
int valueAgain = (int)boxed;

The boxing can also be done implicitly:

int value = 42;
object boxed = value;
int valueAgain = (int)boxed;

This will make a widening conversion from byte to int:

byte a = 42;
int b = (int)a;

The same works as an implicit conversion:

byte a = 42;
int b = a;

This will make a narrowing conversion from int to byte, throwing away the overflow:

int a = 512;
byte b = (byte)a; // b now contains 0
Guffa