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?
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.
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.
"as" tries to cast reference to subtype & returns null, if it fails.
Explicit casting when fails, throws InvalidCastException.
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.
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