Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing list inline

Tags:

c#

I'm getting a weird error when doing this: (.net 2.0)

public overrides List<String> getSpaceballs {     get { return new List<String>() { "abc","def","egh" }; } } 

VS is asking for ; after (). Why?

I sure can do this:

public overrides string[] getSpaceballs {     get { return new string[] { "abc","def","egh" }; } } 
like image 299
John Avatar asked Jan 07 '10 13:01

John


People also ask

How do you initialize a list in one line in Java?

List<String> list = List. of("foo", "bar", "baz"); Set<String> set = Set. of("foo", "bar", "baz");

How do you initialize a list in C#?

List<string> myList = new List<string>() { "one", "two", "three", };


1 Answers

C#'s collection initialization syntax is only supported in versions 3 and up (since you mentioned .NET 2.0 I am going to assume you are also using C# 2). It can be a bit confusing since C# has always supported a similar syntax for array initialization but it is not really the same thing.

Collection initializers are a compiler trick that allows you to create and initialize a collection in one statement like this:

var list = new List<String> { "foo", "bar" }; 

However this statement is translated by the compiler to this:

List<String> <>g__initLocal0 = new List<String>(); <>g__initLocal0.Add("foo"); <>g__initLocal0.Add("bar"); List<String> list = <>g__initLocal0; 

As you can see, this feature is a bit of syntax sugar that simplifies a pattern into a single expression.

like image 54
Andrew Hare Avatar answered Sep 22 '22 07:09

Andrew Hare