Search code examples
c#listgenericscreateinstance

Add items to a list of objects, where the list itself is of type T


private void Call()
{
    List<int> numbers= Get<List<int>>();
    MessageBox.Show("Numbers amount " + numbers.Count);
}

private T Get<T>() 
{
    T list = Activator.CreateInstance<T>();
    int a = 1;
    //HOW TO ADD "A" TO THE T-object [which is a list...]?
    return list;
}

Is it possible to let "T" be a List? I mean, it is possible (it compiles), but how do you add an object to these kind of lists?


Solution

  • I believe you want:

    private static T Get<T>() where T : IList
    {
        T list = Activator.CreateInstance<T>(); 
        int a = 1;
        (list as IList).Add(a);
        return list;
    }