开发者

Why Are Parentheses Required on C# Static Constructors?

开发者 https://www.devze.com 2023-03-07 12:35 出处:网络
Consider: class Foo { static Foo() { // Static initialisation } } Why are the () required in static Foo() {...}? The static constructor must always be parameterless, so why bother? Are they necessa

Consider:

class Foo
{
    static Foo()
    {
        // Static initialisation
    }
}

Why are the () required in static Foo() {...}? The static constructor must always be parameterless, so why bother? Are they necessary to avoid some parser ambiguity, or is it just to maintain consistency with regular parameterless constructors?

Since it looks so much like an initial开发者_如何学编程iser block, I often find myself leaving them out by accident and then have to think for a few seconds about what is wrong. It would be nice if they could be elided in the same way.


Because it's a static constructor, so it's static + a normal-looking constructor.

Consistency is key. :-)


I get this sort of question frequently; that is, the question "the compiler could work out that this thing is missing, so why is it required?" Here's another example of this sort of question:

C# using consts in static classes

As I noted in that question, basically we have three choices in that situation. Make the redundant text required, make it optional, or make it illegal.

Each has its own downside.

The downside of making it required is you end up with an unnecessary redundancy in the language.

The downside of making it optional is you confuse people who think there must be a difference between the two forms. Also, you make it harder for the error-recovering parser to do its work; it thrives on redundancy. And you potentially make it harder to add new language features in the future, because more "syntactic area" is already claimed.

The downside of making it illegal is you then make a "gotcha", where the user has to remember that oh, yeah, I'm supposed to put parens here, but not here.

The proposed feature had better have an upside that pays for the downside. The smallest downside seems to me to be the first: make it required. The other options I would want to have an upside that justifies the downside, and I'm not seeing one here.


I would assume it's for disambiguity: it makes the parser's job easier, recognising the code block as a constructor subroutine (irrespective of staticness); and conversely it helps ensure that the human author/maintainer is aware of the implications of choosing this particular construct, by forcing them to use a specific method-like syntax.

0

精彩评论

暂无评论...
验证码 换一张
取 消