Search code examples
c#interfacenestedoverridingaccess-levels

Overriding operators within nested internal classes


I need to override the Equals operator (and therefore, the GetHashcode method) in a nested class whose accessibility is internal.

When I try to do this, the compiler complains that I can't override Equals - a public member - with a private method. But I can't make the override public, because the class itself is internal, and nested.

How does one do this? How can I override Equals and GetHashcode in a class that is not public (and in fact, is nested and internal)?


Solution

  • I'm not sure why it works, though.

    This behavior is defined in § 3.5.2 of the C# specification:

    The accessibility domain of a nested member M declared in a type T within a program P is defined as follows (noting that M itself may possibly be a type): [...]

    • If the declared accessibility of M is internal, the accessibility domain of M is the intersection of the accessibility domain of T with the program text of P.

    This provision requires that for a class with internal accessibility, type members may be equivalently marked either as public or as internal.

    You can't have a member whose access level is higher than it's containing class?

    This is accurate; the same section of the specification states that "the accessibility domain of a member is never more inclusive than the accessibility domain of the type in which the member is declared". It is important to recognize that although the language allows a member of a type with internal accessibility to be declared as public, it will still have internal accessibility (as if it were declared as internal).

    In other words, in the below segment, the accessibility of X is equivalent in both lines:

    internal class A {public void X() {}}
    internal class A {internal void X() {}}