6
votes

I have a simple generic class as follows:

public class DataResponse<T> where T : new()
{
public DataResponse()  
{
    this.Data = new List<T>();
    IsSuccessful = true;
}

public bool IsSuccessful { get; set; }
public string[] ErrorMessages { get; set; }
public List<T> Data { get; set; }
}

It works just fine for every custom type I use, however in once instance I have a collection of data that is one field. Rather than make custom class with one field I would make the type string. Doing so however returns the error:

var response = new DataResponse<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 'DataResponse'

UPDATE I had added the where T : new() in response to encountering the problem originally. Removing it solved it because it caused the IDE to highlight the correct line that was actually giving me the problem. The line causing the error was to a method that does have the new() constraint.

Apparently its an entirely different call on a method

4
Why did you set where T as new()? - Gandarez
According to the docs, System.String does not have a parameterless constructor. Where do you see one? - O. R. Mapper
The type string has a parameterless contructor. No it does not - String Constructor - Bolu
@Gandarez I had actually added the T : new() as a result of hitting the error and seeing that as the common solution. It was only later I realized that IDE was showing the error on the incorrect line. - jrandomuser

4 Answers

17
votes

The new constraint

where T : new()

requires type T to have public default constructor:

The new constraint specifies that any type argument in a generic class declaration must have a public parameterless constructor. To use the new constraint, the type cannot be abstract.

string does not have one.

Try to remove where T : new() from

public class DataResponse<T> where T : new()
3
votes

This happens because String doesn't have public parameterless constructor which is required by :new(). You can confirm it here String Class

You should modify the code to this:

public class DataResponse<T>
{
public DataResponse()  
{
    this.Data = new List<T>();
    IsSuccessful = true;
}

public bool IsSuccessful { get; set; }
public string[] ErrorMessages { get; set; }
public List<T> Data { get; set; }
}
2
votes

The new constraint specifies that any type argument in a generic class declaration must have a public parameterless constructor. To use the new constraint, the type cannot be abstract.

String does not have a parameterless constructor.

http://msdn.microsoft.com/en-us/library/system.string(v=vs.110).aspx

2
votes

String doesn't have public parameter less constructor which is required for :new() and To use the new constraint, the type cannot be abstract.

For your reference : String Class