Partial Classes in C#

Partial Classes in C# with Examples

In this article, I am going to discuss Partial Classes in C# with some examples. Please read our previous article, where we discussed Method Hiding in C#. At the end of this article, you will understand what are Partial classes and when and how to use Partial Classes in C# with real-time examples.

What are Partial Classes in C#?

Partial Classes are the new feature that has been added in C# 2.0 which allows us to define a class on multiple files i.e. we can physically split the content of the class into different files but even physically they are divided but logically it is one single unit only.

A class which code can be written in two or more files is known as partial class. To make any class as partial we need to use the keyword partial.

Partial classes allow us to split a class definition into 2 or more files.  It is also possible to split the definition of a struct or an interface over two or more source files. Each source file will contain a section of the class definition, and all parts are combined into a single class when the application is compiled.

Understanding Partial Classes in C# with an Example:

Create a console application. Add a class file with name Employee.cs to the project. Copy and paste the following code in the Employee.cs class file.

namespace PartialDemo
{
    public class Employee
    {
        private string _firstName;
        private string _lastName;
        private double _salary;
        private string _gender;

        public string FirstName
        {
            get { return _firstName; }
            set { _firstName = value; }
        }
        public string LastName
        {
            get { return _lastName; }
            set { _lastName = value; }
        }
        public double Salary
        {
            get { return _salary; }
            set { _salary = value; }
        }
        public string Gender
        {
            get { return _gender; }
            set { _gender = value; }
        }

        public void DisplayFullName()
        {
            Console.WriteLine(@"Full Name is :  {0} {1}", _firstName, _lastName);
        }

        public void DisplayEmployeeDetails()
        {
            Console.WriteLine("Employee Details : ");
            Console.WriteLine(@"First Name : {0}", _firstName);
            Console.WriteLine(@"Last Name : {0}", _lastName);
            Console.WriteLine(@"Gender : {0}", _gender);
            Console.WriteLine(@"Salary : {0}", _salary);
        }
    }
}

This is a very simple Employee class having 4 private fields, 4 public properties and 2 public methods. Let’s use the above class in our Main method. So modify the Program class which contains the Main method as shown below.

namespace PartialDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Employee emp = new Employee();
            emp.FirstName = "Pranaya";
            emp.LastName = "Rout";
            emp.Salary = 100000;
            emp.Gender = "Male";
            emp.DisplayFullName();
            emp.DisplayEmployeeDetails();

            Console.WriteLine("Press any key to exist.");
            Console.ReadKey();
        }
    }
}

Run the application and see it will give you the below output.

Partial Classes and Partial Methods in C#

Splitting the above class definition into 2 files. 

One class file is going to contain, all the private fields and public properties and the other class file is going to contain the two public methods.

First, delete the Employee.cs class file from the project. Then we need to add two class file with the name PartialEmployeeOne and PartialEmployeeTwo.

To do so, right click on the project and add a class file with name PartialEmployeeOne.cs and copy and paste the following code.

namespace PartialDemo
{
    public partial class PartialEmployee
    {
        private string _firstName;
        private string _lastName;
        private double _salary;
        private string _gender;

        public string FirstName
        {
            get { return _firstName; }
            set { _firstName = value; }
        }
        public string LastName
        {
            get { return _lastName; }
            set { _lastName = value; }
        }
        public double Salary
        {
            get { return _salary; }
            set { _salary = value; }
        }
        public string Gender
        {
            get { return _gender; }
            set { _gender = value; }
        }
    }
}

Note: Here the class file name is PartialEmployeeOne.cs but the class name is PartialEmployee

Notice that in the above code, the PartialEmployee class is marked with the partial keyword and it contains only the 4 private fields and the 4 public properties. Next, we need to add PartialEmployeeTwo.cs.

Adding PartialEmployeeTwo.cs

To do so, right click on the project and add a class file with name PartialEmployeeTwo.cs and copy and paste the following code.

namespace PartialDemo
{
    public partial class PartialEmployee
    {
        public void DisplayFullName()
        {
            Console.WriteLine(@"Full Name is :  {0} {1}", _firstName, _lastName);
        }

        public void DisplayEmployeeDetails()
        {
            Console.WriteLine("Employee Details : ");
            Console.WriteLine(@"First Name : {0}", _firstName);
            Console.WriteLine(@"Last Name : {0}", _lastName);
            Console.WriteLine(@"Gender : {0}", _gender);
            Console.WriteLine(@"Salary : {0}", _salary);
        }
    }
}

Note: Here the class file name is PartialEmployeeTwo.cs but the class name is PartialEmployee

Notice that in the above code, the PartialEmployee class is also marked with the partial keyword and it contains only the two public methods.

Here, we are able to access the private fields, _firstName, _lastName, _salary, and _gender, that are defined in PartialEmployeeOne.cs file.

Now Modify the Main method of the Program class as shown below to use the PartialEmployee class.

namespace PartialDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            PartialEmployee emp = new PartialEmployee();
            emp.FirstName = "Pranaya";
            emp.LastName = "Rout";
            emp.Salary = 100000;
            emp.Gender = "Male";
            emp.DisplayFullName();
            emp.DisplayEmployeeDetails();

            Console.WriteLine("Press any key to exist.");
            Console.ReadKey();
        }
    }
}

Now run the application and see the out.

Partial Classes and Partial Methods in C#

When we need a Partial Class in C#?

There are several situations when splitting a class definition is desirable

  1. When working on large projects, splitting a class over separate files allows multiple programmers to work on it simultaneously.
  2. When working with automatically generated source code, the code can be added to the class without having to recreate the source file. Visual Studio uses this approach when creating windows form, web service wrapper code and so on.
Rules to follow when working with Partial Classes in C#:

All the parts spread across different class files, must use the partial keyword. Otherwise, a compiler error is raised. Missing partial modifier. Another partial declaration of this type exists.

All the parts spread across different files, must have the same access modifiers. Otherwise, a compiler error is raised. Partial declarations have conflicting accessibility modifiers.

If any of the parts are declared as abstract, then the entire type is considered as abstract or if any of the parts are declared as sealed, then the entire type is considered as sealed or if any of the parts inherit a class, then the entire type inherits that class. 

C# does not support multiple class inheritance. Different parts of the partial class must not specify different base classes. The following code will raise a compiler error stating – Partial declarations must not specify different base classes.

public class Employee
{
}
public class Customer
{
}
public partial class PartialClass : Employee
{
}
public partial class PartialClass : Customer
{
}

Different parts of the partial class can specify different base interfaces and the final type implements all of the interfaces listed by all of the partial declarations. 

In the example below PartialClass needs to provide implementation for both IEmployee, and ICustomer interface methods.

public interface IEmployee
{
    void EmployeeMethod();
}
public interface ICustomer
{
    void CustomerMethod();
}

public partial class PartialClass : IEmployee
{
    public void EmployeeMethod()
    {
        //Method Implementation
    }
}
public partial class PartialClass : ICustomer
{
    public void CustomerMethod()
    {
        //Method Implementation
    }
}

NOTE: Any members that are declared in a partial definition are available to all of the other parts of the partial class. Once we understand Partial Classes in C#, let’s understand Partial Methods in C#.

In the next article, I am going to discuss Partial Methods in C# with some examples. Here, in this article, I try to explain Partial Classes in C# with some examples. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *