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?
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):