Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Generic class with type String and getting error 'string' must be non-abstract type

Tags:

c#

generics

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

like image 246
jrandomuser Avatar asked Aug 19 '14 13:08

jrandomuser


2 Answers

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()
like image 189
AlexD Avatar answered Nov 02 '22 23:11

AlexD


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; }
}
like image 38
nsgocev Avatar answered Nov 02 '22 23:11

nsgocev