4

See this code:

internal class c 
{
    private int d;
}

public class a : c
{
    private int b;
}

Why can I not inherit a public class from an internal class? Why does the compiler have this behavior?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Yazdan Bayati
  • 184
  • 1
  • 2
  • 6
  • 5
    http://blogs.msdn.com/b/ericlippert/archive/2012/11/13/why-is-deriving-a-public-class-from-an-internal-class-illegal.aspx – SLaks Jul 14 '13 at 11:48
  • 3
    @SLaks: You should probably post this as an answer. – Joey Jul 14 '13 at 11:50

4 Answers4

6

Because the public class would be visible outside your current assembly, while the internal one isn't. When deriving from a class you can only restrict visibility further, because in your case it would make the implementation of c available to consumers outside your assembly which kind of defeats the purpose of making the class internal in the first place.

You can use composition instead of inheritance, though.

Joey
  • 344,408
  • 85
  • 689
  • 683
2

C# design principle. Derived class should atleast have same accessibility as the parent class. In your case it is not hence not allowed. Take a look at Eric Lippert's view on this deriving public class from an internal class

Ehsan
  • 31,833
  • 6
  • 56
  • 65
1

Because "public class" is more "visible" than "internal class".

C# language has visibility protection layer that prevents this.

Aniket Inge
  • 25,375
  • 5
  • 50
  • 78
1

Internal classes can only be accessed from within the Assembly in which they are defined. When public class a inherits from an internal class in effect attempts to make the internal class public.

To avoid this encapsulate the internal class in the public class.

Peter Mourfield
  • 1,885
  • 1
  • 19
  • 38