Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Any difference whatsoever between "(subtype)data" and "data as subtype" typecasting?

Assuming I have an instance of an object that I know belongs to a subclass of a certain subtype passed to me through a reference of a supertype in C#, I'm used to seeing typecasting done this Java-like way (Assuming "reference" is of the supertype):

if (reference is subtype){
subtype t = (subtype)reference;
}

But recently I've come across examples of what appears to be the same thing done this way:

if (reference is subtype){
subtype t = reference as subtype;
}

Are those two completely equivalent? Is there any difference?

like image 355
Fabio de Miranda Avatar asked Jul 22 '09 21:07

Fabio de Miranda


4 Answers

The difference is one will throw an exception and the other one will return a null value if the casting is incorrect. Also, "as" keyword does not work on value type.

BaseType _object;

//throw an exception
AnotherType _casted = (AnotherType) _object; 

//return null
AnotherType _casted = _object as AnotherType;

Edit:

In the example of Fabio de Miranda, the exception will not be thrown due to the use of "is" keyword which prevents to enter in the "if" statement.

like image 64
Francis B. Avatar answered Oct 21 '22 11:10

Francis B.


They are the same used that way, but neither is the best option. You should do the type checking only once:

subtype t = reference as subtype;
if (t != null) {
   ...
}

Checking for null is more efficient than checking for type.

like image 38
Guffa Avatar answered Oct 21 '22 11:10

Guffa


"as" tries to cast reference to subtype & returns null, if it fails.
Explicit casting when fails, throws InvalidCastException.

like image 1
shahkalpesh Avatar answered Oct 21 '22 11:10

shahkalpesh


No they are not equivalent. The first will work on any type but the second example will only work on reference types. The reason why is the "as" operator is only valid for a reference type.

like image 1
JaredPar Avatar answered Oct 21 '22 13:10

JaredPar