Amelia B
Amelia B

Reputation: 1084

C# constructor for type parameterized abstract class

So I found a lot of answer to the question if and why it is ok to have a constructor defined in an abstract class.

I am currently trying to make a parameterized constructor available in an abstract class which has a type parameter:

public abstract class Cell<T>
{
    int address;
    T value;

    protected Cell<T>(int address, T value)
    {

    }
}

But c# simply refuses it and Intellisense completely breaks down. So why is it possible to have a constructor in an abstract class but as soon as the abstract class gets a type parameter everything refuses it?

Upvotes: 4

Views: 2743

Answers (2)

Zoran Horvat
Zoran Horvat

Reputation: 11301

Remove <T> from the constructor declaration and then everything will work. For example, this compiles just fine:

public abstract class Cell<T>
{
    int address;
    T value;

    protected Cell(int address, T value)
    {

    }
}

public class CellInt : Cell<int>
{
    public CellInt(int address, int value): base(address, value) { }
}

Upvotes: 4

rory.ap
rory.ap

Reputation: 35260

Your constructor should look like this:

protected Cell(int address, T value)
{

}

You don't need to specify the type parameter in the constructor.

The point of a constructor in an abstract class is to force derived classes to call one of the abstract class' constructors from any constructor that the derived classes define.

Upvotes: 2

Related Questions