Introduction

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.

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.

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.

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.

Comments and Discussions

There is one more highly important usage of "partial class" in the real world example is --- If there is a table with huge number of columns and you are using code first-Entity Framework, you dont need to create entity for the entire table. We can use partial class to define entity classes for required columns only.

With this I believe we not only save lot of time but also can increase performance by not including unwanted columns.

I use that schema occasionally, depending on the complexity and design of the object structure. Partial classes are perfect to separate them and make it possible to stick to the "one class per file" rule.

Until now, I totally missed the partial method feature. :(It seems like C function prototypes with some more capability.I can see them working like conditional methods (ConditionalAttribute decorated ones) but with a more flexible approach.

Exellent article.i am using a code generator(made myself) using which I have created a Hospital management system in 4 months. I hope i can put good use to partial class and methods in my code generator. Thank you.

I want to vote, your article is well written and covers the topic well, but like a few other people have already mentioned I have reservations with a couple of cases:"Use number 3: Better maintenance by compacting large classes"If classes are this large, then there is probably (as opposed to definately) something wrong with them. For one thing it would imply a possible breaking of the Single-Responsibility principle in SOLID design. I'm not saying complex classes are out and out wrong, but they do have a bad code smell about them, and partial classes might encourage this. For the same reason I discourage the use of regions in code as the can do much the same thing, hiding complexity due to bad design.

The other thing is that instead of having one canonical file containing the class, we now hav to look in multiple places. To augment auto-generated code I'm prepared to do this because the alternatives are poorer. I don't thinkg this should be applied in case 3 and certainly not "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). For the same reason (i.e. more than one file) partial classes make security reviews more complicated as the reviewer now must make sure all partial class files are reviewed. OK the security review is not impossible, but it does add effort to the task.

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.

For the same reason I discourage the use of regions in code as the can do much the same thing, hiding complexity due to bad design.

Slightly spurious argument: just open the region to view - a code review will still find poor code wherever it is hiding! I find regions indispensable to compartmentalise code groups. For instance a region for construction, for events, etc. It just looks better and easire to navigate. (Yes, I know, not really a logical argument but quite satisfying, nonetheless).

"If you think it's expensive to hire a professional to do the job, wait until you hire an amateur." Red Adair.nils illegitimus carborundum

Nice try, but, as others said, partial classes was a terrible idea (or a remedy for MS bad WinForms design choices at the beginning) (but why a fresh WPF technology uses it too?). This should be stated in an article about them.When a class grew so big that it would need to be spread over more files (a common thing), then it has to be logically divided on a proper number of more specialized classes. Dot.

Partial classes is a good idea when it comes to RAD , but it was not good for ASP.NET behind code , that's the only mistake i think Microsoft has made about partial classes. That where Microsoft is getting it patched by MVC templates.

I find RAD is only possible if there is partial classes. LINQ , EF , WPF , ASP.NET , SL name any code technology every one has partial classes. I am sure Microsoft has given a thought to it.

If there where no partial classes i see myself dealing with the autogenerated code by the IDE and its a mess. I had it enough when i remember old ASP.NET behind code.

RAD is alive because there is partial classes in c# , or else i would be like those java guys coding for days to get my product out.

Thanks for a commentary. You have some good points. Still, IMO using partial classes by design is wrong in most cases. An auto-generated code should be transparent for user code. Partial clasess create a risk that user code could rely on a version-specific designer implementation (or an idea-specific, which disallows makers of a designer to it's further developent due to backward compatibility sh*t). Fortunately, nothing stops us declare a "model" property in a code-behind and use it as a data context (eg. in WPF).

for me the only reason for partial classes is to separate generated code from hand written code (and even this can be solved via inheritance). In any other case splitting sourcecode over a couple of separate files complicates the development because i have to remember in which partial class the code i'm looking for resides.

If you have a large class with many public methods you should think about the design. Maybe the class has too much responsibilities.

And every source code repository supports merging of changes from different developers so there is no need to split a class just because more than one developer is working on it.

In any other case splitting sourcecode over a couple of separate files complicates the development because i have to remember in which partial class the code i'm looking for resides.

I agree too many splits will definitely create problems. Like you have 10 partial classes it will be weird. When i see old ASP.NET behind code and todays behind code i feel more focussed as i do not need to see that event handlers and UI objects.

Klaus Luedenscheidt wrote:

If you have a large class with many public methods you should think about the design. Maybe the class has too much responsibilities.

NoT necessarily. Even two methods in a single class have make a class bad if the concerns are not specific to the class.

Klaus Luedenscheidt wrote:

nd every source code repository supports merging of changes from different developers so there is no need to split a class just because more than one developer is working on it.

I agree your thought and i have put this point at the last as a browny point. Small projects with two developers having a TFS is a bit of load and this works good.

for me the only reason for partial classes is to separate generated code from hand written code (and even this can be solved via inheritance)

This is a very good point you have made we can implement the same by inheritance or possible assoication/aggregation and composition. But then what if really there is no inheritance relationship possible. I mean it just does not fit like

That is a bit of a sweeping statement. I have very successfully used partial classes when implemented a c# .Net interface to C++ API another product provided - this API changed very slightly over different versions of the other product but by using partial classes I was able to put all the code that was the same for all versions of the API into one file and then add separate files for the definitions that differed by API version - meant much better use of shared code where inheritance would not have worked.

I wouldn't be so arrogant as to assume that just because I didn't find something useful no one else would either.

Thats a bit poor of you to vote 2 for the article just because you dont like the use of partial classes.If the article itself was poor then fine vote 2, but you have voted on your dislike of the concept, not your evaluation of the article.

Bryce

MCAD---To paraphrase Fred Dagg - the views expressed in this post are bloody good ones.--