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?
A static nested class can inherit: an ordinary class. a static nested class that is declared in an outer class or its ancestors.
A nested class is declared within the scope of another class. The name of a nested class is local to its enclosing class.
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.
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.
the second example you provided is not a nested class, but a normal class that derives from OuterClass
.
private
visibility, but can be declared with a wider visibilityprivate
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With