90
votes

Is it forbidden in C# to implement a default constructor for a generic class?

If not, why the code below does not compile? (When I remove <T> it compiles though)

What is the correct way of defining a default constructor for a generic class then?

public class Cell<T> 
{
    public Cell<T>()
    {
    }
}

Compile Time Error: Error 1 Invalid token '(' in class, struct, or interface member declaration

3

3 Answers

150
votes

You don't provide the type parameter in the constructor. This is how you should do it.

public class Cell<T> 
{
    public Cell()
    {
    }
}
11
votes

And if you need the Type as a property:

public class Cell<T>
{
    public Cell()
    {
        TheType = typeof(T);
    }

    public Type TheType { get;}
}
6
votes

And if you need to inject an instance of the type:

public class Cell<T>
{
    public T Thing { get; }

    public Cell(T thing)
    {
        Thing = thing;
    }
}