Up-casting and Down-casting in C# Inheritance

Answer: Explanation of Up-casting and Down-casting in C# inheritance with program examples.

C# Up-Casting

An assignment of derived class object to a base class reference in C# inheritance is known as up-casting. The up-casting is implicit and any explicit typecast is not required.
For example, in the below program in the main() method, assignment of the derived class “Circle” object to the base class “Shape” reference is up-casting.

static void Main(string[] args)
    {
        //Use Base class reference
        Shape circle = new Circle();//Up-casting.
        circle.Draw();
}

//Base class
class Shape
{ 
    //Draw()available to base class Shape and all child classes
    public virtual void Draw()
    {
        Console.WriteLine("Shape");
    }
}

class Circle : Shape
{    
    public override void Draw()
    {
        Console.WriteLine("Drawing a Circle ");
    }

    //Speciallized method available to only Circle class
    public void FillCircle()
    {
        Console.WriteLine("Filling a Circle");
    }
}

C# Down-Casting

An assignment of base class object to derived class object is known as Down-casting. For example, in the below c# program example, we have assigned the existing base class object to the derived class circle object using typecasting.

static void Main(string[] args)
    {
        //Use Base class reference
        Shape baseObj = new Circle();//Up-casting.
        baseObj.Draw();

        ////This is called downcasting as assiging it from base to derived object

        Circle derivedObj = (Circle)baseObj; //Down-casting-casting.
        derivedObj.Draw();
        derivedObj.FillCircle();

    }

Why Down-Casting is required in C# programming?

It is possible that derived class has some specialized method. For example, in above derived class Circle, FillCircle() method is specialized and only available to Circle class not in Shape base class.

So, if we have base class reference that is pointing to child class and we want to call specialized method of child class, we cannot call FillCircle() method using base class reference, as it will not be visible to base class.

So, we have to downcast from base to child class, then call specialized method that is FillCircle(); . Same has been depicted in above main() program.

Recommended to read the interview question: Prefer way of down-casting object for sub classes in C#.

Related Posts