views:

1657

answers:

2

How can I use reflection to create a generic List with a custom class (List<CustomClass>)? I need to be able to add values and use propertyInfo.SetValue(..., ..., ...) to store it. Would I be better off storing these List<>'s as some other data structure?

Edit:

I should have specified that the object is more like this, but Marc Gravell's answer works still.

class Foo
{
    public List<string> Bar { get; set; }
}
+2  A: 

Here's an example of taking the List<> type and turning it into List<string>.

var list = typeof(List<>).MakeGenericType(typeof(string));

Neil Whitaker
That doesn't give you a list of any kind - it gives you a Type
Marc Gravell
+5  A: 
class Foo
{
    public string Bar { get; set; }
}
class Program
{
    static void Main()
    {
        Type type = typeof(Foo); // possibly from a string
        IList list = (IList) Activator.CreateInstance(
            typeof(List<>).MakeGenericType(type));

        object obj = Activator.CreateInstance(type);
        type.GetProperty("Bar").SetValue(obj, "abc", null);
        list.Add(obj);
    }
}
Marc Gravell
what if i haveclass Foo{ public List<Bar> bars {get; set;}}class Bar{public byte Id { get; set; }public byte Status { get; set; }public byte Type { get; set; }public Bar(){}}I instantiate foo using reflection, activator.createinstance(). Now I need to populate that list of bars with Bar objects.
towps
should the code you have there compile? I'm told that I still need to supply the declaration of the IList with a type... IList<typeof(type)> or something, I don't know?
towps
I can do var list = Activator.CreateInstance(typeof(List<>).MakeGenericType(GetListType(p.ParameterType)));But I don't seem to get a list in return since list doesn't seem to have an Add method...
towps
missing using system.collection;
towps
For brevity, it isn't uncommon to omit the `using` declarations.
Marc Gravell