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
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()
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; }
}
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