Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we create derived class reference which points to base object

Tags:

c#

Can I create a derived class reference which points to base object?

Consider the following example. I am trying this but gives an error.

Why is it not possible?

class Shape
{
    public virtual void CalculateArea()
    {
      //Code
    }
}

class Circle: Shape
{
    public override void CalculateArea()
    {
        //Code
    }
}

//Main method
class Main()
{
    Public Static void Main()
    {
        Circle circle = new Shape(); //  WHY THIS IS NOT POSSIBLE
    }
}

Is there any solution to this problem?

like image 372
Ravi Solanki Avatar asked Sep 11 '26 05:09

Ravi Solanki


1 Answers

Because Circle is not a base class of Shape.

Yo can do this:

Shape shape = new Circle();
like image 105
Uladzimir Palekh Avatar answered Sep 13 '26 19:09

Uladzimir Palekh