Reputation: 1437
I am working with Generic class and Constraint. Following is my class.
public class GenericList<T> where T : new()
{
private Node head;
// constructor
public GenericList()
{
head = null;
}
}
when i create object with integer it works fine
GenericList<int> list = new GenericList<int>();
But when i try with string it gives me following compile time error.
GenericList<string> list1 = new GenericList<string>();
'string' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'GenericTest.GenericList' also when i passed reference parameter like any custom class it works fine.
What is the problem with string?
Upvotes: 1
Views: 312
Reputation: 25846
It is pointless for String
type to have public parameterless constructor because String
is immutable, which means that if String
would have this constructor then it would have to create an empty string object and that is just stupid, because after creation you can not change it.
Upvotes: 2
Reputation: 18534
String Class does not have a public parameterless constructor..that is why the new()
constraint is not applicable to it.
Read Constraints on Type Parameters (C# Programming Guide):
where T : new()
The type argument must have a public parameterless constructor. When used together with other constraints, the new() constraint must be specified last.
Upvotes: 3