Reputation: 1096
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?
Upvotes: 6
Views: 650
Reputation: 7208
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.
Upvotes: 11
Reputation: 26648
1. As far I know (possbily outdated) "as
" is faster then cast.
2. Neither of your examples are optimal. The optimal way is:
var v = reference as subtype;
if (v != null){
// Do somthing.
}
In this way you do not have double-casting problem.
Upvotes: 1
Reputation: 17014
One important thing about that is that, when using the as operator, such type should be nullable since, should it fail, it will return null. Whereas, using C-style casting, will throw an Exception when the cast can't be performed.
Upvotes: -1
Reputation: 1031
http://msdn.microsoft.com/en-us/library/cscsdfbt(VS.71).aspx
which says: "as" equals to:
expression is type ? (type)expression : (type)null;
That means means second one is kind of too much.
Upvotes: 1
Reputation: 700212
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.
Upvotes: 6
Reputation: 754565
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.
Upvotes: 1
Reputation: 33476
"as" tries to cast reference to subtype & returns null, if it fails.
Explicit casting when fails, throws InvalidCastException.
Upvotes: 1