Ramesh is UX specialist & Yadav is C# developer; Both are working for a project and building a screen in windows form application and needs the same class file; Ramesh want 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#.
- What are partial classes?
- When to use partial class?
- How to create partial class in C#
- Real world example of partial class
- 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 other 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, where as 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 string _name;
public Customer(string name)
_name = name;
Let's define other partial class.
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
Let's discuss about two examples of partial class. One in Windows Form application and other in ASP.NET web application.