Search code examples
c#listobjectparentinherited

C# How to access inherited object from parent List


I'm trying to find a way to make a list of parent object with a variety of inherited objects. Here is an example.

class Prog {
    public Prog ( ) {
        List<Shape> shapes = new List<Shape>();
        shapes.Add( new Cube() );
        shapes.Add( new Shape() );

        //All those ways will not work, I cannot figure a way how to do this
        shapes[0].CubeFunction(); 
        (Cube)shapes[0].CubeFunction();
        Cube cube = shapes[0];
    }
}

class Shape {
    public Shape (){}
}

class Cube : Shape {        
    public Cube (){}
    public void CubeFunction(){}
}

Does anyone know how to get the code in class Prog to work?


Solution

  • Your cast version is nearly right - it's only wrong because of precedence. You'd need:

    ((Cube)shapes[0]).CubeFunction();
    

    Alternatively:

    Cube cube = (Cube) shapes[0];
    cube.CubeFunction();
    

    The need to cast like this is generally a bit of a design smell, mind you - if you can avoid it, it's worth trying to do so.