Search code examples
c#downcastupcasting

Writing Upcasting and Downcasting expressions in c#


I have been recently studying upcasting and downcasting in c#. I understand that upcasting refers to conversion from a derived class to a base class. However, when i see a practical example of upcasting (like below), i get confused.

public class Shape 
{
...
}

public class Circle : Shape
{
...
}

Circle circle = new Circle();
Shape shape = new Shape();
// Converting an object into its base class reference
shape = circle

If we are converting circle into its base class reference, shouldn't it be like

circle = shape 

Sorry if it sounds too amateur. This is because I have always seen expressions in the following format:

int x = 3; // means assign 3 to variable x. 

So I am just confused why circle is on the right hand side and not on the left hand side. Please advise. Consider me a beginner.


Solution

  • (Aside: This is called upcasting because, traditionally, class diagrams are drawn such that the base classes are shown physically above the derived classes.)

    Now when you do:

    shape = circle; // shape->(instance of Circle)
    

    you are assigning a Circle reference to a Shape reference, so that after the assignment the reference shape will be referencing a Circle.

    This is fine, because everything you can do with a Shape you can also do with a Circle.

    If, however, you do:

    circle = shape; // circle->(instance of Shape)
    

    you are assigning a Shape reference to a Circle reference. You can't do this because (if this were possible) you would then be able to access Circle features that are not present in a Shape.

    For example, imagine that Circle.Radius exists but Shape.Radius does not.

    If you were allowed to point the circle reference at a Shape what would happen if you tried to access circle.Radius? The answer would be: undefined behaviour would happen, because Shape.Radius does not exist.