So why create a nested class?
I can think of couple of important reasons:
1. Enable encapsulation
Many times nested classes are implementation details of the class. Users of the main class should not have to care about their existence. You should be able to change them at will without requiring the users of the main class to change their code.
2. Avoid name pollution
You should not add types, variables, functions, etc. in a scope unless they are appropriate in that scope. This is slighly different than encapsulation. It could be useful to expose the interface of a nested type but the proper place for the nested type is still the main class. In C++ land, iterator types are one such example. I am not experienced in C# enough to give you concrete examples in it.
Let's make up a simplistic example to illustrate why moving a nested class to the same scope as the main class is name pollution. Let's say you are implementing a linked list class. Normally, you would use
publid class LinkedList
{
class Node { ... }
// Use Node to implement the LinkedList class.
}
If you decide to move Node
up to the same scope as LinkedList
, you will have
public class LinkedListNode
{
}
public class LinkedList
{
// Use LinkedListNode to implement the class
}
LinkedListNode
is unlikely to be useful without LinkedList
class itself. Even if LinkedList
provided some functions that returnd a LinkedListNode
object that a user of LinkedList
could use, it still makes LinkedListNode
useful only when LinkedList
is used. For that reason, making the "node" class a peer class of LinkedList
is polluting the containing scope.