Partial Keyword in C#

 

We can define any class with partial keyword. The main advantage of partial keyword is we can split the one class into multiple files that means we can define one single class into multiple physical files. By spitting the one class multiple files readability will increase and it is very easy to go to specific portion of the class even though class contains hundred lines of code.

 

In this example we discuss about how to separate properties and methods into different files for single class by using partial keyword. For example we have the Employee class with different properties and methods.

 

We will split this Employee class into two files instead of one file by using partial keyword. First file is going to have all properties and second file is going to have methods.

 

As shown below we are splitting the single Employee class file into two Employee class files.

 

Employee-Props.cs

 

namespace PartialClassExp

{

    public partial class Employee

    {

        public int Id { get; set; }

 

        public string Name { get; set; }

    }

}

 

Employee-Methods.cs

 

namespace PartialClassExp

{

    public partial class Employee

    {

        public decimal GetEmpSal(int iId)

        {

            return 50000;

        }

    }

}

 

As shown above we separated the single Employee class into two files. First file Employee-Props.cs contains all properties and second file Employee-Methods.cs contains methods of Employee class.

 

Even though we split the class into multiple files, calling procedure of class will not change. We have to create the object for partial class also as we create the object for normal class as shown below.

 

            Employee obj = new Employee();

            obj.Id = 100;

            obj.Name = "ABC";

 

            decimal dSal = obj.GetEmpSal(100);

 

We can give file names that contain partial class as per our wish. But we have to define all partial classes of particular class under same namespace. Even though partial classes are defined in different physical files once all these files are compiled by the C# compiler, the end result is going to be single unified type.

                                                                                                         

                                                                                                                      PartialClassExp.zip (12.37 kb)