Partial class in C# is a special feature that allows 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.

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 of partial class in C#

Lets have a look at below example.

  • We have declared a partial class as Employee having properties as FirstName and Designation in Employee1.cs file.
  • We 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 that have been declared across multiple files.

When we run above code then following out put will be generated and 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

Key Points of C# partial classes:

  • In C# partial classes feature is completely implemented by C# compiler , CLR literally knows nothing about partial type at all.
  • When you write partial classes spanned across in multiple files then make sure that you use same language.
  • Partial classes don’t allow for extending classes in another assembly. They only support splitting class implementation across multiple files in same assembly.

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