-1

I am trying to understand Upcasting and DownCasting. In the code shown below, I upcast Circle object to Shape and after upcasting methods available are Draw and Duplicate, but when I executed shape.Draw() it is showing output from derived class - can anybody explain why?

class Program
{
    static void Main(string[] args)
    {
        //Use Base class reference
        Circle circle = new Circle();
        //Up-casting
        Shape shape = circle;
        shape.Draw();           //output:- Drawing a Circle 
        shape.duplicate();      //output:- Duplicated!!    
    }
}

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

    public void duplicate()
    {
        Console.WriteLine("Duplicated!!");
    }
}

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");
    }
}

Why is the output of shape.Draw(); "Drawing a Circle" instead of "Drawing Shape" even though upcasting doesn't make access to any method from child class?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
baudi27
  • 25
  • 5
  • Because the circle remains a circle, event though you casted it. Casting is not converting, it remains the same object – Charlieface Oct 10 '21 at 16:47
  • Please read the documentation on [`override`](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/override), and then you will understand. You can also refer to cly's answer. – Jiale Xue - MSFT Oct 11 '21 at 01:46

1 Answers1

0

The Draw method declared as virtual in Shape which means the runtime will look for overriding member on actual instance and execute it if found. It doesnt care what is the type of the reference you currently have to that instance.

Of course you wont see any Circle specific members while trying to call them using reference of type Shape.

cly
  • 661
  • 3
  • 13