01 January 2014

partial class in c#

Ramesh is UX specialist & Yadav is a C# developer; Both are working for a project and building a screen in windows form application and needs the same class file; Ramesh wants to create user interface & Yadav want to add code behind logic. So you can see, there is a competition between these two guys for the same C# class file. Often it happens, they are overwriting each other changes and spending time in merging the changes.

This is definitely a problem and needs to be addressed. Using the partial class, the competition for the same c# class file problem can be solved. So let's go through the below sections to understand partial class in c#.

  1. What are partial classes?
  2. When to use partial class?
  3. How to create partial class in C#
  4. Real world example of partial class
  5. More about partial class

What are partial classes?

Partial class can be defined in more than one place; they can be defined in more than one file. A portion of the class can be written in a file and another part of the class can be coded in another different file.

When to use partial class?

If there is a class file which could be updated by different kind of authors, you should consider to use partial class. The authors can be C# developer, User Interface (UI) designer & tools like Visual Studio Win forms Designer.

For example, if you design windows form using the drag & drop feature of Visual Studio, then it's better to allow a different file for Visual Studio; as it will help separation of concerns. The developer is concerned about adding code-behind logic, whereas designer is concerned about a form's look and feel. Allowing these authors to work on different class files helps to avoid merge issues and get rid of file overwrite problems.

How to create partial class in C#

Partial classes will be created using the partial keyword.

public partial class Customer
{
  public string _name;
   
  public Customer(string name)
  {
    _name = name;
  }
}

Let's define other partial class.

public partial class Customer
{
   public void DisplayCustomerInfo()
   {
    Console.WriteLine("Customer name: "+ _name);
   }
}
  • As you can see the partial class Customer is defined in two different code snippets. These partial class definitions can exist different files.
  • The method DisplayCustomerInfo() can access the private member, _name defined in other partial class. It works because the class is same, but just that, they exist in two different files.

Real world example of partial class

Partial classes are mainly used by CODE Generators. On such example is with ASMX web service proxy generation in Visual Studio. Recently I blogged about the advantage of web service proxy classes being generated as Partial classes.

partial class practical use case with web service proxy regeneration