What is the difference between Type casting and as operator in C#. For example in this code:
class LivingThing
{
public int NumberOfLegs { get; set; }
}
class Parrot : LivingThing
{
}
interface IMover<in T>
{
void Move(T arg);
}
class Mover<T> : IMover<T>
{
public void Move(T arg)
{
// as operator
Console.WriteLine("Moving with" + (arg as Parrot).NumberOfLegs + " Legs");
// Type casting
Console.WriteLine("Moving with" + (Parrot)arg.NumberOfLegs + " Legs");
}
}
Why the Type casting is not valid in the second situation and what is the difference of those?
Well,
((Parrot) arg)
cast : eitherParrot
instance or exception (invalid cast) thrown. Note, that you should castarg
first and only then useNumberOfLegs
:Console.WriteLine("Moving with" + ((Parrot)arg).NumberOfLegs + " Legs");
note extra(...)
arg as Parrot
: eitherParrot
instance ornull
(note you can't useas
if type isstruct
and thus can't benull
)arg is Parrot
: eithertrue
ifarg
can be cast toParrot
orfalse
otherwiseThe last case (
is
) can be used in pattern matching, e.g.