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 : eitherParrotinstance or exception (invalid cast) thrown. Note, that you should castargfirst and only then useNumberOfLegs:Console.WriteLine("Moving with" + ((Parrot)arg).NumberOfLegs + " Legs");note extra(...)arg as Parrot: eitherParrotinstance ornull(note you can't useasif type isstructand thus can't benull)arg is Parrot: eithertrueifargcan be cast toParrotorfalseotherwiseThe last case (
is) can be used in pattern matching, e.g.