C# Partial Classes

A partial class lets you split the definition of a single class across multiple files. The compiler merges all the parts into one complete class when building the program. This is useful for large classes, auto-generated code, and team collaboration.

The Problem Partial Classes Solve

Imagine a large class with hundreds of lines — user interface logic, database logic, validation logic, and business logic all in one file. The file becomes hard to navigate and multiple developers cannot work on different sections simultaneously without merge conflicts.

┌──────────────────────────────────────────────────────────────┐
│  WITHOUT PARTIAL — One giant file:                           │
│  CustomerManager.cs (1,200 lines — hard to manage)           │
├──────────────────────────────────────────────────────────────┤
│  WITH PARTIAL — Split cleanly:                               │
│  CustomerManager.UI.cs          (UI methods)                 │
│  CustomerManager.Database.cs    (DB methods)                 │
│  CustomerManager.Validation.cs  (validation methods)         │
│                                                              │
│  Compiler sees all three as ONE class                        │
└──────────────────────────────────────────────────────────────┘

Declaring a Partial Class

Add the partial keyword before class in every file that contains a part of the class. All parts must have the same class name and be in the same namespace.

File 1: Employee.cs

public partial class Employee
{
    public string Name;
    public string Department;
    public double Salary;

    public Employee(string name, string dept, double salary)
    {
        Name       = name;
        Department = dept;
        Salary     = salary;
    }
}

File 2: Employee.Methods.cs

public partial class Employee
{
    public void DisplayInfo()
    {
        Console.WriteLine($"Name: {Name}, Dept: {Department}, Salary: {Salary}");
    }

    public void GiveRaise(double percent)
    {
        Salary += Salary * percent / 100;
        Console.WriteLine($"{Name} now earns {Salary}");
    }
}

How They Merge

┌────────────────────────────────────────────────────────────┐
│  Employee.cs           +   Employee.Methods.cs             │
│  ┌──────────────────┐      ┌──────────────────────┐        │
│  │ Fields           │      │ DisplayInfo()        │        │
│  │ Constructor      │  +   │ GiveRaise()          │        │
│  └──────────────────┘      └──────────────────────┘        │
│             │                       │                      │
│             └───────────┬───────────┘                      │
│                         ▼                                  │
│          Complete Employee class (compiler merges)         │
└────────────────────────────────────────────────────────────┘

Using the Class

class Program
{
    static void Main()
    {
        Employee emp = new Employee("Alice", "Engineering", 70000);
        emp.DisplayInfo();      // Name: Alice, Dept: Engineering, Salary: 70000
        emp.GiveRaise(10);      // Alice now earns 77000
    }
}

Rules for Partial Classes

┌────────────────────────────────────────────────────────────┐
│  Rules:                                                    │
│  ✅ All parts must use the partial keyword                 │
│  ✅ All parts must have the same class name                │
│  ✅ All parts must be in the same namespace                │
│  ✅ All parts must be in the same assembly (project)       │
│  ✅ Access modifiers must be consistent                    │
│  ❌ Cannot split a class across different assemblies       │
│  ❌ Cannot use partial on enum or delegate                 │
└────────────────────────────────────────────────────────────┘

Partial Methods

A partial method is a method declared in one part of a partial class and optionally implemented in another part. If no implementation is provided, the method and all calls to it are removed by the compiler — no error, no runtime cost.

// File 1 — declaration only:
public partial class Order
{
    partial void OnOrderPlaced(string orderId);   // declaration

    public void PlaceOrder(string id)
    {
        Console.WriteLine("Order placed: " + id);
        OnOrderPlaced(id);   // calls partial method — safe even if not implemented
    }
}

// File 2 — implementation:
public partial class Order
{
    partial void OnOrderPlaced(string orderId)
    {
        Console.WriteLine("Sending confirmation email for: " + orderId);
    }
}

Partial Method Diagram

┌──────────────────────────────────────────────────────────────┐
│  Partial Method Flow:                                        │
│                                                              │
│  Declaration in File 1:   partial void OnOrderPlaced(...)    │
│                                    │                         │
│  Implementation in File 2?                                   │
│          YES ──────────────────────▶  Method runs normally   │
│          NO  ──────────────────────▶  Compiler removes call  │
│                                       (no error, no cost)    │
└──────────────────────────────────────────────────────────────┘

Partial Classes and Auto-Generated Code

The most common real-world use of partial classes is with code generators. Tools like Visual Studio, Entity Framework, and Windows Forms automatically generate part of a class. You add your own logic in a separate partial class file without touching the generated file.

┌──────────────────────────────────────────────────────────────┐
│  EXAMPLE: Windows Forms Designer                             │
├──────────────────────────────────────────────────────────────┤
│  Form1.Designer.cs    ← AUTO-GENERATED (do not edit)         │
│  ┌───────────────────────────────────────────────┐           │
│  │ partial class Form1 : Form                    │           │
│  │ {                                             │           │
│  │     // Button positions, sizes, colors        │           │
│  │     // generated by the visual designer       │           │
│  │ }                                             │           │
│  └───────────────────────────────────────────────┘           │
│                                                              │
│  Form1.cs             ← YOU WRITE THIS                       │
│  ┌───────────────────────────────────────────────┐           │
│  │ partial class Form1                           │           │
│  │ {                                             │           │
│  │     void button1_Click(...)                   │           │
│  │     {                                         │           │
│  │         // your custom logic here             │           │
│  │     }                                         │           │
│  │ }                                             │           │
│  └───────────────────────────────────────────────┘           │
└──────────────────────────────────────────────────────────────┘

Partial Structs and Interfaces

The partial keyword also works with struct and interface, following the same rules as partial classes.

// Partial struct:
public partial struct Size
{
    public int Width;
}

public partial struct Size
{
    public int Height;

    public int Area() { return Width * Height; }
}

// Partial interface:
public partial interface IVehicle
{
    void Start();
}

public partial interface IVehicle
{
    void Stop();
}

Benefits of Partial Classes

┌────────────────────────────────────────────────────────────┐
│  ✅ Organize large classes into logical sections           │
│  ✅ Multiple developers can work on different parts        │
│  ✅ Separate auto-generated code from hand-written code    │
│  ✅ Easier to read and navigate in large projects          │
│  ✅ No performance cost — compiler merges at build time    │
└────────────────────────────────────────────────────────────┘

Quick Summary

┌──────────────────────────────────────────────────────────────┐
│  partial class → split one class across multiple files       │
│  partial method → declare in one part, implement in another  │
│                                                              │
│  Requirements:                                               │
│  • Same class name in all parts                              │
│  • Same namespace in all parts                               │
│  • partial keyword in every part                             │
│                                                              │
│  Common uses:                                                │
│  • Auto-generated code (EF, WinForms, XAML)                  │
│  • Large classes split by responsibility                     │
│  • Team development on shared classes                        │
└──────────────────────────────────────────────────────────────┘

Partial classes are a practical organizational tool. They do not change how a class works — they only change how its source code is arranged across files. In any real project that uses code generation tools, you will encounter partial classes constantly.

Leave a Comment

Your email address will not be published. Required fields are marked *