Skip to content
Tutorials Center
My learning

Topics

Lesson 68 of 182 ยท Classes and Objects

Partial, Nested and Local Types

Learn C# partial classes, partial methods and partial properties, how code generators use them, nested types, file-scoped types, anonymous types and why C# has no local classes.

So far every type in this course has lived in one place and been a top-level declaration. C# has several tools for organising types differently. A partial type can be split across several files, which is how code generators and humans safely edit the same class. A nested type is declared inside another type, the right choice for helpers nobody else should see. A file-scoped type is visible only within one source file. And an anonymous type is a throw-away shape the compiler invents for you, mostly in LINQ queries.

This lesson explains each tool, shows what it compiles to, and gives rules of thumb for when to use it. You should be comfortable with classes, access modifiers and records.

Partial classes

Adding the partial keyword lets you split a type declaration across multiple parts. The compiler merges all parts with the same name in the same namespace into one type, as if you had written it in one place. All parts must use partial, must agree on accessibility and kind, and must be compiled together (in the same assembly).

Our runner compiles a single file, so the parts below sit in one file, but they behave identically across files:

C# One class in two parts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

There is one Invoice type with fields, constructors and methods from both parts. The members of one part can freely use those of the other, and the order of the parts does not matter. Things that are combined across parts: members, interfaces (each part can add some), attributes and XML docs. Things that must be stated at most once or consistently: the base class (you can repeat it, but cannot contradict it), and the modifiers like abstract, sealed.

Why partial exists: generated code

The main reason is tools. Visual designers, source generators, ORMs and serializers write code into a file such as Form1.Designer.cs. If that file were the only place for the class, your own edits would be overwritten the next time the tool ran. With partial, the tool owns one file, you own the other, and both contribute to one class. Modern .NET relies heavily on source generators that add partial members at compile time: [GeneratedRegex], [LoggerMessage], System.Text.Json's source generation and many more. This is the reason that classes using them must be declared partial.

A secondary use is organisation: a very large class split into Customer.Validation.cs, Customer.Persistence.cs and so on. It is acceptable for generated code and for nested-heavy or legacy classes, but if you need partial just to make a class manageable, that class likely has too many responsibilities (see designing with objects).

Partial methods

A partial method has a declaration in one part and, optionally, an implementation in another. It is the older hook mechanism for generated code: the generator declares partial void OnCreated(); and you may implement it.

