TOC
Classes:

Partial Classes

If you have worked with C#, or perhaps even another programming language, you are used to the fact that the name of a class has to be unique - there cannot be two classes with the same name, unless they are in different namespaces. However, at one point, Microsoft decided to change this, with the introduction of something called partial classes.

When you define your class with the partial keyword, you or someone else is allowed to extend the functionality of your class with another class, which also needs to be declared as partial. This is useful in the following situations:

  • When you have a very large class - you can then keep it in multiple files, to make it easier to work with various parts of the classes. For instance, you could have all the properties in one file and all the methods in another file, while still just having one class.
  • When you work with a designer, like the one in Visual Studio - for instance with WinForms, where all the automatically generated designer code can be kept in one file, while your code is kept in another file.

Let me illustrate this with an example. In my project, I have the usual Program.cs, found in a console app. Besides that, I have added two files: PartialClass1.cs and PartialClass2.cs. Here are the files and their contents:

PartialClass1.cs

using System;

namespace PartialClasses
{
    public partial class PartialClass
    {
        public void HelloWorld()
        {
            Console.WriteLine("Hello, world!");
        }
    }
}

PartialClass2.cs

using System;

namespace PartialClasses
{
    public partial class PartialClass
    {
        public void HelloUniverse()
        {
            Console.WriteLine("Hello, universe!");
        }
    }
}

Notice that both classes are defined with the partial keyword and have the same names. Also notice that each of them define a method - HelloWorld() and HelloUniverse(). In our Program.cs we can now use this class as if it was defined in only one place, just like any other class:

using System;

namespace PartialClasses
{
    class Program
    {
        static void Main(string[] args)
        {
            PartialClass pc = new PartialClass();
            pc.HelloWorld();
            pc.HelloUniverse();
        }
    }
}

Summary

With partial classes, you can split your classes into multiple files, either because the class definition is very large or when the tools you work with benefits from it, like with the Visual Studio designer for WinForms.

This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!