Click here to Skip to main content
11,641,668 members (64,629 online)
Click here to Skip to main content

Four real world uses of Partial classes and Partial methods

, 17 Jan 2012 CPOL 128.4K 105
Rate this:
Please Sign up or sign in to vote.
In this article we will explain for real world use of Partial classes and partial methods.

Table of contents


Recently I was researching about partial classes and their real world use. Many of the postings found on Google talked about the concept of partial classes and partial methods, but very few highlighted in what scenarios to use them.

In this article, we will first start with the fundamentals of partial classes and methods and then discuss four real world uses. I have also created a video here where I have discussed about partial classes and shown their real world use.

Fundamentals of partial classes

A partial class allows a single class to be divided into two separate physical files. During compile time, these files get compiled into a single class. For instance, you can see in the below figure we have the customer class divided into two different files “customer1.cs” and “customer2.cs”.

During compilation, these files get compiled into a single class internally. So when you create an object of the Customer class, you will be able to see methods lying in both the physical files. For instance, you can see the Add method belongs to customer1.cs and the Delete method belongs to customer2.cs, but when the Customer object is created, we can see both the Add and Delete methods.

Fundamentals of partial methods

There is one more important concept in partial classes called partial methods. Partial methods helps us to define a method in one physical file and we can implement that method in another physical file, as shown in the below figure.

In the figure, you can see we have defined the Validate method in Customer1.cs and this Validate method is implemented in Customer2.cs. Please note the partial keywords attached to both of these methods.

Use number 1: ASP.NET auto generated code

The biggest use of partial classes is in technologies where there is code generation. The Microsoft team themselves use partial classes in ASP.NET, LINQ, and EF code generation. For instance when we look at ASP.NET, there are two parts: the auto generated code of a page and the code-behind where you write your custom logic.

The custom logic is written in the “.aspx.cs” file while the auto generated logic is in the “.aspx.designer.cs” file, as shown in the below figure.

As a developer, you would like the auto generated code to do its work, i.e., generate code when you drag and drop a button in the ASP.NET designer.

Below is how the auto generated code looks like:

public partial class WebForm1 {
    /// <summary>
    /// form1 control.
    /// <remarks>
    /// Auto-generated field.
    /// To modify move field declaration from designer file to code-behind file.
    /// </remarks>
    protected global::System.Web.UI.HtmlControls.HtmlForm form1;
    /// <summary>
    /// Button1 control.
    /// </summary>
    /// <remarks>
    /// Auto-generated field.
    /// To modify move field declaration from designer file to code-behind file.
    /// </remarks>
    protected global::System.Web.UI.WebControls.Button Button1;
    /// <summary>
    /// Label1 control.
    /// </summary>
    /// <remarks>
    /// Auto-generated field.
    /// To modify move field declaration from designer file to code-behind file.
    /// </remarks>
    protected global::System.Web.UI.WebControls.Label Label1;

At the same time, you would also like to customize the code in some other file in such a way that the auto generation part is not disturbed. For that, ASP.NET provides the “.aspx.cs” file which is a partial class where you can put your own custom logic.

public partial class WebForm1 : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)
        // Your custom logic

This is only possible when the class is split into two physical files but united via the partial keyword. So if you look at any ASP.NET code-behind class file, it’ll be marked with the word partial.

By using the partial keyword in ASP.NET, the Microsoft team has made VS and developers work side by side thus not fiddling with each other’s code and increasing productivity.

Use number 2: LINQ and Entity Framework

LINQ and EF also use partial classes and methods heavily because of the auto generation nature of these technologies. So when you drag tables in these framework, they create auto generated classes as shown in the below figure.

In the figure, you can see how the auto generated code has partial classes and partial methods.

The partial methods later can be extended to put custom logic. For instance, you can see in the below code that for the above auto-generated class tblCustomer, we have used partial methods to override the OnCustomerCodeChanged event to ensure that customer code is not more than 8 characters.

public partial class tblCustomer
    partial void OnCustomerCodeChanged()
        if (_CustomerCode.Length > 8)
            throw new Exception("Customer code can not be greater than 8");

So by using partial classes and partial methods, LINQ and EF keep auto generating classes and by using partial methods, we can customize the classes with our own logic.

Use number 3: Better maintenance by compacting large classes

The other important use of partial classes is for better maintenance of the project. If you have large classes with lots of methods as shown in the figure, it’s a bit of a pain to maintain those classes.

By using partial classes, you can split them into physical files as shown in the below figure, thus making your project better and easy to maintain.

Use number 4: Multiple people working on the same class

