开发者

Initializing list inline

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

public开发者_JAVA技巧 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" }; }
}


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.


As the other users point out, that is not supported in 2.0. However, you can mimic it by doing the following.

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

Please note that this creates some computational overhead.


The first option is not legal :)

You can only do that type of initialiser on arrays.

-- Edit: See Andrew Hare's post (and others, below); it is only available in v3 and up.

-- Edit again:

Just to be clear, if your compiler is of 3 or greater, you can target 2.0, to get this to work (because it's compiled down to the code that Andrew shows, below). But if your compiler is 2, then you can't.


Just in case anyone would search for it as well nowadays, there is a neat way to do that using LINQ extensions. Hope it helps someone ;)

var list = new string[]{ "1", "2", "3" }.ToList();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