Possible Duplicates:
Direct casting vs 'as' operator?
Casting: (NewType) vs. Object as NewType
What is difference between normal typecasting and using “AS” keyword?
The is operator returns true if the given object is of the same type whereas as operator returns the object when they are compatible with the given type. The is operator returns false if the given object is not of the same type whereas as operator return null if the conversion is not possible.
The as operator can only be used on reference types, it cannot be overloaded, and it will return null if the operation fails. It will never throw an exception. Casting can be used on any compatible types, it can be overloaded, and it will throw an exception if the operation fails.
Using 'as' will return null if the 'cast' fails where casting will throw an exception if the cast fails. Show activity on this post. Using 'as' will not throw an exception if the obj is not a String. Instead it'll return null.
Typecasting, or type conversion, is a method of changing an entity from one data type to another. It is used in computer programming to ensure variables are correctly processed by a function. An example of typecasting is converting an integer to a string.
Using as
will fail gracefully if the object is the wrong type, and the resulting value will be null, where a normal cast would throw an InvalidCastException:
object x = new object();
string y = x as string; // y == null
string z = (string)x; // InvalidCastException
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With