The last and final real world use I see of partial classes is when we want developers to work simultaneously in the same class. I agree this can be a very rare use as there are better options like using a version control software like TFS or Subversion, but in case you want something quick and local, this option is not bad at all.

You can also watch my 500 videos on different technologies like .NET, C#, Silverlight, Azure, VSTS, WCF, WPF, WWF, SharePoint, Design Patterns, UML, and lots more.


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


About the Author

Shivprasad koirala
India India

I am an ex-Microsoft MVP for ASP/ASP.NET and currently a CEO of a small
E-learning company in India. We are very much active in making training videos, writing books and corporate trainings. Do visit my site for 
.NET, C#, Design Pattern, WCF, Silverlight, LINQ, ASP.NET, ADO.NET, SharePoint, UML, SQL Server  training 
and Interview questions and answers

You may also be interested in...

Comments and Discussions

SuggestionOne more GREAT use with partial class in code first Pin
Member 1170982917-Jun-15 20:35
memberMember 1170982917-Jun-15 20:35 
GeneralMy vote of 4 Pin
raven8er17-Sep-14 5:56
memberraven8er17-Sep-14 5:56 
SuggestionAnother Use Case Pin
FIorian Schneidereit10-Jul-14 22:18
memberFIorian Schneidereit10-Jul-14 22:18 
GeneralRe: Another Use Case Pin
Franc Morales13-Nov-14 23:16
memberFranc Morales13-Nov-14 23:16 
QuestionC# concept applied to C++/CLI? Pin
RogueClay10-Jun-14 10:24
memberRogueClay10-Jun-14 10:24 
GeneralRe: C# concept applied to C++/CLI? Pin
PIEBALDconsult10-Jun-14 11:36
memberPIEBALDconsult10-Jun-14 11:36 
GeneralRe: C# concept applied to C++/CLI? Pin
Shivprasad koirala12-Jun-14 18:56
mvpShivprasad koirala12-Jun-14 18:56 
QuestionMessage Automatically Removed Pin
3-Apr-14 22:35
memberAyesha Sharma3-Apr-14 22:35 
GeneralVery clear! Pin
Tam Mai19-Jan-14 3:35
memberTam Mai19-Jan-14 3:35 
GeneralMy vote of 5 Pin
Pratik Bhuva19-Nov-13 19:29
professionalPratik Bhuva19-Nov-13 19:29 
QuestionVery nice Pin
jagadishkr15-Jul-13 21:59
memberjagadishkr15-Jul-13 21:59 
GeneralMy vote of 5 Pin
Juhi Paunikar8-Jul-13 0:25
memberJuhi Paunikar8-Jul-13 0:25 
GeneralMy vote of 5 Pin
csharpbd19-Jun-13 8:27
membercsharpbd19-Jun-13 8:27 
Questiongr8 Pin
lovelyim31-May-13 5:44
memberlovelyim31-May-13 5:44 
GeneralMy vote of 5 Pin
Member 92709757-May-13 0:05
memberMember 92709757-May-13 0:05 
QuestionWell Done. Pin
Justin Shepertycki12-Mar-13 8:14
memberJustin Shepertycki12-Mar-13 8:14 
GeneralNice Article Shiv Pin
rajneeshrai7-Mar-13 21:06
memberrajneeshrai7-Mar-13 21:06 
GeneralMy vote of 5 Pin
VitorHugoGarcia7-Mar-13 3:34
memberVitorHugoGarcia7-Mar-13 3:34 
GeneralMy vote of 5 Pin
Daniele Rota Nodari10-Feb-13 23:33
memberDaniele Rota Nodari10-Feb-13 23:33 
GeneralMy vote of 5 Pin
Praveen Raghuvanshi18-Jan-13 6:04
memberPraveen Raghuvanshi18-Jan-13 6:04 
Answercc Pin
jaiyaprada2-Jan-13 1:14
memberjaiyaprada2-Jan-13 1:14 
SuggestionObsolete members Pin
jswolf1926-Oct-12 16:16
memberjswolf1926-Oct-12 16:16 
GeneralMy vote of 5 Pin
sathish5712-Oct-12 3:40
membersathish5712-Oct-12 3:40 
GeneralMy vote of 4 Pin
thalavi31-Jul-12 2:17
memberthalavi31-Jul-12 2:17 
GeneralMy vote of 5 Pin
Anoop Ananthan19-Jul-12 20:46
memberAnoop Ananthan19-Jul-12 20:46 
GeneralMy vote of 1 Pin
thomsenj7231-Mar-12 0:13
memberthomsenj7231-Mar-12 0:13 
QuestionI haven't voted: Pin
Keith Barrow18-Feb-12 22:22
mentorKeith Barrow18-Feb-12 22:22 
AnswerRe: I haven't voted: Pin
Shivprasad koirala20-Feb-12 6:47
memberShivprasad koirala20-Feb-12 6:47 
Thanks for the valuable comments.
Keith Barrow wrote:
If classes are this large, then there is probably (as opposed to definately) something wrong with them

