3

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


List &ltString&gt list = new ArrayList&ltString&gt()
{{
    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&ltString&gt()
{{
    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?

Nick
  • 1,417
  • 1
  • 14
  • 21
user489041
  • 27,916
  • 55
  • 135
  • 204
  • this isn't a "[static initializer](http://download.oracle.com/javase/tutorial/java/javaOO/initial.html)" - it's an instance initializer – matt b Oct 24 '11 at 20:55

3 Answers3

8

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() }
}
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • @user489041 : you can initialize Dictionary as well, see an example in my answer below – sll Oct 24 '11 at 20:44
2

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" }
};
sll
  • 61,540
  • 22
  • 104
  • 156
1

Yes, it's described on MSDN here

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720