Search code examples
c#arraysclassradixderived

C# Accessing values of a derived class in an array of the base class


This is not exactly what I am working with but I hope it makes a clear example:

public abstract class Shape
{
     public int Area;
     public int Perimeter;
     public class Polygon : Shape
     {
         public int Sides;
         public Polygon(int a, int p, int s){
             Area = a;
             Perimeter = p;
             Sides = s;
         }
     }
     public class Circle : Shape
     {
         public int Radius;
         public Circle(int r){
              Area = 3.14*r*r;
              Perimeter = 6.28*r;
              Radius = r;
         }
     }
}

In the main function I would have something like this:

Shape[] ThisArray = new Shape[5];
ThisArray[0] = new Shape.Circle(5);
ThisArray[1] = new Shape.Polygon(25,20,4);

My problem is that when I deal with ThisArray, I can't access values other than Area and Perimeter. For example:

if (ThisArray[0].Area > 10)
   //This statement will be executed

if (ThisArray[1].Sides == 4)
   //This will not compile

How can I access Sides from ThisArray[1]? I could access it if I did something like
Shape.Polygon RandomSquare = new Shape.Polygon(25,20,4) but not if it is in an array of shapes.

If I recall correctly this could be accomplished in C++ by doing something like
Polygon->ThisArray[1].Sides (I forget what this is called) but I do not know how do this in C#

If I can't do what I am trying to do, how can I circumvent this problem?

Thank you for reading through what I intended to be short, any help is appreciated.


Solution

  • You should use casting:

    (ThisArray[1] as Shape.Polygon).Sides
    

    Note that you should make sure the underlying object instance actually IS a Polygon, otherwise this will raise an exception. You can do this by using something like:

    if(ThisArray[1] is Shape.Polygon){
        (ThisArray[1] as Shape.Polygon).Sides
    }