简体   繁体   中英

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM