1

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?

Munsta0
  • 121
  • 1
  • 7

2 Answers2

6

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Why is it a design smell? How could the compiler know what is the type? I hope Eric didn't read your smell comment... `:)` – gdoron Jun 24 '12 at 17:46
  • Thank you very much for this very fast answer :) – Munsta0 Jun 24 '12 at 17:51
  • @gdoron: It's usually a design smell to *need* to do this. I'm not saying that the requirement to cast in this situation is the smell - I'm saying that the situation itself (having to treat one element of a collection in a different way) is a smell. – Jon Skeet Jun 24 '12 at 18:06
5

If you are not sure the cast is valid and don't want an InvalidCastException to be thrown, you can do like this:

Cube cube = shapes[0] as Cube;
if (cube == null)
{
    // cast is not valid
}
else
{
    cube.CubeFunction();
}
Thomas C. G. de Vilhena
  • 13,819
  • 3
  • 50
  • 44