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
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.
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.
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() .
You don't provide the type parameter in the constructor. This is how you should do it.
public class Cell<T> { public Cell() { } }
And if you need the Type as a property:
public class Cell<T> { public Cell() { TheType = typeof(T); } public Type TheType { get;} }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With