C# – When and Why to Use Nested Classes

cclass-designnetobject-orientedprogramming practices

Using Object Oriented Programming we have the power to create a class inside a class (a nested class), but I have never created a nested class in my 4 years of coding experience.
What are nested classes good for?

I know that a class can be marked as private if it is nested and that we can access all private members of that class from the containing class.
We could just put the variables as private in the containing class itself.
So why create a nested class?

In which scenarios should nested classes be used or are they more powerful in terms of usage over other techniques?

Best Answer

The main feature of nested classes is that they can access private members of the outer class while having the full power of a class itself. Also they can be private which allows for some pretty powerfull encapsulation in certain circumstances:

Here we lock the setter completely down to the factory since the class is private no consumer can downcast it and access the setter, and we can control completely what is allowed.

public interface IFoo 
{
    int Foo{get;}      
}
public class Factory
{
    private class MyFoo : IFoo
    {
        public int Foo{get;set;}
    }
    public IFoo CreateFoo(int value) => new MyFoo{Foo = value};
}

Other than that it is useful for implementing third-party interfaces in a controlled environment where we can still access private members.

If we for example were to provide an instance of some interface to some other object but we don't want our main class to implement it we could let an inner class implement it.

public class Outer
{
    private int _example;
    private class Inner : ISomeInterface
    {
        Outer _outer;
        public Inner(Outer outer){_outer = outer;}
        public int DoStuff() => _outer._example;
    }
    public void DoStuff(){_someDependency.DoBar(new Inner(this)); }
}
Related Topic