Question

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?

Was it helpful?

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() }
}

OTHER TIPS

Since C# 3.0 you can do it as well:

List <String> list = new List<String>
                     {
                             "a", "b", "c"
                     };

MSDN, Collection Initializers

Collection initializers let you specify one or more element intializers when you initialize a collection class that implements IEnumerable. The element initializers can be a simple value, an expression or an object initializer. By using a collection initializer you do not have to specify multiple calls to the Add method of the class in your source code; the compiler adds the calls.

EDIT: Answer to comment regarding dictionary

IDictionary<string, string> map = new Dictionary<string, string>
{
   { "Key0", "Value0" },
   { "Key1", "Value1" }
};

Yes, it's described on MSDN here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top