Edit

Share via


Nested types (C# programming guide)

A nested type is a type that you define within a class, struct, or interface. For example:

public class Container
{
    class Nested
    {
        Nested() { }
    }
}

Regardless of whether the outer type is a class, interface, or struct, nested types default to private. You can access them only from their containing type. In the preceding example, external types can't access the Nested class.

You can also specify an access modifier to define the accessibility of a nested type, as follows:

The following example makes the Nested class public:

public class Container
{
    public class Nested
    {
        Nested() { }
    }
}

The nested, or inner, type can access the containing, or outer, type. To access the containing type, pass it as an argument to the constructor of the nested type. For example:

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

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

A nested type has access to all of the members that are accessible to its containing type. It can access private and protected members of the containing type, including any inherited protected members.

In the previous declaration, the full name of class Nested is Container.Nested. This is the name used to create a new instance of the nested class, as follows:

Container.Nested nest = new Container.Nested();

See also