I read a bit too much about nested classes and now I’m confused: In his answer to this older Question, Eric Lippert mentions that we should use nested classes only if it acts as an implementation detail of the outer class and not for name scoping and discovery mechanism. Now let me provide a sample usage that I probably think is wrong as per the guideline provided by Eric, I need some assistance in understanding why it’s wrong.
public class Graph
{
private List<Edge> edges = new List<Edge>();
private HashSet<string> nodes = new HashSet<string>();
public void AddEdge(string fromNode, string toNode)
{
edges.Add(new Edge(fromNode, toNode));
}
// Nested class
private class Edge
{
public string FromNode { get; }
public string ToNode { get; }
}
}
In the above example, the Edge class looks as though it’s an implementation detail of the outer class on the surface, which I don’t think is true. Why I say so is because Class Edge can exist elsewhere and the code will work fine. Aren’t we just scoping the class that case? So what exactly is an “implementation detail” ? I guess public methods aren’t “implementation details” are we talking about the methods that dictate behaviors of the classes? If yes ,I still don’t see why it should be within the same class if it can exist elsewhere and can be referenced here. The only implementation in which this pattern makes sense is in the builder pattern given below where the nested class must exist within the outer class for it to have the expected behaviour.
public class Outer
{
private Outer(Builder builder)
{
// Copy stuff
}
public class Builder
{
public Outer Build()
{
return new Outer(this);
}
}
}