Why Would I Ever Need to Use C# Nested Classes

Why Would I Ever Need to Use C# Nested Classes [duplicate]

A pattern that I particularly like is to combine nested classes with the factory pattern:

public abstract class BankAccount
{
  private BankAccount() {} // prevent third-party subclassing.
  private sealed class SavingsAccount : BankAccount { ... }
  private sealed class ChequingAccount : BankAccount { ... }
  public static BankAccount MakeSavingAccount() { ... }
  public static BankAccount MakeChequingAccount() { ... }
}

By nesting the classes like this, I make it impossible for third parties to create their own subclasses. I have complete control over all the code that runs in any bankaccount object. And all my subclasses can share implementation details via the base class.

 

c# Public Nested Classes or Better Option? 

The contents of a class should be the implementation details of that class. Are the nested classes implementation details of the outer class, or are you merely using the outer class as a convenient name scoping and discovery mechanism?

If the former, then you shouldn't be making the private implementation details publically available. Make them private if they are implementation details of the class.

If the latter, then you should be using namespaces, not outer classes, as your scoping and discovery mechanism.

Either way, public nested classes are a bad code smell. I'd want to have a very good reason to expose a nested class.

 

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.

 

 

 

 

 

 

 

上一篇:LeanCloud在Android studio中SDK的安装与连接


下一篇:linux之四层负载均衡