Home > Back-end >  Return the same type as subclass calling a base method
Return the same type as subclass calling a base method

Time:12-31

A very simple base class:

class Figure {
    public List<?> getList() {
        var list = new List<same as child>();
        //do some code
        //filling list
        return list;
    }
}

This inheriting class:

class Rectangle : Figure
{
    
}
class Cube : Figure
{
    
}

I know I could use the generic like this:

class Figure {
    public List<T> getList<T>() {
        var list = new List<T>();
        //do some code
        //filling list
        return list;
    }
}

Rectangle rec = new Rectangle();
List<Rectangle> lRec = rec.getList<Rectangle>();

Cube cube = new Cube();
List<Cube> lCube = cube.getList<Cube>();

But I want to know if there is an alternative

Like this:

Rectangle rec = new Rectangle();
List<Rectangle> lRec = rec.getList();

Cube cube = new Cube();
List<Cube> lCube = cube.getList();

CodePudding user response:

If you constraint the type parameter to the implementing class you get what you're looking for:

class Figure<T> where T : Figure<T>
{
    public List<T> getList()
    {
        var list = new List<T> ();
        //do some code
        //filling list
        return list;
    }
}

class Rectangle : Figure<Rectangle>
{

}
class Cube : Figure<Cube>
{

}

Depending on the scenario marking getList as virtual or abstract might come in handy

  • Related