Partial members

Partial members appeared very early with C# 2.0. They allow you to dispatch the code of a class or method between many files.

Partial classes are very useful when you want to dispatch groups of methods of a class between many developers and avoid risks of merge conflicts if multiple check-out is enabled. The class is therefore split into multiple files. Imagine for instance a class that manages queries and you want to separate the create, read, update and delete methods. Then you have four files but only one class. But the most common reason why you would use partial classes is when you work with code generators. Indeed when a class is created by a code generator, you shouldn’t modify it, at least not the generated file. So instead of creating inheritance, you may just create a partial class in another file. So how do we declare such a class ? Just add the partial keyword to the class declaration, it is that easy (Figure 1)!

partial-class

Figure 1

Repeat this operation in each file that is part of the partial class. Of course, be aware that all declarations must be located in the same namespace. Note that interfaces can also be partial.

Regarding partial method, you obviously cannot spread the implementation at several locations. A partial method must be part of a partial class and allows you to separate its declaration from its implementation, which is somehow similar to what we do with interfaces. So the essential use of partial methods is when the code is generated. This allows you to declare a method and add calls to it in your generated code (Figure 2), which by default won’t execute anything as the method is like empty and then implement it in a partial class (Figure 3).

partial-method-declaration

Figure 2

partial-method-implementation

Figure 3

Unlike partial classes and interfaces, partial methods have some constraints:

  • They cannot return any result;
  • They cannot have out parameters;
  • They must be private (but no access modifier is allowed anyway).
Advertisements