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
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.
%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.
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.
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, }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With