C# Partial methods: declaration and implementation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Two flavours exist, and they differ in an important way:

  • Classic partial methods (partial void M();) must return void, have no accessibility modifier (implicitly private) and no out parameters. If no part implements one, the compiler removes the call entirely, so it costs nothing.
  • Extended partial methods (C# 9+) carry an accessibility modifier, any return type, or out parameters, such as private static partial int Clamp(int value);. They must be implemented exactly once; a missing implementation is an error.

When the signature of the declaration and implementation do not match, you get a compile error (for example CS8795: partial method must have an implementation part). Make sure both sides spell the signature identically.

Partial properties and indexers (C# 13)

C# 13 extended partial to properties and indexers. The declaration part is just the signature (public partial string Title { get; set; }); the implementation part supplies the accessor bodies. Source generators use this to produce the plumbing for a property you declare.

C# Partial properties (C# 13)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

A partial property needs a declaration and an implementation with the same signature, and it cannot be an auto-property in the implementing part (because that would look like a second declaration). Partial constructors and events were added in C# 14 in the same spirit; they are most interesting to generator authors.

Nested types

A type declared inside another type is a nested type. It is a member of the outer type, so it can be private or protected, and it can use the outer type's private members through an instance.

C# A private nested helper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Two common roles for nested types appear above:

  1. Hidden implementation detail: Node is private, so the stack can change its structure without breaking callers, and the name Node does not clutter the namespace. Enumerators (like List<T>.Enumerator) are typical.
  2. Types that only make sense with their owner: Report.Options reads as "the options of a report". Callers write Report.Options.

Facts to remember:

  • Nested types default to private (top-level types default to internal), and can be public, protected, private protected and so on. A nested type may be a class, struct, record, interface, enum or delegate.
  • A nested type of a generic class is itself generic over the outer type parameters: LinkedStack<int>.Node and LinkedStack<string>.Node are different types. Here Node uses T from the outer class.
  • Nested types can access the outer type's private static members directly, and private instance members through a reference to an instance.
  • The outer type has no special access to the nested type's private members.

Avoid public nested types for things many places need; a plain top-level type is easier to find and to use. The .NET guidelines recommend nested public types only when the relationship to the outer type is strong.

File-scoped types (C# 11)

The file modifier makes a top-level type visible only inside the file that declares it. Two files may each declare a file class Helper with no conflict. This is mainly intended for source generators, to avoid clashing with names in user code, but it is useful for small private helpers in a big project.

C# A file-scoped type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Hasher cannot be named from any other file, and cannot appear in the signature of a non-file type's accessible members. Compare it to internal, which limits visibility to the assembly, and to a private nested class, which limits it to the owner. file fits when "this helper belongs to this file only".

Do not confuse file (a type modifier) with file-scoped namespaces (namespace MyApp;), which just save one level of braces.

Anonymous types

An anonymous type is a class the compiler writes for you. You create one with new { ... }, and the compiler infers its property names and types. It has read-only properties, value-based Equals/GetHashCode, and a readable ToString. Because it has no name you can write, you hold it in a var.

C# Anonymous types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notes:

  • Properties are read-only; use with to produce a modified copy.
  • Two anonymous objects share one compiler-generated type when they have the same property names, types and order in the same assembly, which is why Equals works above.
  • They are internal to the assembly and cannot be returned from a method with a precise type (only as object or dynamic), which is their biggest limitation.
  • They are reference types (classes). They can't contain methods or events.

Anonymous types are handy for quick LINQ projections, grouping keys and one-off values. For anything that crosses a method boundary, prefer a record, a record struct or a tuple, all of which have names for their members and a proper type.

Local types: what C# does not have

Java has local classes (classes declared inside a method). C# does not allow type declarations inside a method body. Writing class Foo {} there is a syntax error. What you can declare locally are local functions, which are methods nested inside another method and can capture its variables.

C# Local functions instead of local types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The tuple return type plays the role a tiny local class would play in Java. When a result shape is needed in several methods, declare a record or record struct as a private nested type or a file type. You will see lambda expressions and local functions in more depth in lambdas and the methods chapter.

Which tool when?

Need Use
A tool or generator writes part of a class partial class (and partial members)
A helper type used only by one class private nested class or struct
A type that conceptually belongs to another (Report.Options) public nested type, sparingly
A helper visible only in one file / generated code names file type
A one-off result shape inside a method or query Anonymous type or tuple
A result shape that is returned or reused record / record struct

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What must be true for the parts of a partial class?

    All declarations of the type carry partial and are merged by the compiler within one assembly. Files are a convention, not a requirement.
  2. 2. What happens to a call to a classic partial void Hook(); when no part implements it?

    Classic (void, no modifier) partial methods without an implementation are removed with their calls. Extended partial methods must be implemented.
  3. 3. What is the default accessibility of a nested class declared without a modifier?

    Members of a type, including nested types, are private by default. Top-level types default to internal.
  4. 4. Which statement about anonymous types is true?

    Anonymous types are immutable reference types with compiler-generated value equality; you cannot name their type in a signature.
  5. 5. How do you declare a helper class that is visible only in the current source file?

    The file modifier (C# 11) restricts a top-level type to the file that declares it. Top-level types cannot be private.

Summary

  • partial splits a type, method, property or indexer across declarations; its main users are code generators and source generators.
  • Classic partial methods are optional hooks that vanish when not implemented; extended ones (with modifiers or return values) must be implemented. Partial properties and indexers arrived in C# 13.
  • Nested types are private by default and are ideal for implementation details such as node classes and enumerators.
  • file types are visible only in their file; anonymous types are immutable, compiler-named result shapes held in var.
  • C# has no local classes: use local functions, tuples or a private nested record.

Next: Designing with Objects: SOLID in C#