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
- Create an interface which does have
Id
and Name
,
- Modify every compatible class so it implements this interface.
- Add another generic constraint to your function, requiring the type parameter to implement this interface.
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);