Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 935
Sergey Kudriavtsev Avatar asked Nov 24 '11 07:11

Sergey Kudriavtsev


People also ask

Why is C used?

The C programming language is the recommended language for creating embedded system drivers and applications. The availability of machine-level hardware APIs, as well as the presence of C compilers, dynamic memory allocation, and deterministic resource consumption, make this language the most popular.

Why is C used in C?

%d is used to print decimal(integer) number ,while %c is used to print character . If you try to print a character with %d format the computer will print the ASCII code of the character.

Why should you learn C?

Being a middle-level language, C reduces the gap between the low-level and high-level languages. It can be used for writing operating systems as well as doing application level programming. Helps to understand the fundamentals of Computer Theories.


1 Answers

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, }
like image 162
Jon Skeet Avatar answered Jan 16 '23 02:01

Jon Skeet