Round brackets or not? Whats the difference?

喜你入骨 提交于 2019-12-06 02:15:42

As far as I know, they're exactly equivalent. The C# specification (or at least Microsoft's implementation of it) allows you to omit the () when using the default constructor (no parameters) as long as you're using curly brackets (i.e. the syntax for object initialisers). Note that the object initializer makes no difference to the constructor here - the new MyClass bit still gets interpreted separately as a call to the default constructor. Personally, I would recommend you always include the round brackets () for consistency - you need them when you don't have an object initializer following.

There is no difference, first form just points out that you are also calling the constructor:

class Ö {
    public string Ä { get; set; }
    public string Å { get; set; }
    public Ö() { Å = "dear";}
    public Ö(string å) { Å = å; }    
}

Console.WriteLine(new Ö { Ä = "hello" }.Å);
Console.WriteLine(new Ö("world") { Ä = "hello" }.Å);

will result in:

dear
world

To add to the above comments, adding extra's definitely help to clarify what constructor or init method is being called. Definitely a styling aspect also....

I guess they retain the () form for object initializers because some users like the clarity of () for invoking the constructor, but iirc, C++ (or the first versions) allow invoking constructor without the parentheses. My second guess, they(language designers) are leaning to make C# have JSON-like structure, which is kinda neat, so they facilitate invoking constructor without the (). I favor the second form.

There's no difference, just like the property(though so bad) of VB.NET would allow you to assign variables in two forms: button1.Height = 100 button1.Height() = 1000 Kinda lame, if you may ask.

Actually they don't have much difference until you deal with Types that don't have default empty constructor. In such a case you can get benefit writing something like "new SomeClass(MandatoryArgument) { Prop1 = 1, Prop2 = 2 }"

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