Why/when should you use nested classes in .net? Or shouldn't you?
Use a nested class when the class you are nesting is only useful to the enclosing class. For instance, nested classes allow you to write something like (simplified):
public class SortedMap {
private class TreeNode {
TreeNode left;
TreeNode right;
}
}
You can make a complete definition of your class in one place, you don't have to jump through any PIMPL hoops to define how your class works, and the outside world doesn't need to see anything of your implementation.
If the TreeNode class was external, you would either have to make all the fields public
or make a bunch of get/set
methods to use it. The outside world would have another class polluting their intellisense.
From Sun's Java Tutorial:
Why Use Nested Classes? There are several compelling reasons for using nested classes, among them:
- It is a way of logically grouping classes that are only used in one place.
- It increases encapsulation.
- Nested classes can lead to more readable and maintainable code.
Logical grouping of classes—If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.
Increased encapsulation—Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world. <- This doesn't apply to C#'s implementation of nested classes, this only applies to Java.
More readable, maintainable code—Nesting small classes within top-level classes places the code closer to where it is used.
Fully Lazy and thread-safe singleton pattern
public sealed class Singleton
{
Singleton()
{
}
public static Singleton Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}
source: https://csharpindepth.com/Articles/Singleton