Course contentsShow
← C#
Lesson 31 of 1,9081. C# Language FoundationsFree lesson

Partial Classes and Source Generation

Separate concerns by splitting class definitions across multiple source files.

In this lesson, you will learn how to split a single class definition across multiple files to keep your codebase clean and enable powerful automation.

Breaking the Monolith

Sometimes a class grows so large that it becomes difficult to manage. Other times, you might have code that is automatically generated by tools (like database mappers or UI designers) that you shouldn't edit manually. C# solves this using the partial keyword.

When you mark a class as partial, you are telling the compiler: "I am defining part of this class here, but the rest of the definition exists elsewhere." The compiler will look at all the files in your project, find the pieces with the same name, and stitch them together into one single class at compile time.

A Practical Example

Imagine you have a User class. You want to write custom logic in one file, but have a tool automatically generate the data-handling properties in another.

File 1: User.cs (Your custom logic)

public partial class User
{
    public void DisplayInfo() => Console.WriteLine($"Hello, {Name}!");
}

File 2: User.Generated.cs (Tool-generated code)

public partial class User
{
    public string Name { get; set; } = "Anonymous";
}

When you build your application, the C# compiler treats these two files as if they were one block of code. You can call user.DisplayInfo() and access user.Name seamlessly, even though they lived in separate files.

Why use this with Source Generation?

Source generators are "helper programs" that write C# code for you while you compile. Because these generators can’t easily modify your existing, hand-written files without causing conflicts, they use partial classes. The generator creates a new file containing a partial piece of your class, providing extra functionality (like high-performance logging or JSON serialization) without you ever needing to touch that generated code. It keeps your business logic separate from the machine-generated plumbing.

Key Takeaway: The partial keyword allows you to split a single class across multiple files, making it possible to keep your manual code separate from auto-generated code while letting the compiler combine them into one seamless unit.