Partial class in C# is a special feature that allows you to design a class that can spread across a single or multiple files. The compiler combines all of these partial class files together and represent them as a single class during compilation time.

This is a very handy feature allows multiple developers to work on a single class, Using a partial keyword, we can split across the class in to multiple files. This keyword is also useful to split the functionality of methods, interfaces, or structure into multiple files.

Key Points of Partial Class in C#:

  • In C# partial classes feature is completely implemented by C# compiler , CLR literally knows nothing about partial type at all.
  • Partial classes don’t allow for extending classes in another assembly, it only support splitting class implementation across multiple files in same assembly.
  • All partial type defined across multiple files must have the same accessibility, such as public, private, etc.
  • Nested partial types are also allowed in partial type definitions.

Create Partial Class in C# :

We can create partial classes by decorating partial modifier just before the class name. In below we have declared a partial class as Employee.

Example  1:

Lets have a look at below example.

  • Declared a partial class as Employee having properties as FirstName and Designation in Employee1.cs file.
  • Have also declared a partial class as Employee having properties as LastName and Salary in Employee2.cs file.

  • In below Main method, we have created an Employee emp object and successfully accessing all properties declared across multiple files.

When we run above code then it generates below output, here you can see we are able to access all Employee object properties in the Main method.

Partial Class OutPut 1.0

What C# compiler does behind the screen ?

If you run ILDASM (IL Disassembler) tool on the assembly of above code sample, then you can see something similar as shown below.

Partial Class OutPut 1.1

If you look closely, then you can see that the C# compiler creates a single class as Employee having all 4 properties as FirstName , Designation , LastName and Salary , you can also check below assembly explorer image, which clearly shows that all properties of both partial classes present in different files (Employee1.cs and Employee2.cs).

Partial Class OutPut 1.2

Thanks for your time 🙂 feel free to provide your feedback and do check my other blogs on some of other concept like Static Classes in C#