What is the syntax for a default constructor for a generic class?

C#.NetGenerics

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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

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

Solution 2 - C#

And if you need the Type as a property:

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

    public Type TheType { get;}
}

Solution 3 - C#

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;
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpencilCakeView Question on Stackoverflow
Solution 1 - C#Trevor PilleyView Answer on Stackoverflow
Solution 2 - C#RogerWView Answer on Stackoverflow
Solution 3 - C#PeerhenryView Answer on Stackoverflow