What is Partial class in .NET?

Partial Class: - Partial class allows you to define a single class in to multiple physical files (more than one physical file) and during compilation time these classes are combined to form a single class.

Now, in above code snippet class you can see that the BigClass containing three methods which will have their own implementation and the implementation can be bigger which can make the code not readable so partial basically divide this thing and make your code readable.

Let's demonstrate a simple example to see how exactly Partial Class help us make your code more readable for that just follow the following steps.

The below example will give you an idea of how does Partial Class look like.

namespace PartialExampleConsole
{
class Program
{
// Below you can see that i have declared the class as Partial.
public partial class BigClass
{
int ResultAdd;
// created a add method which will give result of two numbers.
public void Add(int i, int j)
{
ResultAdd = i + j;// Addition is done here.
//The below line will print the output
Console.WriteLine("The Substration of two Numbers is :" + ResultAdd);
}
}
// Below you can see that i have declared the class as Partial
//with the same name as the above partial class.
public partial class BigClass
{
int ResultSubstract;
// created a Subtract method which will give result of two numbers.
public void Substract(int a , int b)
{
ResultSubstract = a - b;//Substraction is done here.
//The below line will print the output
Console.WriteLine("The Addition of two Numbers is:" +ResultSubstract);
}
}
// Below you can see that i have declared the class as Partial
with the same name as the above partial class.
public partial class BigClass
{
int ResultMultiply;
// created a Multiply method which will give result of two numbers.
public void Multiply(int x, int y)
{
ResultMultiply = x * y;//Multiplicaton is done here
//The below line will print the output
Console.WriteLine("The Multiplication of two Numbers is :" + ResultMultiply);
}
}
static void Main(string[] args)
{
//Created the object of BigClass.
BigClass obj = new BigClass();
obj.Add(5, 5);//Call the Add method and assign the value to the paramaters.
obj.Substract(10, 5);//Call the Substract method and assign the value to the paramaters.
obj.Multiply(5, 5);//Call the Multiply method and assign the value to the paramaters.
Console.ReadLine();
}
}
}

Note: - In the main class I have created instance of the BigClass only once but have created three classes declared as Partial which means a single class can be span in to more files but at compiled time this classes are combined to form a single class.