Search code examples
c#inheritancenested-class

Inheritance + NestedClasses in C#


We can have nested classes in C#. These nested classes can inherit the OuterClass as well. For ex:

public class OuterClass
{
  // code here
  public class NestedClass : OuterClass
  {
    // code here
  }
}

is completely acceptable.

We can also achieve this without making NestedClass as nested class to OuterClass as below:

public class OuterClass
{
  // code here
}

public class NestedClass : OuterClass
{
  // code here
}

I am wondering, what is the difference between above two scenarioes? What is achievable in scenario I which can't be achievable in scenario II? Is there anything that we get more by making NestedClass "nested" to OuterClasss?


Solution

  • the second example you provided is not a nested class, but a normal class that derives from OuterClass.

    • nested types default to private visibility, but can be declared with a wider visibility
    • nested types can access properties, fields and methods of the containing type (even those declared private and those inherited from base types)

    also take a look at this question here on when and why to use nested classes.
    MSDN link : Nested Types (C# Programming Guide)

    EDIT
    To address @Henk's comment about the difference in nature of the both relations (inheritance vs. nested types): In both cases you have a relation between the two classes, but they are of a different nature. When deriving from a base class the derived class inherits all (except private) methods, properties and fields of the base class. This is not true for nested class. Nested classes don't inherit anything, but have access to everything in the containing class - even private fields, properties and methods.