Initializing a Generic.List in C#

This is called a collection initializer. It’s calling the parameterless constructor, and then calling Add:

List<int> tmp = new List<int>();
tmp.Add(1);
tmp.Add(2);
tmp.Add(3);
List<int> intList = tmp;

The requirements for the type are:

  • It implements IEnumerable
  • It has overloads of Add which are appropriate for the argument types you supply. You can supply multiple arguments in braces, in which case the compiler looks for an Add method with multiple parameters.

For example:

public class DummyCollection : IEnumerable
{
    IEnumerator IEnumerable.GetEnumerator()
    {
        throw new InvalidOperationException("Not a real collection!");
    }

    public void Add(string x)
    {
        Console.WriteLine("Called Add(string)");
    }

    public void Add(int x, int y)
    {
        Console.WriteLine("Called Add(int, int)");
    }
}

You can then use:

DummyCollection foo = new DummyCollection
{
    "Hi",
    "There",
    { 1, 2 }
};

(Of course, normally you’d want your collection to implement IEnumerable properly…)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)