Search code examples
c#javastatic-initializerstatic-initialization

Collection Initializers in C#


In Java, I can create an List and immediately populate it using a static initializer. Something like this:


List <String> list = new ArrayList<String>()
{{
    Add("a");
    Add("b");
    Add("c");
}}

Which is convenient, because I can create the list on the fly, and pass it as an argument into a function. Something like this:


printList(new ArrayList<String>()
{{
    Add("a");
    Add("b");
    Add("c");
}});

I am new to C# and trying to figure out how to do this, but am coming up empty. Is this possible in C#? And if so, how can it be done?


Solution

  • You can use a collection initializer:

    new List<string> { "a", "b", "c" }
    

    This compiles to a sequence of calls to the Add method.
    If the Add method takes multiple arguments (eg, a dictionary), you'll need to wrap each call in a separate pair of braces:

    new Dictionary<string, Exception> {
        { "a", new InvalidProgramException() },
        { "b", null },
        { "c", new BadImageFormatException() }
    }