views:

335

answers:

5

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

+13  A: 

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.

Noldorin
+1 because you mentioned that this is the "object initialiser" feature whichis btw new in C# 3.0.Here's a link http://weblogs.asp.net/dwahlin/archive/2007/09/09/c-3-0-features-object-initializers.aspx
J M
+2  A: 

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
Pasi Savolainen
I just had an Ikea flashback.
Wouter van Nifterick
A: 

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

Rev316
A: 

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.

Michael Buen
A: 

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

Denis Vuyka