Search⌘ K
AI Features

Partial Classes and Methods

Explore how to define and implement partial classes and partial methods in C#. Understand how splitting class definitions across files improves code organization, supports optional method implementations, and aids collaboration in multi-developer projects. Learn the compiler's role in merging partial types and practical use cases for working with generated code and large teams.

C# allows us to split a class definition across multiple files using the partial keyword. This informs the compiler that the type definition spans several source files.

Define partial classes

Let’s look at how we can define the properties of a Person class in one file.

C# 14.0
namespace PartialClasses;
// We marked this class as partial
// The compiler will look through the source code
// to find the rest of the class definition
public partial class Person
{
// We initialize string properties to empty strings
// to satisfy the compiler's null-safety checks.
public string FirstName { get; set; } = string.Empty;
public string LastName { get; set; } = string.Empty;
public int Age { get; set; }
public string Occupation { get; set; } = string.Empty;
public decimal AnnualSalary { get; set; }
}
  • Line 1: We use a file-scoped namespace to reduce indentation.

  • Line 6: We add the partial keyword before class. This indicates the class definition continues elsewhere.

  • Lines 10–14: We define the properties. We initialize the string properties to string.Empty to ensure they are not null when the object is created.

Next, we can define the methods for the same Person class in a completely different file.

C# 14.0
namespace PartialClasses;
// This is the continuation of the Person class
public partial class Person
{
public void PrintFullName()
{
// We have access to all class members defined in other files
// Ultimately, it is the same class
Console.WriteLine($"{FirstName} {LastName}");
}
}
...