Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

generics

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

like image 212
pencilCake Avatar asked Mar 14 '12 11:03

pencilCake


People also ask

What Is syntax in constructor?

Syntax of constructor functionsThe declaration integer v1; initializes our object v1 and assigns the data members a and b the value 2 . With normal member functions, we have to write a statement to initialize each of the objects.

What is a generic constructor in Java?

A generic constructor is a constructor that has at least one parameter of a generic type. We'll see that generic constructors don't have to be in a generic class, and not all constructors in a generic class have to be generic.

What is default constructor with example?

A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values. If no user-defined constructor exists for a class A and one is needed, the compiler implicitly declares a default parameterless constructor A::A() .


2 Answers

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

public class Cell<T>  {     public Cell()     {     } } 
like image 56
Trevor Pilley Avatar answered Oct 16 '22 10:10

Trevor Pilley


And if you need the Type as a property:

public class Cell<T> {     public Cell()     {         TheType = typeof(T);     }      public Type TheType { get;} } 
like image 20
RogerW Avatar answered Oct 16 '22 08:10

RogerW