Nested Enum and Property Naming Conflicts

后端 未结 7 835
孤城傲影
孤城傲影 2021-02-06 23:48

There are some related questions here and here, but they didn\'t really give me satisfactory answers. The problem is that enums nested in a class in C# cannot have the same name

7条回答
  •  梦谈多话
    2021-02-07 00:05

    It would also be nice to know why this is disallowed. Maybe Eric Lippert or someone could chime in on the decision to forbid it?

    The point of the rule is to ensure that there is no ambiguity within the class when looking up a name. Certain regions of code are designated as defining a 'declaration space'. The fundamental rule of declaration spaces is no two things declared in the same declaration space have the same name (except for methods, which must differ by signature, not name.)

    Making exceptions to this rule just makes things more confusing, not less confusing. I agree that it is vexing that you cannot have a property and an enum of the same name declared in the same declaration space, but once you start making exceptions then it just gets to be a mess. It's usually a nice property that a name uniquely identifies a method group, type parameter, property, and so on.

    Note that this rule applies to things declared in a declaration space, not things used in a declaration space. It is perfectly legal to say "public Suit Suit { get; set; }" provided that the type Suit is not declared in the same declaration space as the property. When someone says "Suit.X", figuring out whether X is on the type (that is, X is a static member) or the property (that is, X is an instance member) is a bit tricky. See my article on how we do that for details:

    http://blogs.msdn.com/ericlippert/archive/2009/07/06/color-color.aspx

提交回复
热议问题