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?
-
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.
Jon Skeet : You can do this in .NET 2.0 as well, if you're using C# 3.0.Kyle Trauberman : Good to know. :) -
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"};Jon Skeet : Note that if you're calling the parameterless constructor you don't need the () part. Just new List{ "hello", "there" } works fine. Chry Cheng : -1. Answer did not mention that this is available only from C# 3.0 onwards. -
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 ofDictionary<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.
serg10 : 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!David B : @serg10 you used all the saved keystrokes typing comments on StackOverFlow - no early retirement for you! -
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
0 comments:
Post a Comment