What is a partial class in C#

The concept of partial classes gives huge power to software engineering teams working on software application projects using .net technologies. This concept does not make code writing easy, rather it makes working in large teams easy. Let’s explain this with an example

Suppose you have a software team with 10 team members. Our of these 10 team members there are 4 team members who need to work on the same class and add functionality to it. To give a twist to the story let’s assume that these 4 team members are very angry in nature and don’t like each other. So there are chances that they will delete each other’s code and create problems for the project (although this never happens, we are just taking an extreme example to explain the use of partial classes). Now as a project manager you want to use the partial classes feature of C# to avoid any type of fights in your team.

How to use partial classes

To have peace in your team you decide to create 4 different files for each team member to work on. But if you create a class with the same name in 4 different files then the C# compiler will throw an error. What to do? This is where partial classes come into picture. You can create 4 classes with the same name in 4 different files just by marking them as partial. This way each of the team members will get his own file to work on and in each file they will have a partial class.

When the C# compiler will compile the source code it will compile all the parts of the partial class and combine them to make one class at the end. Take a look at the code below

// Code in file Test_TeamMember1.cs  namespace ConsoleApplication4  {      public partial class Test      {       // First team member adds Function1          public void Function1()          {            }      }  }
// Code in file Test_TeamMember2.cs  namespace ConsoleApplication4  {      public partial class Test      {       // Second team member adds Function2          public void Function2()          {            }      }  }
// Code in file Test_TeamMember3.cs  namespace ConsoleApplication4  {      public partial class Test      {       // Third team member adds Function3          public void Function3()          {            }      }  }
// Code in file Test_TeamMember4.cs  namespace ConsoleApplication4  {      public partial class Test      {       // Fourth team member adds Function4          public void Function4()          {            }      }  }

After compilation the final Test class will have all 4 functions

Partial classes in C#
 

Quick Links

E-Magazines

@

Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..

Ok

Login to Open ESchool OR Create your account    Login   SignUp