Nested Types

Type defined within class or struct which defaults to private as are called nested types. The access modifiers for nested types can be : public, protected, internal, protected internal, private, private proteted.

Nested types of a struct can be public, internal, or private.

class OuterClass
{
	class InnerClass
	{
	  Nested () {}
	}
}

The nested, or inner, type can access the containing, or outer, type.

public class Container
{
    public class Nested
    {
        private Container parent;

        public Nested()
        {
        }
        public Nested(Container parent)
        {
            this.parent = parent;
        }
    }
}
Container.Nested nest = new Container.Nested();

It is better approach 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() { ... }
}

Complete control over all the code that runs in any bankaccount object.

Guidelines when not to use nested types:

  • If the type needs to be instantiated by client code then do not use nested types
  • If the type has public constructor
  • Inner type should not be widely used outside
  • References to the type are commonly declared in client code.

Leave a Reply

Your email address will not be published. Required fields are marked *