Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

c# - Inline property initialisation and trailing comma

void Main()
{
    Test t = new Test
    {
        A = "a",
        B = "b", // <-- erroneous trailing comma
    };
}

public class Test
{
    public string A { get; set; }
    public string B { get; set; }
}

I find the above typo in my code quite a lot. I'm always suprised that the compiler doesn't seem to care about this. Why is the above not a syntax errror? Is there any actually valid use for it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I find the above typo in my code quite a lot. I'm always suprised that the compiler doesn't seem to care about this. Why is the above not a syntax errror?

Because the people designing the C# syntax grammar were smart enough to learn the lessons from other programming languages which didn't allow the dangling comma, to the constant irritation of programmers in those languages.

For example, ECMAScript (JavaScript) was silent on the issue initially, and so naturally some implementations (SpiderMonkey in Firefox, Opera's JavaScript, etc.) allowed them while others (Microsoft's JScript) didn't. And so this led to a spate of "why doesn't this work in IE" questions here and elsewhere. (Fortunately, ECMAScript 5 explicitly allows them, and IE8 finally supports them in object initializers -- IE8 still treats array initializers in a non-standard way, though to be fair the dangling comma for those was only clarified in ECMAScript 5, too.)

You find this in lots of other places in the C# grammar too, like enums and array initializers.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...