Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting - What's the difference between "(myObject)something" and "something As myObject" in C#?

Tags:

c#

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?

like image 348
NibblyPig Avatar asked Nov 30 '22 18:11

NibblyPig


1 Answers

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.

like image 83
Aaronaught Avatar answered Apr 26 '23 19:04

Aaronaught