Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top