Skip to main content

How to Use a Nested Type in C#

· 8 min read
Jagdish Kumawat
Founder @ Dewiride

A nested type is a class, an enum or any other type declared inside another type. Outside its containing class you write its full name, Coffee.Size; inside, the short name Size is enough.

Microsoft's programming guide: A nested type is a type that you define within a class, struct, or interface. And when to use one: Use nesting when a type is usually needed only in the context of its containing type. The containing type's name becomes part of the nested type's name. The guide's example: the full name of class Nested is Container.Nested. This is the name used to create a new instance of the nested class.

Syntax​

Syntax
class <Outer>
{
public enum <InnerEnum> { <Value1>, <Value2> }

public class <InnerClass>
{
// members
}
}

// Outside <Outer>:
<Outer>.<InnerEnum> <name> = <Outer>.<InnerEnum>.<Value1>;
<Outer>.<InnerClass> <other> = new <Outer>.<InnerClass>();
PartWhat it is
<Outer>The containing type: a class, struct or interface
<InnerEnum>, <InnerClass>Types declared inside its braces, here an enum and a class
publicLets code outside <Outer> use the nested type
<Outer>.<InnerClass>The nested type's name outside <Outer>. Inside <Outer>, the short name <InnerClass> works

Leave out public and only the containing type can use it. The guide: 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.

The Example​

A console app called NestedType has a Coffee class with two nested types: an enum Size, and a class Extra for something added to the drink, such as oat milk. The code outside Coffee orders two coffees, and Coffee works out what each one costs.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

Terminal
dotnet new console -n NestedType
cd NestedType
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/NestedType/NestedType.csproj:
Determining projects to restore...
Restored /Users/you/source/NestedType/NestedType.csproj (in 39 ms).
Restore succeeded.

dotnet new console -n NestedType creates a folder named NestedType with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or NestedType.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First the code that orders the coffees:

Program.cs (the orders)
// Outside Coffee, the name of a nested type starts with Coffee.
Coffee first = new(Coffee.Size.Large, new Coffee.Extra { Name = "oat milk", Price = 0.40m });
Coffee second = new(Coffee.Size.Small, new Coffee.Extra { Name = "vanilla", Price = 0.30m });

Console.WriteLine(first.Describe());
Console.WriteLine(second.Describe());
  • Coffee.Size.Large: Coffee.Size is the enum's full name, and Large is one of its values.
  • new Coffee.Extra { Name = ..., Price = ... } creates an Extra object and sets its two properties. Outside Coffee, the class's name is Coffee.Extra.

Then start the Coffee class, with its two nested types:

Program.cs (the nested types)
class Coffee
{
// Two types declared inside Coffee: an enum and a class.
public enum Size { Small, Large }

public class Extra
{
public string Name { get; init; } = "";
public decimal Price { get; init; }
}

enum Size and class Extra are declared between Coffee's braces, so they're nested types. Both are public, so the orders above can use them.

Finish the class:

Program.cs (the rest of the class)
// Inside Coffee, the short names Size and Extra are enough.
private readonly Size size;
private readonly Extra extra;

public Coffee(Size size, Extra extra)
{
this.size = size;
this.extra = extra;
}

public string Describe()
{
decimal basePrice = size == Size.Large ? 3.50m : 2.80m;
return $"{size} coffee with {extra.Name}: {basePrice + extra.Price:0.00}";
}
}

Inside Coffee, the fields, the constructor and Describe use the short names Size and Extra. Describe adds the extra's price to a base price of 3.50 for a large coffee or 2.80 for a small one, and :0.00 prints the total with two decimal places.

Step 3: Run It​

Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
Large coffee with oat milk: 3.90
Small coffee with vanilla: 3.10

macOS-style terminal window titled Terminal — NestedType showing dotnet run printing Large coffee with oat milk: 3.90 and Small coffee with vanilla: 3.10

Both orders went through the nested types: the large coffee came to 3.90 (3.50 plus 0.40 for oat milk), and the small one to 3.10 (2.80 plus 0.30 for vanilla). Each line starts with the Size value's name, Large or Small.

The Complete File​

macOS-style code window titled Program.cs — NestedType showing two coffees ordered with Coffee.Size and new Coffee.Extra, and a Coffee class that declares a public enum Size and a public class Extra inside it, keeps them in fields and works out the price in Describe

Program.cs
// Outside Coffee, the name of a nested type starts with Coffee.
Coffee first = new(Coffee.Size.Large, new Coffee.Extra { Name = "oat milk", Price = 0.40m });
Coffee second = new(Coffee.Size.Small, new Coffee.Extra { Name = "vanilla", Price = 0.30m });

Console.WriteLine(first.Describe());
Console.WriteLine(second.Describe());

class Coffee
{
// Two types declared inside Coffee: an enum and a class.
public enum Size { Small, Large }

public class Extra
{
public string Name { get; init; } = "";
public decimal Price { get; init; }
}

// Inside Coffee, the short names Size and Extra are enough.
private readonly Size size;
private readonly Extra extra;

public Coffee(Size size, Extra extra)
{
this.size = size;
this.extra = extra;
}

public string Describe()
{
decimal basePrice = size == Size.Large ? 3.50m : 2.80m;
return $"{size} coffee with {extra.Name}: {basePrice + extra.Price:0.00}";
}
}

Common Mistakes​

MistakeWhat happensDo this instead
Leaving out public on a nested typeWith class Extra and no modifier, Coffee.Extra extra = new(); outside Coffee didn't build: error CS0122: 'Coffee.Extra' is inaccessible due to its protection levelMark the nested type public when code outside the containing type needs it
Using the short name outside the containing typeExtra extra = new(); outside Coffee didn't build: error CS0246: The type or namespace name 'Extra' could not be found (are you missing a using directive or an assembly reference?)Write the full name, Coffee.Extra
A public member that uses a private nested typeA public Coffee(Extra extra) constructor with a private Extra didn't build: error CS0051: Inconsistent accessibility: parameter type 'Coffee.Extra' is less accessible than method 'Coffee.Coffee(Coffee.Extra)'Make the nested type at least as accessible as the member. The guide: the return type and the parameter types of any method, indexer, or delegate must be at least as accessible as the member itself.

FAQ​

Why does a nested type show up as Coffee+Extra?​

.NET writes a nested type's name with a plus sign at run time: typeof(Coffee.Extra).FullName printed Coffee+Extra, and so did Console.WriteLine(new Coffee.Extra()). The .NET reference: Plus sign (+), Precedes a nested class. In C# code, you still write Coffee.Extra.

Can I write Size instead of Coffee.Size outside the class?​

Yes, with using static Coffee; at the top of the file. Then Size size = Size.Large; and Extra extra = new() { Name = "oat milk" }; built and printed Large with oat milk. The reference: The using static directive names a type whose static members and nested types you can access without specifying a type name.

Should a nested class be public?​

Microsoft's design rule CA1034, Nested types should not be visible, says: Do not use externally visible nested types for logical grouping or to avoid name collisions; instead, use namespaces. It makes exceptions: Nested enumerations, protected types, and builder patterns are exempt from this rule. The rule isn't turned on by default in .NET 10, but it's a good guide: keep a nested class private when only its containing class uses it.

Conclusion​

Declare a type inside another when it belongs to that type. Outside, name it with its containing type, such as Coffee.Size and Coffee.Extra; inside, the short name works. Nested types are private until you add public.

Additional Resources​