I've encountered this a couple of times and been perplexed.
Cat c = new Cat("Fluffy");
return (Animal)c;
Cat c = new Cat("Fluffy");
return c as Animal;
What's the reason for both of these syntaxes to exist?
The as
operator is a safe cast. If the types are not compatible, as
will return null
.
The explicit cast, (Animal)c
, on the other hand, will throw an InvalidCastException
if the types are not assignment-compatible.
Also worth noting that as
only works for inheritance relationships, whereas the explicit cast operator will work for value types...
decimal d = 4.0m;
int i = (int)d;
...and any other explicit conversion operators defined on the type with public static explicit operator
. These won't work with as
.
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