Why C# 4.0 tolerates trailing comma in anonymous objects initialization code? [duplicate]

半世苍凉 提交于 2019-12-05 11:52:01

问题


Possible Duplicate:
Inline property initialisation and trailing comma

Working on one of my projects (C# 4.0, Visual Studio 2010), I've accidentally discovered that code like

var obj = new { field1 = "Test", field2 = 3, }

is compiled and executed OK without any errors or even warnings and works exactly like

var obj = new { field1 = "Test", field2 = 3 }

Why does compiler tolerate the trailing coma in first example? Is this a bug in compiler or such behavior does have some purpose?

Thanks


回答1:


To determine whether or not it's a bug in the compiler, you need to look at the C# spec - in this case section 7.6.10.6, which clearly allows it:

anonymous-object-creation-expression:    
    new   anonymous-object-initializer

anonymous-object-initializer:  
    { member-declarator-listopt }  
    { member-declarator-list , }

So no, it's not a compiler bug. The language was deliberately designed to allow it.

Now as for why the language has been designed that way - I believe it's to make it easier to add and remove values when coding. For example:

var obj = new { 
    field1 = "test", 
    field2 = 3,
};

can become

var obj = new { 
    field2 = 3,
};

or

var obj = new { 
    field1 = "test", 
    field2 = 3,
    field3 = 4,
};

solely by adding or removing a line. This makes it simpler to maintain code, and also easier to write code generators.

Note that this is consistent with array initializers, collection initializers and enums:

// These are all valid
string[] array = { "hello", };
List<string> list = new List<string> { "hello", };
enum Foo { Bar, }



回答2:


One reason the trailing commas is good is because of Source Compares. If you update the source and use a source compare tool, then the source compare tool will only show 1 line changed (the new field3. If there was no trailing comma, then source compare will show 2 lines changed because you had to add the comma after the number 3.

var obj = new {
  field1 = "Test",
  field2 = 3,
  }

var obj = new {
  field1 = "Test",
  field2 = 3,
  field3 = "New",
  }



回答3:


To make deleting the last field easier, I suppose. There is really no ambiguity introduced in the syntax by doing this, so it just makes life a bit easier.



来源:https://stackoverflow.com/questions/8253413/why-c-sharp-4-0-tolerates-trailing-comma-in-anonymous-objects-initialization-cod

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!