Search code examples
c#.netcastingas-operator

Type casting vs as operator in C#


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?


Solution

  • Well,

    • ((Parrot) arg) cast : either Parrot instance or exception (invalid cast) thrown. Note, that you should cast arg first and only then use NumberOfLegs: Console.WriteLine("Moving with" + ((Parrot)arg).NumberOfLegs + " Legs"); note extra (...)
    • arg as Parrot: either Parrot instance or null (note you can't use as if type is struct and thus can't be null)
    • arg is Parrot: either true if arg can be cast to Parrot or false otherwise

    The last case (is) can be used in pattern matching, e.g.

    Console.WriteLine($"Moving with {(arg is Parrot parrot ? parrot.NumberOfLegs : 0)} Legs");