Click here to Skip to main content
15,558,870 members
Articles / Programming Languages / C#
Posted 10 Jan 2014


63 bookmarked

Partial Classes in C# With Real Example

Rate me:
Please Sign up or sign in to vote.
4.70/5 (69 votes)
29 Dec 2014CPOL5 min read
I explain partial classes in C# language with an example


In this article, I explain partial classes in C# language with an example. A partial class splits the definition of a class over two or more source files. You can create a class definition in multiple files but it will be compiled as one class.

Suppose you have a "Person" class. That definition is divided into the two source files "Person1.cs" and "Person2.cs". Then these two files have a class that is a partial class. You compile the source code, then create a single class. Let's see that in Figure 1.1.

Partial class and compiled class in C#

Figure 1.1 : Partial class and compiled class

Advantages of a Partial Class

Here is a list of some of the advantages of partial classes: 

  1. You can separate UI design code and business logic code so that it is easy to read and understand. For example, you are developing a web application using Visual Studio and add a new web form then there are two source files, "aspx.cs" and "aspx.designer.cs". These two files have the same class with the partial keyword. The ".aspx.cs" class has the business logic code while "aspx.designer.cs" has user interface control definition.
  2. When working with automatically generated source, the code can be added to the class without having to recreate the source file. For example, you are working with LINQ to SQL and create a DBML file. Now when you drag and drop a table, it creates a partial class in designer.cs and all table columns have properties in the class. You need more columns in this table to bind on the UI grid but you don't want to add a new column to the database table so you can create a separate source file for this class that has a new property for that column and it will be a partial class. So that does affect the mapping between database table and DBML entity but you can easily get an extra field. It means you can write the code on your own without messing with the system generated code.
  3. More than one developer can simultaneously write the code for the class.
  4. You can maintain your application better by compacting large classes. Suppose you have a class that has multiple interfaces so you can create multiple source files depending on interface implements. It is easy to understand and maintain an interface implemented on which the source file has a partial class. Let's see the following code snippet.
    public interface IRegister
        //Register related function
    public interface ILogin
        //Login related function
    //UserRegister.cs file
    public partial classUser : IRegister, ILogin
        //implements IRegister interface
    //UserLogin.cs file
    public partial classUser
        //implements ILogin interface

Points That You Should be Careful about Partial Classes

There are some points that you should be careful about when you are developing a partial class in your application.

  1. You need to use partial keyword in each part of partial class.
  2. The name of each part of partial class should be the same but source file name for each part of partial class can be different.
  3. All parts of a partial class should be in the same namespace.
  4. Each part of a partial class should be in the same assembly or DLL, in other words you can't create a partial class in source files of a different class library project.
  5. Each part of a partial class has the same accessibility.
  6. If you inherit a class or interface on a partial class, then it is inherited on all parts of a partial class.
  7. If a part of a partial class is sealed, then the entire class will be sealed.
  8. If a part of partial class is abstract, then the entire class will be an abstract class.

Using the Code

I will develop an example that explains how to use a partial class in your project. Suppose you are working with LINQ to SQL in your application. So you create a data context, in other words a .dbml file and drag and drop the necessary tables. Each table creates a partial class in the data context designer file and each table field becomes a property for the table. Suppose you have a "Person" table that has the three fields "Id","Name" and "DateOfBirth" and you want to show the age of each person in a grid view. What will you do? If you add a new column to the table for age in database for the "Person" table then it fails the normalization rule so you should not do that. If you add a new property to auto-generated code, then it will not be mapped to the database. So you need to create a partial class portion in a separate source file that has the "Age" property. This "Age" property calculates the age of the person when you bind a person list to the grid view. Let's see each step-by-step.

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

    You need to create a person table in the database that has the three fields "Id","Name" and "DateOfBirth". The "Id" field is the primary key.

    Id int identity(1,1)primary key,
    Name nvarchar(50),
    DateOfBirthDate default getUtcDate()
  2. Create a web application from Visual Studio.
  3. Right-click on the project in the Solution Explorer, then go to "Add" and click on "Class".
  4. Choose "LINQ to SQL Classes" from the list and provide the name "Person" for the DBML name. Then click on "Add".
  5. Drag the User table from the database in the Server Explorer and drop onto the O/R Designer surface of the "Person.dbml" file.

    Person Entity

    Figure 1.2: Person entity

    Now you can open the "Person.designer.cs" file. In the file, the "Person" partial class has been created for drag and drops a "Person" table from database on O/RM surface.

  6. Create a partial class part that has the "Age" property to calculate the age. This file is named "PersonExtension.cs".
    using System;
    namespace PartialClassExample
       public partial class Person
            public int Age
               get { return Convert.ToInt32(System.DateTime.UtcNow.Date.Year - _DateOfBirth.Value.Year); }
  7. Create a UI design to show a person's details in the grid view.
    <%@Page Language="C#"AutoEventWireup="true"
    <head id="Head1"runat="server">
  8. Write code for the "Page_Load" event to bind a grid view by person list in the code behind file.
    using System;
    using System.Linq;
    namespace PartialClassExample
       public partial class PersonUI : System.Web.UI.Page
           protected void Page_Load(object sender, EventArgs e)
               using (PersonDataContext context =new PersonDataContext())
                   var query = from person in context.GetTable<person>()
                                select new
                   var content = query.ToList();
                    gridPerson.DataSource = content;
  9. Run the application, you will see the Age column in the grid view that shows the age of each person. Let's see that in Figure 1.3.


    Figure 1.3: Output


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Software Developer
India India
He is awarded for Microsoft TechNet Guru, CodeProject MVP and C# Corner MVP.

