Partial Class and Partial Methods in C#

What are partial classes?

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.

Let’s understand partial classes 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#

Now let us split 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.

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?

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:

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#.

Partial methods in C#:

A partial class or a struct can contain partial methods. A partial method is created using the same partial keyword.

Let us understand partial methods with an example. Create a console application. Add a class file with name PartialClassOne.cs to the project. Copy and paste the following code. 

namespace PartialDemo
{
    partial class PartialClass
    {
        // Declaration of the partial method.
        partial void PartialMethod();

        // A public method calling the partial method
        public void PublicMethod()
        {
            Console.WriteLine("Public Method Invoked");
            PartialMethod();
        }
    }
}

Notice that the PartialMethod() definition has the partial keyword and does not have a body(implementation) only the signature. The implementation of a partial method is optional. If we don’t provide the implementation, the compiler removes the signature and all calls to the method.

The implementation can be provided in the same physical file or in another physical file that contains the partial class. In this example, the partial PartialMethod() is invoked within the PublicMethod().

Copy and paste the following code in the Main() method of the Program class.
namespace PartialDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            PartialClass SC = new PartialClass();
            SC.PublicMethod();
            
            Console.WriteLine("Press any key to exist.");
            Console.ReadKey();
        }
    }
}
OUTPUT:

Partial Class and Partial Methods in C#

When we run the application, now notice that we don’t get a compiler error, in spite of not having an implementation for the partial PartialMethod(). Since the implementation of the partial method is missing, the compiler will remove the signature and all calls to the method.

Now add a class file with name PartialClassTwo.cs. Copy and paste the following code. The implementation for the partial method is provided here.

namespace PartialDemo
{
    partial class PartialClass
    {
        // Partial method implemented
        partial void PartialMethod()
        {
            Console.WriteLine("Partial PartialMethod  Invoked");
        }
    }
}

Now, run the console application and notice the output. The partial method and the public method messages are printed on the console as shown below.

Partial Class and Partial Methods in C#

So, a partial method declaration consists of two parts. 

1. The definition (only the method signature ending with a semi-colon, without method body)

2. The implementation. 

Partial methods are private by default and it is a compile-time error to include any access modifiers, including private. The following code will raise an error stating – A partial method cannot have access modifiers or the virtual, abstract, override, new, sealed, or extern modifiers.

partial class PartialClass
{ 
    private partial void PartialMethod();
}

It is a compile-time error to include declaration and implementation at the same time for a partial method. The code below produces a compile-time error – No defining declaration found for implementing declaration of partial method ‘PartialDemo.PartialClass.partialMethod()’

partial class PartialClass
{
    partial void PartialMethod()
    {
        Console.WriteLine("PartialMethod Implemented");
    }
}

A partial method return type must be void. Including any other return type is a compile-time error – Partial methods must have a void return type

partial class PartialClass
{ 
    partial int PartialMethod();
}

A partial method must be declared within a partial class or partial struct. A non-partial class or struct cannot include partial methods.

Signature of the partial method declaration must match with the signature of the implementation.

A partial method can be implemented only once. Trying to implement a partial method more than once raises a compile-time error – A partial method may not have multiple implementing declarations. 

SUMMARY:

In this article, I try to explain Partial Classes and Partial Methods 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 *