In Kathleen Dollard's recent blog post, she presents an interesting reason to use nested classes in .net. However, she also mentions that FxCop doesn't like nested classes. I'm assuming that the people writing FxCop rules aren't stupid, so there must be reasoning behind that position, but I haven't been able to find it.
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 static 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.
If I understand Katheleen's article right, she proposes to use nested class to be able to write SomeEntity.Collection instead of EntityCollection< SomeEntity>. In my opinion it's controversial way to save you some typing. I'm pretty sure that in real world application collections will have some difference in implementations, so you will need to create separate class anyway. I think that using class name to limit other class scope is not a good idea. It pollutes intellisense and strengthen dependencies between classes. Using namespaces is a standard way to control classes scope. However I find that usage of nested classes like in @hazzen comment is acceptable unless you have tons of nested classes which is a sign of bad design.
It depends on the usage. I rarely would ever use a Public nested class but use Private nested classes all of the time. A private nested class can be used for a sub-object that is intended to be used only inside the parent. An example of this would be if a HashTable class contains a private Entry object to store data internally only.
If the class is meant to be used by the caller (externally), I generally like making it a separate standalone class.
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.
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();
}
}
I've just started using nested classes to hold test data. It seems pretty natural but I'd be interested if anyone else thinks this is a good idea?
[TestClass]
public class NameQueueTests
{
public class NameQueueTestData
{
public static readonly List<string> nounList = new List<string>()
{
"monkey", "weasel"
};
}
[TestMethod]
public void ctor_CreatesInstance_UsingValidListOfWords()
{
var nameQueue = new NameQueue(NameQueueTestData.nounList);
Assert.IsInstanceOfType(nameQueue, typeof(NameQueue));
}
[TestMethod]
public void GetNext_ReturnsNextInQueue_GivenValidList()
{ ...
}