3

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

Cardinal Fang
  • 283
  • 2
  • 12
  • Can you post code what you have tried – Gun Jun 29 '14 at 03:46
  • Not easily. I'm hoping this question is general enough to have a general answer, like "you need to create an explicit implementation of the interface of..." – Cardinal Fang Jun 29 '14 at 03:49
  • "But I can't make the override public, because the class itself is internal, and nested" - why? Have you tried? – Alexei Levenkov Jun 29 '14 at 03:50
  • Wow. While trying to write sample code, I did try, and it does work! I'm not sure why it works, though. Ordinarily, you can't have a public member in an internal class, right? You can't have a member whose access level is higher than it's containing class? At any rate - I'm happy now! I can't answer the question or vote, though, cuz I just created my account. – Cardinal Fang Jun 29 '14 at 04:04

1 Answers1

3

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() {}}
drf
  • 8,461
  • 32
  • 50