Partial classes divides the class in to physical files thus leading to code you want to look or concentrate on , rather than the whole thing. I loved when in the new versions of ASP.NET behind code i was only looking at my custom UI events and not the declarations of UI objects. At the end its one logical class so partial classes no where helps in either SRP or anything. That angle thinking is totally wrong and neither i have presented in the article.

Keith Barrow wrote:
The other thing is that instead of having one canonical file containing the class, we now hav to look in multiple places

Why not think the other way, rather than looking in to many code, i look at what i need. Classic example is the ASP.NEt behind code. You have a code you want your developers to go and extend but not touching some core functions and also they all finally end up in to one class.

Keith Barrow wrote:
Use number 4: Multiple people working on the same class" because this implies code changes to accomodate working practises (about as wrong as changing code for test IMO).

I agree to your point. I have just put as a browny point and i agree its controversial.

thanks it made my day i learnt.
My book .NET interview questions with 500 mostly asked questions in .NET world .NET Interview questions and answers

AnswerRe: I haven't voted: Pin
mark merrens9-Mar-12 7:54
membermark merrens9-Mar-12 7:54 
GeneralMy vote of 3 Pin
Clifford Nelson15-Feb-12 11:00
memberClifford Nelson15-Feb-12 11:00 
Questionnice Pin
CIDev13-Feb-12 9:54
memberCIDev13-Feb-12 9:54 
GeneralMy vote of 5 Pin
Rene Pilon11-Feb-12 7:03
memberRene Pilon11-Feb-12 7:03 
GeneralMy vote of 5 Pin
Mihai MOGA8-Feb-12 6:34
memberMihai MOGA8-Feb-12 6:34 
GeneralMy vote of 5 Pin
Sridhar Patnayak6-Feb-12 17:10
memberSridhar Patnayak6-Feb-12 17:10 
GeneralMy vote of 5 Pin
KevinQiang.K6-Feb-12 6:51
memberKevinQiang.K6-Feb-12 6:51 
SuggestionPartial methods feel like premature optimization. Pin
Dwayne J. Baldwin28-Jan-12 6:46
memberDwayne J. Baldwin28-Jan-12 6:46 
GeneralMy vote of 5 Pin
Azhar Iqbal SE24-Jan-12 20:05
memberAzhar Iqbal SE24-Jan-12 20:05 
GeneralMy vote of 5 Pin
Kanasz Robert24-Jan-12 11:17
mvpKanasz Robert24-Jan-12 11:17 
GeneralMy vote of 5 Pin
SChristmas20-Jan-12 3:09
memberSChristmas20-Jan-12 3:09 
GeneralMy vote of 3 Pin
Jacek Gajek18-Jan-12 6:28
memberJacek Gajek18-Jan-12 6:28 
GeneralRe: My vote of 3 Pin
Shivprasad koirala20-Feb-12 7:05
memberShivprasad koirala20-Feb-12 7:05 
GeneralRe: My vote of 3 Pin
Jacek Gajek20-Feb-12 12:26
memberJacek Gajek20-Feb-12 12:26 
QuestionSeparate Data and Code in WCF Pin
Member 136679718-Jan-12 4:51
memberMember 136679718-Jan-12 4:51 
QuestionNice Pin
surajfrommumbai18-Jan-12 0:46
membersurajfrommumbai18-Jan-12 0:46 
GeneralMy vote of 2 Pin
Klaus Luedenscheidt17-Jan-12 19:10
memberKlaus Luedenscheidt17-Jan-12 19:10 
GeneralRe: My vote of 2 Pin
Shivprasad koirala18-Jan-12 0:53
memberShivprasad koirala18-Jan-12 0:53 
GeneralRe: My vote of 2 Pin
Shivprasad koirala18-Jan-12 1:05
memberShivprasad koirala18-Jan-12 1:05 
GeneralRe: My vote of 2 Pin
James H18-Jan-12 5:58
memberJames H18-Jan-12 5:58 
GeneralRe: My vote of 2 Pin
bryce23-Jan-12 15:43
memberbryce23-Jan-12 15:43 
GeneralRe: My vote of 2 Pin
Mohammad A Rahman18-Feb-12 22:28
memberMohammad A Rahman18-Feb-12 22:28 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150731.1 | Last Updated 17 Jan 2012
Article Copyright 2012 by Shivprasad koirala
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid