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

207 views Asked by At
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?

3

There are 3 answers

2
Konrad Kokosa On BEST ANSWER

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;
}
2
Kell On

What Asad said, but if you want a generic method to get a list, I would propose calling it GetList and doing the following (notice that adding is done in a lambda so you can add whatever you want or provide a function to do so):

private void Call()
        {
            List<int> numbers = GetList<int>(l =>
            {
                l.Add(1);
                l.Add(2);
                //etc
            });
            MessageBox.Show("Numbers amount " + numbers.Count);
        }

        private List<T> GetList<T>(Action<List<T>> initList)
        {
            List<T> list = Activator.CreateInstance<List<T>>();
            initList(list);
            return list;
        }
0
Asad Saeeduddin On

If your T is always supposed to have the ability to add integers, what you're essentially saying is it implements ICollection<int>. Once you add ICollection<int> as a type constraint, you should be able to do this pretty easily:

private T Get<T>() where T: ICollection<int>, new
{
    T coll = new T();
    int a = 1;

    coll.Add(a);
    return coll;
}

As mentioned in the comments, you can also avoid Activator.CreateInstance since you don't need any constructor arguments.

Now you can use:

var myList = Get<List<int>>();
Console.WriteLine(myList.Count); // Should be 1

Here is a demonstration: http://ideone.com/0pjFoJ