Search code examples
c#asp.netclassconventions

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


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.