What is Partial class ?
A class in which code can be written in two or more files is known as a partial class.
Partial class is a feature that allows a class to be split into multiple files.
These files are then combined into a single class by the compiler when the program is compiled.
To make any class partial we need to use the keyword "partial".
Use of Partial Class ?
1. Large classes can be broken down into smaller, more manageable pieces.
2. If multiple developers are working on the same class, they can work on different parts of the class in separate files without interfering with each other.
3. Sometimes, tools or designers (like Visual Studio’s form designer) generate part of a class automatically. Using partial classes allows the generated code to be kept separate from manually written code.
Example
suppose employee class too large so we create partial class for get Employee details as shown below,
Adding PartialEmployeeOne.cs
namespace PartialClassDemo
{
public partial class PartialEmployee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public double Salary { get; set; }
}
}
Adding PartialEmployeeTwo.cs
using System;
namespace PartialClassDemo
{
public partial class PartialEmployee
{
public void DisplayFullName()
{
Console.WriteLine($"Full Name is : {FirstName} {LastName}");
}
public void DisplayEmployeeDetails()
{
Console.WriteLine("Employee Details : ");
Console.WriteLine($"First Name : {FirstName}");
Console.WriteLine($"Last Name : {LastName}");
Console.WriteLine($"Gender : {Gender}");
Console.WriteLine($"Salary : {Salary}");
}
}
}
Now in program.cs class we can create of that partial class instance and access it
using System;
namespace PartialClassDemo
{
class Program
{
static void Main(string[] args)
{
PartialEmployee emp = new PartialEmployee()
{
FirstName = "Pranaya",
LastName = "Rout",
Salary = 100000,
Gender = "Male"
};
emp.DisplayFullName();
emp.DisplayEmployeeDetails();
Console.ReadKey();
}
}
}
Output
Employee Details :
First Name : yash
Last Name : prajapati
Gender : male
Salary : 20000
Full Name is : yash prajapati
Explaination : Two partial class are create but at complie time system we understand as single class