Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 857
Chev Avatar asked May 13 '26 22:05

Chev


1 Answers

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

Explicit cast will throw an exception if it fails.

like image 169
Leon Avatar answered May 15 '26 11:05

Leon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!