Round brackets or not? Whats the difference?

倾然丶 夕夏残阳落幕 提交于 2019-12-22 09:25:02

问题


I've seen these two things lately and I'm a bit confused.

var blah = new MyClass() { Name = "hello" } 

and

var blah = new MyClass { Name = "hello" } 

Whats the difference? and why do they both work?

Update: Does this mean that if i have something in a constructor which does some computation that i would have to call the first one??


回答1:


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.




回答2:


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



回答3:


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....




回答4:


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.




回答5:


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 }"



来源:https://stackoverflow.com/questions/668557/round-brackets-or-not-whats-the-difference

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