Each source file contains the definition and declaration of methods that are combined when an application is compiled. We can split classes, structures, interfaces, and other methods using the various source files. 

Partial classes help split the methods into two or more source(.cs) files. All the partial classes will be combined when the whole program is compiled.

Partial Class is a unique feature of C#. It can break the functionality of a single class into many files. When the application is compiled, these files are then reassembled into a single class file. The partial keyword is used to build a partial class. 

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

Use of Partial Classes

Following are the scenarios where splitting the files becomes necessary:

  1. If you are working on a bigger project, splitting the files over different classes helps developers work on the same project simultaneously.
  2. If you are working on an automatically generated source, then the code can be added to the class without regenerating the source file.
  3. The visual studio which creates windows forms, web service wrapper code, and some other files automatically, uses this partial class method to split it into files without modifying them.
  4. Partial classes can be helpful if you are using source generators to generate additional functionality.

We can split the class definition by using the partial keyword modifier as shown in the image below.

The partial keyword denotes that other parts of class, method, and function can be defined here. 

public partial class Students {

    private string Name;

    private int Roll no;

    public Students(string a, int t)

    {

        this.Student_name = a;

        this.Roll_no = t;

    }

}

Listed below are some of the file types which are merged from the partial classes:

  1. XML comments
  2. interfaces
  3. generic-type parameter attributes
  4. class attributes
  5. members

Advantages of a Partial Class

1. With the help of partial classes, you can separate UI design code and business logic code.

For instance, if we develop a web application using the visual studio, some of the source files will get added. These files will have partial keywords. There is a ".aspx.cs" class that has the business logic code and "aspx.designer.cs" that has user interface control definition.

2. We are not required to regenerate the source file when working with automatically-generated files. 

For instance, when working with LINQ to SQL and creating a DBML file. When we copy and paste a table, it will create a partial class in designer.cs. So to not add new columns, we can create a separate source file for the class, which will act as a partial class.

3. More developers can work simultaneously on the same project.

4. It is easier to maintain, understand, and develop a partial class than a huge class for the whole program. A huge file can be converted into many partial classes containing various methods and classes.

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

Points to Remember

  • All partial classes must contain the partial keyword.
  • Partial classes can elaborate on various base classes that will be combined at the compiler time. Any method, interface, and function declared on a partial class is available for all the other parts.
  • The source file name for each part of the partial class can be different, but each partial class’s name must be the same.
  • The name of all parts of a partial class should be the same.
  • All parts of a partial class should be in the same assembly.
  • All classes should have public, private, or another accessibility modifier; the accessibility of each part of the partial class should be the same. 
  • If we inherit a class or method on a partial class, it will also be inherited for all parts of the partial class.
  • If any part of the class is declared with any specific access modifier, then the whole class will be considered of the same type. 
  • If any part of the class is declared abstract, then the whole type is abstract, and if any class is declared sealed, the whole class is sealed. 

Example:

We will create a partial class that will help us understand the use of partial classes in our projects. 

In this example, we are working with LINQ to SQL applications to create Name, Roll no, and Date of Birth columns for students. We will then create a separate partial class with a Roll no property.

1. Create a "Student" table in the database.

We will need to create a student table in the database that has the three fields "Name", "RollNo", and "DateOfBirth". The "Name" field is the primary key.

CREATE TABLE Student  

(

Class int identity(1,1) primary key,  

Name nvarchar(50),    

DateOfBirth Date defaultgetUtcDate() 

2. We will create a web application from the visual studio.

3. Next, we will add a new class using the add function on the solution explorer.

4. Choose "LINQ to SQL Classes" from the list of partial classes and provide the name "Student" for the DBML name. Then we will click on "Add".

5. We will then copy the User table from the database in the Server Explorer and paste it into the Designer surface of the "Student.dbml" file.

6. Now we can open the "Student.designer.cs" file. We see the "Student" partial class has been created. We can now drag and drop a "Student" table from the database on the surface.

7. Create a UI design to show students’ details in the grid view from the data provided.

<%@Page Language="C#" AutoEventWireup="true" CodeBehind="StudentUI.aspx.cs" Inherits="PartialClassExample.PersonUI"%>  

<!DOCTYPE html>  

<html xmlns="http://www.w3.org/1999/xhtml">  

<head id="Head1" runat="server">  

<title></title>  

</head>  

<body>  

<form id="form1" runat="server">  

<div>  

    <asp:GridView Rollno="gridPerson" runat="server">  

    </asp:GridView>  

</div>  

</form>  

</body>  

</html>

8. We will write code for the "Page_Load" event to bind a grid view by student list in the code behind the file.

using System;  

using System.Linq;  

namespace PartialClassExample  

  {  

  • public partial class StudentUI : System.Web.UI.Page  
  • {  
  •     protected void Page_Load(object sender, EventArgs e)  
  •     {  
  •         using (StudentDataContext context =new StudentDataContext())  
  •         {  
  •             var query = from student in context.GetTable<Person>()  
  •                  select new  
  •                      {    
  •                          student.Name,  
  •                          student.DateOfBirth,  
  •                          student.RollNo  
  •                       };  
  •              var content = query.ToList();  
  •                 gridStudent.DataSource = content;  
  •                 gridStudent.DataBind();  
  •          }  
  •      }  
  •  }  

   }

9. On running this application, we will see the Roll no column in the grid view that will show each student’s age.

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

Conclusion

In this article on Partial Class in C#, we learned that with the help of partial classes, we can split our classes into multiple files. This is useful, especially when either the class definition is large or when you are working on a complex model or method, like with WinForms in Visual Studio designer. We also saw the advantages of using Partial Class in C# and some major key points to remember about Partial Class in C#.

To know more about partial class in C#, you can enroll in the Post-Graduate Program In Full-Stack Web Development offered by Simplilearn in collaboration with Caltech CTME. This Web Development course is a descriptive online bootcamp that includes 25 projects, a capstone project, and interactive online classes. In addition to ASP.NET, the course also details everything you need to become a full-stack technologist and accelerate your career as a software developer.

Simplilearn also offers free online skill-up courses in several domains, from data science and business analytics to software development, AI, and machine learning. You can take up any of these free courses to upgrade your skills and advance your career.

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 17 Jun, 2024

6 Months$ 8,000
Full Stack Developer - MERN Stack

Cohort Starts: 30 Apr, 2024

6 Months$ 1,449
Automation Test Engineer

Cohort Starts: 1 May, 2024

11 Months$ 1,499
Full Stack Java Developer

Cohort Starts: 14 May, 2024

6 Months$ 1,449