Schotime
Schotime

Reputation: 15997

Round brackets or not? Whats the difference?

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

Upvotes: 3

Views: 1753

Answers (5)

Denis Vuyka
Denis Vuyka

Reputation: 2865

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

Upvotes: 1

Noldorin
Noldorin

Reputation: 147401

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.

Upvotes: 15

Michael Buen
Michael Buen

Reputation: 39423

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.

Upvotes: 1

Rev316
Rev316

Reputation: 1951

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

Upvotes: 1

Pasi Savolainen
Pasi Savolainen

Reputation: 2500

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

Upvotes: 3

Related Questions