views:

1201

answers:

4

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?

+2  A: 

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.

Kyle Trauberman
You can do this in .NET 2.0 as well, if you're using C# 3.0.
Jon Skeet
Good to know. :)
Kyle Trauberman
+4  A: 

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"};
ckramer
Note that if you're calling the parameterless constructor you don't need the () part. Just new List<string> { "hello", "there" } works fine.
Jon Skeet
-1. Answer did not mention that this is available only from C# 3.0 onwards.
Chry Cheng
+7  A: 

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.

Jon Skeet
This is the best of the answers as it uses var - just think of the keystrokes you can save over your career by letting type inference take care of the left hand side. You could retire early!
serg10
@serg10 you used all the saved keystrokes typing comments on StackOverFlow - no early retirement for you!
David B
A: 

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

Michael Walts