Search code examples
c#constructorobject-initializers

Parenthesis with object initializers


In C#, I can have a class such as:

class MyClass {
  public void DoStuff();
}

I can initialize this class like:

MyClass mc = new MyClass();

Or:

MyClass mc = new MyClass { };

If I don't need the parenthesis, and there are no properties to be set by an object initializer, why can't I do this?

MyClass mc = new MyClass;

Solution

  • You cannot do MyClass mc = new MyClass because designers of the parser for the language decided not to allow you to do that. In fact, they were rather generous for allowing an empty pair of curly braces: I guess it was easier for them to take that route than explicitly asking for at least one expression.

    There is nothing inherent in the structure of the new expression that you are proposing that would prohibit such syntax: modifying a parser to support the third alternative would not take much effort. However, doing so would create an inconsistency with calling non-constructor methods that have no arguments. Currently, omitting parentheses makes them method groups with specific semantic enabled in certain contexts. It would be hard to modify the parser to allow no-argument method calls without parentheses, because there would be no syntactic marker for it (note that when you call the constructor, the new keyword plays a role of such a marker).