While expressing concern with preventing exposure of base classes, I learned (through testing) that a public
class cannot inherit from an internal
class; however, a public
class can inherit from an internal
interface. I am truly curious as to why this is possible. I believe it could be due to one of (or any combination of) the following:
- An interface simply contains signatures that must be implemented.
- A class may have properties, methods, etc. that can be accessed via the derived type.
- A class may have methods that can be overridden by derived types.
Case 1
I believe that since an interface is simply a contract that contains signatures and states that derived types must implement those signatures, the inheritance is allowed. This is due to the fact that the interface doesn't care who accesses these signatures, only that the derived type implements them.
Case 2 and 3
Unlike interfaces
, classes can have public
properties that can be accessed by derived types. For example:
private class A {
public int SomeProperty { get; set; } = 0;
}
public class B : A {
// Some cool code.
}
public class C : B {
public int MyInt => SomeProperty;
}
This structure has inconsistent accessibility since SomeProperty
is public
and can be accessed by all derived types; thus A
and B
must have the same access levels to prevent exposure.
Is this the reason why a public
class can derive from an internal interface
but not a internal class
, or am I missing something? Also, are there any other reasons why this is possible?
Note
I am not looking for an opinion based answer; I am looking for the technically correct reason why this is possible.
This is not a duplicate as I wanted the reason why you can't derive from one, but you can another.