1
votes

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?

2
Konstantin has explained why it's failing - but why do you have the constraint on T to start with? When do you want to call new T()? That's all the constraint enables. - Jon Skeet
None of that answers why you'd want the parameterless constructor constraint. Again, when do you want to call new T() within GenericList? - Jon Skeet

2 Answers

3
votes

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.

2
votes

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.