Partial classes and Partial structures

Sometimes you have to write hundred lines of code for single class, this can end up being a mighty lengthy file indeed. Handling this type of file is very difficult. C# provides way to solve this problem through partial keyword.

 

Single Class and Structure can defined in multiple files by using partial keyword. For example you may want to define constructors and properties in one file and methods in some other file; in this case partial keyword is very useful.

 

Here I am explaining partial keyword with an example through class Emp.  Emp class has parameterized constructor, single variable and one method. I am defining the parameterized constructor and variable in one file called Emp.cs and method display() in EmpInternal.cs file as shown below using partial keyword.

 

Emp.cs file

 

partial class Emp
{
        public string empName;
        public Emp(string name)
        {
            empName = name;
        }
}

 


EmpInternal.cs file


partial class Emp
{
        public void display()
        {
            //empName is assigned through constructor in Emp.cs file
            Console.WriteLine("Employee Name: " + empName);
        }
}

 

If you observe the above code, we define the Emp class in two files with partial keyword. You can use one file members in another file. Here we used the empName variable which is assigned in parameterized constructor of Emp.cs file in EmpInternal.cs file display method.

 

Create object for Emp class and check whether you are able to access its display() method by passing emp name as shown below.

 

static void Main(string[] args)
{
            Emp obj = new Emp("John");
            obj.display();
            Console.ReadLine();
}

 

The output is as shown below. The display() method of EmpInternal.cs file is displaying emp name which passed to Emp.cs file.

 

 

In this way you can use partial keyword for structures also to split the code between files. You can give the file name as you want.

                   

                                                                                                  PartialClassesExample.zip (23.32 kb)