The difference between "as" and "cast" operators?

Today i read some important about 'as' operator.Which i would like to share with my .Net geeks.This is one of the most frequent question asked in interview.its bit confusing but the excerpt defined here will give you bit idea about the representation.

The difference between "(Dotnet) cSharp" and "cSharp as Dotnet" is that the former throws an exception if the conversion fails, whereas the latter returns null. Though this is correct, and this is the most obvious difference, it's not the only difference. There are pitfalls to watch out for here.


short s = (short)123;
int? i = s as int?;

The "as" operator will not make the representation-changing conversions from short to nullable int like the cast operator would. Similarly, if you have class Dotnet and unrelated class cSharp,  with a user-defined conversion from cSharp to Dotnet, then "(Dotnet) cSharp,  will run the user-defined conversion, but "csharp as Dotnet" will not. The "as" operator only considers reference.

And finally, of course the use cases of the two operators are  similar, but semantically quite different. A cast communicates to the reader "I am certain that this conversion is legal and I am willing to take a runtime exception if I'm wrong"(I am willing to accept such error). The "as" operator communicates "I don't know if this conversion is legal or not;(Let's try once and see what happens how it goes").

In more layman words "The as operator returns null if the object can't be cast to that type, and just casting produces an exception"

Enjoy Coding
Sachin Kalia
Ebook Download
View all
Learn
View all