Question

In Java, i like to use constructs such as

List<String> list = new ArrayList<String>() {{add("foo");}};

Is there a way to do this in 1 line in C#, too?

Was it helpful?

Solution

I think what you want is an array initializer

List<string> list = new List<string>() { "foo" };

Multiple items should be comma-separated

List<string> list = new List<string>() { "foo","bar","bas"};

OTHER TIPS

This is called a collection initializer and it's part of C# 3.0.

As well as lists, you can initialize collections of more complicated types, so long as they implement IEnumerable and have approprate Add methods for each element in the collection initializer. For example, you can use the Add(key, value) method of Dictionary<TKey, TValue> like this:

var dict = new Dictionary<string, int> 
{ 
    {"first", 10 }, 
    {"second", 20 }
};

More details can be found in chapter 8 of C# in Depth, which can be downloaded free from Manning's web site.

You can do it in .NET 3.5 to set property values:

List<string> list = new List<string> () { Property = Value, Property2 = Value2 };

Or to initialize an array:

List<string> list = new List<string> () { "value1", "value2" };

You can't call methods this way, however.

If you just need to deal with adding objects to a collection, then collection initializers work great, but if you need more static initialization to be performed, you can use something called a static constructor that works the same as a static initializer in java

This has poor formatting but seems to cover it

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