Using Reflection to set a Property with a type of List<CustomClass>

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

Answers


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

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

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


Need Your Help

GKTurnBasedMatch push notifications are very inconsistent

iphone ios push-notification game-center gkturnbasedmatch

I'm testing a turn based game between two devices. As far as I understand, sending a turn with [GKTurnBasedMatch endTurnWithNextParticipants:], for example, should automatically push a game center

Java SuperClass over writing subclass variables

java inheritance global-variables

I have a project that involves creating objects of varying types that inherit methods and variables from a super class, but when I try to change the variable in the subclass (to a value inputted th...