Partial class in C# (partial modifier)

This post was originally posted at https://agrawalsuneet.github.io/blogs/partial-class-in-csharp-partial-modifier/ and reposted on Medium on 30th Mar 2020.

What is a Partial class?

A partial class is a special type of class where a single class can be split into multiple .cs file and while compilation, all the functionalities of same partial classes written in different .cs files will be merged and then compile it.
It provides you with functionality where you can split your class into different files based on the requirement and usability.

//Someclass1.cs
public partial class SomeClass
{
// code
private void function1(){ }}//Someclass2.cs
public partial class SomeClass
{
// code
private void function2(){ }}//final compiled code
public class SomeClass
{
private void function1(){ }
private void function2(){ }}

Requirements of Partial modifier

  • A partial modifier can be added to a class or an interface or a struct.
  • Every part of the partial class definition should be in the same assembly and namespace, but we can use different source file name.
  • All the parts must have the same accessibility for example public or private, etc.
  • If any part is declared abstract, sealed or base type then the whole class is declared of the same type.
  • The partial modifier can only appear immediately before the keywords class, struct, or interface.
  • Nested partial types are allowed.
  • Different parts can have different base types like implementing different interfaces and the final class will inherit all the base types.

Advantages of Partial class

  • With the concept of partial classes, we can better the code structure like by separating business logic and UI implementation within the same class.
  • Can avoid conflicts if multiple developers working on the same class or interface or struct.
  • When we working with automatically generated source, code can be added to the class without having to recreate the source file. For example, Visual Studio separates HTML code for the UI and server-side code into two separate files: .aspx and .cs files.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store