i'm not sure even it's possible but here the problem i'm trying to add item to List<T>
as follow
public static SelectList ToSelectList<T>(List<T> addlist) where T : new ()
{
addlist.Insert(0, new T { Id = -1, Name = "SELECT" });
var list = new SelectList(addlist, "Id", "Name");
return list;
}
new T { Id = -1, Name = "SELECT" }
throwing error is it possible to add item to List<T>
?
The problem is that, via the generic constraints, you have declared T
as any object with a default constructor.
The compiler performs type checking at compile time, and T does not neccessarily have the properties Id
or Name
.
A solution is to
Id
and Name
, A compiling example:
public interface IEntity
{
int Id {get; set; }
string Name {get; set; }
}
class Widget : IEntity
{
public int Id {get; set; }
public string Name {get; set; }
public string SomeOtherProperty { get; set; }
}
public static SelectList ToSelectList<T>(List<T> addlist) where T : IEntity, new ()
{
addlist.Insert(0, new T { Id = -1, Name = "SELECT" });
var list = new SelectList(addlist, "Id", "Name");
return list;
}
// In your code
List<Widget> widgetList = new List<Widget>();
ToSelectList(widgetList);
The problem with your code is that you do not know what T
is and what properties it has. new
is not enough as your generic constraint. All it specifies it:
The new constraint specifies that any type argument in a generic class declaration must have a public parameterless constructor
If you want to go and just instantiate an object of type T
then see: Create instance of generic type? .
But what might be better is just to create an interface with those properties, specify that your function gets a list of that type and then just instantiate an object of that type:
public static SelectList ToSelectList(List<YourInterface> addlist)
{
addlist.Insert(0, new YourDerived { Id = -1, Name = "SELECT" });
var list = new SelectList(addlist, "Id", "Name");
return list;
}
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.