Sep 06

Partial classes

Posted in Basics C#      Comments Off on Partial classes

In the previous post, I’ve talked about partial methods and I’ve promised that the next post would be about partial classes. And here it is! Now that I think about it, I should have written this post before the one on partial methods, but this order will have to do it now, won’t it?

The first thing you need to know about partial classes is that they depend entirely on the C# compiler. The second thing you should know is that you can apply the partial qualifier to classes, structs and interfaces (so I probably should have used Partial types for the title of this post).

In practice, when the C# compiler finds the partial qualifier applied to a type (class, struct or interface), it knows that its definition may span several source “groups”, which may (or may not) be scattered across several files. Partial classes are cool for splitting the “functionalities” of a type into several “code groups” (for example, I’ve used it for splitting the definition of a class into several files to improve readability).

Partial types were introduced to solve the same problem I’ve mentioned in the previous post: customization of code built through code generators. Now that you know the basics, lets go through a simple example. Suppose we’ve got a Student type and that you want to separate it’s features into different code groups. Here’s how you can do that with a partial class:

//File Student.cs
public partial class Student {
    public String Name { get; set; }
    public Int32 Age { get; set; }
//File Student.Validation.cs
public partial class Student {
    public void Validate(){

In the previous snippet,we’re creating a new type (Student) which is split into 2 different files (Student.cs and Student.Validation.cs). When you compile the previous code (notice that both files must be in the same project!),you’ll end up with a single type (Student) which has all the members exposed by the partial classes.

Even though I’ve put the partial class definitions into different files, the truth is that you can place both in the same file (though I haven’t seen this being used like that in lots of places). Since partial types don’t depend on the CLR but on the compiler, you need to write all the files in the same language and they must be compiled into the same unit (ie, all the partial file definitions must be defined in the same project).

And there’s not much to say about partial types