Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collection Initializers in C#

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?

like image 882
user489041 Avatar asked Apr 30 '26 06:04

user489041


1 Answers

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() }
}
like image 76
SLaks Avatar answered May 02 '26 21:05

SLaks