开发者

Different Cast Types in C# [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicates:

Casting: (NewType) vs. Object as NewType

开发者_如何学JAVA Why is the C# “as” operator so popular?

Hey,

I know this may be a silly question but this doubt came to me today.

What is the difference between doing

String text = (String) variable;

and

String text = variable as String;

?


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


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


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