C# Tutorial Lesson 24: Partial Types [2.0]

Note: this lesson covers new functionality in C# 2.0, which at the time of writing is not released.

By using the new 'partial' class modifier, you can define a class across multiple files. The compiled class merges the various partial source files into a single compiled class. So, for instance, if you have the source code

1.

public partial class A

2.

{

3.

    public void method1()

4.

    {...}

5.

}


and somewhere else you have the source code

1.

public partial class A

2.

{

3.

    public void method2()

4.

    {...}

5.

}


then the compiled object will exhibit both method1 and method2. Note that it's important that the various aspects of the declaration like modifiers, type parameters, etc. all match up across the multiple partial declarations.

The stated reason for introducing the 'partial' modifier is that it's fairly common for projects to include some automated code generation. Partial types supports code generation because it means that code changes won't necessarily be overwritten if code generation occurs anew; the changes can be held in distinct files.

Generally speaking, it is a compile-time error to declare two elements of the same class twice. The only exceptions are for things like inner classes, which may themselves be declared as partial.

Link Building Information