Comments and Discussions

GeneralRe: 1 Question Pin
Antonio Ripa31-Dec-14 2:54
professionalAntonio Ripa31-Dec-14 2:54 
QuestionTutorial is very clear Pin
Member 1119161429-Oct-14 20:38
Member 1119161429-Oct-14 20:38 
AnswerRe: Tutorial is very clear Pin
Sandeep Singh Shekhawat22-Nov-14 16:48
professionalSandeep Singh Shekhawat22-Nov-14 16:48 
GeneralMy vote of 3 Pin
Klaus Luedenscheidt13-Sep-14 19:06
Klaus Luedenscheidt13-Sep-14 19:06 
GeneralRe: My vote of 3 Pin
Sandeep Singh Shekhawat14-Sep-14 5:08
professionalSandeep Singh Shekhawat14-Sep-14 5:08 
GeneralRe: My vote of 3 Pin
reeselmiller229-Dec-14 21:31
reeselmiller229-Dec-14 21:31 
GeneralRe: My vote of 3 Pin
PIEBALDconsult30-Dec-14 18:16
professionalPIEBALDconsult30-Dec-14 18:16 
GeneralRe: My vote of 3 Pin
Klaus Luedenscheidt30-Dec-14 19:27
Klaus Luedenscheidt30-Dec-14 19:27 
Certainly not; there are many reasons, just maybe not reasons you have experienced yet.

Not all you can do you should do... I can imagine many situations where i could use partial classes, but most of them will lead to more unreadable code for me. It's like placing more than one class in a single source file. I have an example in the (great) Cinch MVVM framework. Sasha placed platform specific code into separate partial classes. I found an error and wondered why the method was not in the source file i mentioned. It took me a while to recognize that the method was placed in another partial class.

You seem to have very little imagination.

I don't say that only one programmer should work on a single class, but they shouldn't work on it simultaneously. And it should never be the only reason to split a class into partial classes. If it's necessary to fulfill your project goals you should think about your project organization. In my over 30 years of programming experience i never had a situation where multiple programmers need to edit the same source code simultaneously.

It's not all about size.

I agree that it's not all about size, but it's an important part. For example: Some time ago i had to migrate a VB6 application to .NET. The VB6 programmers had put the logic for all reports of the application into a single class which leads to a source size of about 50.000 lines. The VB editor of Visual Studio 2010 couldn't manage this file properly. It decreases the performance of Visual Studio significantly. After splitting it into one class per report Visual Studio was fast as a lightning. Not only this, changes where much easier just because the code to be changed was found faster, i could place some common logic into base classes and there fore reduce the size of the code more than 50%.
GeneralThoughts Pin
PIEBALDconsult13-Sep-14 5:55
professionalPIEBALDconsult13-Sep-14 5:55 
GeneralRe: Thoughts Pin
CS201116-Sep-14 5:17
professionalCS201116-Sep-14 5:17 
GeneralGood Job Pin
Member 1087962328-Jul-14 19:40
Member 1087962328-Jul-14 19:40 
GeneralRe: Good Job Pin
Sandeep Singh Shekhawat30-Aug-14 17:44
professionalSandeep Singh Shekhawat30-Aug-14 17:44 
GeneralMy vote of 5 Pin
Ștefan-Mihai MOGA14-Feb-14 18:05
professionalȘtefan-Mihai MOGA14-Feb-14 18:05 
GeneralRe: My vote of 5 Pin
Sandeep Singh Shekhawat30-Aug-14 17:45
professionalSandeep Singh Shekhawat30-Aug-14 17:45 
GeneralMy vote of 5 Pin
ThatsAlok10-Feb-14 2:49
ThatsAlok10-Feb-14 2:49 
GeneralRe: My vote of 5 Pin
Sandeep Singh Shekhawat10-Feb-14 3:13
professionalSandeep Singh Shekhawat10-Feb-14 3:13 
Questiongood work Pin
winnervijay7-Feb-14 7:42
winnervijay7-Feb-14 7:42 
AnswerRe: good work Pin
Sandeep Singh Shekhawat30-Aug-14 17:43
professionalSandeep Singh Shekhawat30-Aug-14 17:43 
SuggestionCan u provide detail steps for the coding? Pin
yuzaihuan23-Jan-14 17:37
yuzaihuan23-Jan-14 17:37 
GeneralRe: Can u provide detail steps for the coding? Pin
Sandeep Singh Shekhawat30-Aug-14 17:46
professionalSandeep Singh Shekhawat30-Aug-14 17:46 
GeneralMy vote of 1 Pin
Antonio Ripa14-Jan-14 5:37
professionalAntonio Ripa14-Jan-14 5:37 
GeneralRe: My vote of 1 Pin
PIEBALDconsult30-Dec-14 5:46
professionalPIEBALDconsult30-Dec-14 5:46 
GeneralRe: My vote of 1 Pin
Antonio Ripa31-Dec-14 3:01
professionalAntonio Ripa31-Dec-14 3:01 
GeneralRe: My vote of 1 Pin
PIEBALDconsult31-Dec-14 5:41
professionalPIEBALDconsult31-Dec-14 5:41 
GeneralRe: My vote of 1 Pin
Antonio Ripa31-Dec-14 7:40
professionalAntonio Ripa31-Dec-14 7:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.