开发者

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

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

Possible Duplicate:

Direct casting vs 'as' operator?

Casting vs using the 'as' keyword in the CLR

object myObject = "Hello world.";
var myString = my开发者_开发知识库Object as string;

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

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


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

Explicit cast will throw an exception if it fails.


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.


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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