Ra3IDeN Ra3IDeN - 25 days ago 8
ASP.NET (C#) Question

How to add items of generic type to list?

Should be relativly simple but I cant figure it out, i have the following:

public static List<T> GetList <T>(dynamic data)
{
var lst = new List<T>();

foreach (var d in data)
{
lst.Add(new T { Value = d.Id.ToString(), Text = d.Name };);
}

return lst;
}


errror:

enter image description here

Answer

You constrained your type to T but provided no additional constraints on that type. The compiler cannot know there exists a property Value or Text. You could use an interface and then constrain on that type. The type you pass in when you call the method must also implement that interface.

public interface ITextValue{
   string Text {get;set;}
   string Value {get;set;}
}

And then the code with the added constraint

public static List<T> GetList <T>(dynamic data) where T : ITextValue, new()
{
    var lst = new List<T>();

    foreach (var d in data)
    {
        lst.Add(new T { Value = d.Id.ToString(), Text = d.Name });
    }

    return lst;
}

Here is a good link on all of the available constraints and syntax for those constraints that you can apply to generic type parameters. Constraints on Type Parameters (C# Programming Guide). And along with what @juan pointed out the new() constraint specifies that the type you use must have a parameterless constructor.