Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 203
bayCoder Avatar asked Sep 25 '11 10:09

bayCoder


People also ask

Can nested classes be inherited?

A static nested class can inherit: an ordinary class. a static nested class that is declared in an outer class or its ancestors.

What is nested class in C?

A nested class is declared within the scope of another class. The name of a nested class is local to its enclosing class.

Can we create nested classes in C?

Master C and Embedded C Programming- Learn as you goA nested class is a class that is declared in another class. The nested class is also a member variable of the enclosing class and has the same access rights as the other members.


2 Answers

Inheriting from a parent class does not allow a nested class to see its parent's private members and methods, only protected (and public) ones. Nesting it within the parent class lets it see all private members and invoke its private methods, whether the nested class inherits from the parent class or not.

like image 100
BoltClock Avatar answered Sep 24 '22 10:09

BoltClock


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.

like image 45
yas4891 Avatar answered Sep 25 '22 10:09

yas4891