Вопрос

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;
Это было полезно?

Решение

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

Другие советы

Because the syntax new MyClass { } is the new parameter-less constructor syntax, that's why you can omit the (). The constructor method public MyClass() is called by inference.

But, this syntax new MyClass is just bad because the compiler doesn't accept it as valid.

It's not that they couldn't do it, they can do just about anything with the compiler, but they aren't doing it.

Consider this:

public class MyClass {

    public int Value { get; private set; }

    public MyClass With(int i) {
        Value = i;
        return this;
    }
}

MyClass my = new MyClass().With(5);    // Old-school
MyClass my1 = new MyClass { }.With(6); // Kind of funky looking, but okay.
MyClass my2 = new MyClass.With(4);     // This looks just like a static method call except for the new

Because MyClass is the class name/type and MyClass() is the constructor; the one you need (want) to call is the constructor.

This is because you are calling your default constructor for the object to be initialized. That's why, you use:

MyClass mc = new MyClass();

You can try, if there doesn't a default constructor (which takes zero number of arguments) exist, this line will give an error, saying something like, 'no default constructor exists'.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top