Home > Blockchain >  Why doesnt Main recognize properties and methods declared in a inherited class?
Why doesnt Main recognize properties and methods declared in a inherited class?

Time:01-01

abstract class Geometry 
{
    public string Color {get; set;}
}


class Ring : Geometry 
{
    public double Radius {get; set;}
}

class Triangle : Geometry 
{

}

class Square : Geometry 
{

}

I want to add property radius only to class ring, but I have to declare radius also in geometry class if I want instances of Ring to have access to Radius property in Main, and then Main instances of triangle and square also have access to radius - which I dont want.

The same thing is with methods

I declare classes in Main like this:

Geometry ring1 = new Ring();
Geometry triangle1 = new Triangle();
Geometry square1 = new Square();

I know that it works with Ring ring1 = new Ring(); but what if I want to declare it like this: Geometry ring1 = new Ring(); to put everything in an array of geometry objects?

CodePudding user response:

If you place everything in an array of type Geometry you don't want access to the radius. You want to handle all objects as a Geometry and since that class doesn't implement the radius is not visible without casting.

This becomes interesting when you have methods or properties that span all classes e.g. a method for calculating the area of a shape. They each can have their own implementation with the circle relying on the radius while a quare uses the length of a side.

After all you create an array of the shapes because they have something in common that you want to make use of.

CodePudding user response:

Maybe you should read more about inheritance and polymorphism.

You can access derived properties through the base class via conversion, e.g.:

Geometry ring= new Ring();
var radius = (ring as Ring).Radius;
  •  Tags:  
  • c#
  • Related