Partial Classes


The definition of a class may be split into parts. Parts of a class may thus be declared in separate files. The keyword that splits a class definition is partial. When a program with partial classes is compiled, the parts of the class are merged to form a single class. The partial modifier has the following form:

partial class class-name
{
 // ...
}

where class-name is the name of the class being separated into parts.

Following is an example of a partial class. Two files are shown - Program.cs and Class1.cs.

// Partial - Partial Classes - File: Program.cs

using System;

partial class X
{
    public static void f()
    {
        Console.WriteLine("In X.f()");
    }
}

class Program
{
    static void Main()
    {
        X.f();
        X.g();
    }
}


// Partial - Partial Classes - File: Class1.cs

using System;

partial class X
{
    public static void g()
    {
        Console.WriteLine("In X.g()");
    }
}

The class is split across the files Program.cs and Class1.cs. When the project is built, Main() accesses both parts of the class, thus the compiler has merged the parts.