A191919
A191919

Reputation: 3462

Generic function add element to list

I want to replace AddQuickElement and AddRangeElement with one generic function AddElement<T>. But how can i add generic element to List<Base> list. Activator do not work. Or what is better way to make this without reflection?

namespace ConsoleApplication
{
class Program
{
    static void Main(string[] args)
    {
        List<Base> list = new List<Base>();
        AddQuickElement(list,5);
        AddRangeElement(list, 5);
        AddElement<Quick>(list,5);
        Console.WriteLine(list.Count);
        Console.ReadKey();
    }
    public static void AddQuickElement(List<Base> list, int number)
    {
        for (int i = 0; i < number; i++)
        {
            list.Add(new Quick());
        }
    }
    public static void AddRangeElement (List<Base> list, int number)
    {
        for (int i = 0; i < number; i++)
        {
            list.Add(new Range());
        }
    }
    public static void AddElement<T>(List<Base> list, int number)
    {
        Type type = typeof(T);
        var element = Activator.CreateInstance(type);
        // list.Add(element); // do not work
    }
}
public abstract class Base
{

}

public class Quick:Base
{

}

public class Range : Base
{

}
}

Upvotes: 1

Views: 57

Answers (1)

Jakub Lortz
Jakub Lortz

Reputation: 14894

You need to constraint the type parameter to AddElement method

public static void AddElement<T>(List<Base> list, int number) where T : Base, new()
{
    for (int i = 0; i < number; i++)
    {
        list.Add(new T());
    }
}

The type constraints where T : Base, new() mean that the type T

  1. is derived from Base
  2. has a public parameterless constructor.

(1) lets you add an instance of T to a List<Base>, (2) lets you create a new instance of T using new T().

Upvotes: 3

Related Questions