How are partial methods used in C# 3.0? - c#

I have read about partial methods in the latest C# language specification, so I understand the principles, but I'm wondering how people are actually using them. Is there a particular design pattern that benefits from partial methods?

Partial methods have been introduced for similar reasons to why partial classes were in .Net 2.
A partial class is one that can be split across multiple files - the compiler builds them all into one file as it runs.
The advantage for this is that Visual Studio can provide a graphical designer for part of the class while coders work on the other.
The most common example is the Form designer. Developers don't want to be positioning buttons, input boxes, etc by hand most of the time.
In .Net 1 it was auto-generated code in a #region block
In .Net 2 these became separate designer classes - the form is still one class, it's just split into one file edited by the developers and one by the form designer
This makes maintaining both much easier. Merges are simpler and there's less risk of the VS form designer accidentally undoing coders' manual changes.
In .Net 3.5 Linq has been introduced. Linq has a DBML designer for building your data structures, and that generates auto-code.
The extra bit here is that code needed to provide methods that developers might want to fill in.
As developers will extend these classes (with extra partial files) they couldn't use abstract methods here.
The other issue is that most of the time these methods wont be called, and calling empty methods is a waste of time.
Empty methods are not optimised out.
So Linq generates empty partial methods. If you don't create your own partial to complete them the C# compiler will just optimise them out.
So that it can do this partial methods always return void.
If you create a new Linq DBML file it will auto-generate a partial class, something like
[System.Data.Linq.Mapping.DatabaseAttribute(Name="MyDB")]
public partial class MyDataContext : System.Data.Linq.DataContext
{
...
partial void OnCreated();
partial void InsertMyTable(MyTable instance);
partial void UpdateMyTable(MyTable instance);
partial void DeleteMyTable(MyTable instance);
...
Then in your own partial file you can extend this:
public partial class MyDataContext
{
partial void OnCreated() {
//do something on data context creation
}
}
If you don't extend these methods they get optimised right out.
Partial methods can't be public - as then they'd have to be there for other classes to call. If you write your own code generators I can see them being useful, but otherwise they're only really useful for the VS designer.
The example I mentioned before is one possibility:
//this code will get optimised out if no body is implemented
partial void DoSomethingIfCompFlag();
#if COMPILER_FLAG
//this code won't exist if the flag is off
partial void DoSomethingIfCompFlag() {
//your code
}
#endif
Another potential use is if you had a large and complex class spilt across multiple files you might want partial references in the calling file. However I think in that case you should consider simplifying the class first.

Partial methods are very similar in concept to the GoF Template Method behavioural pattern (Design Patterns, p325).
They allow the behaviour of an algorithm or operation to be defined in one place and implemented or changed elsewhere enabling extensibility and customisation. I've started to use partial methods in C# 3.0 instead of template methods because the I think the code is cleaner.
One nice feature is that unimplemented partial methods incur no runtime overhead as they're compiled away.

Code generation is one of main reasons they exist and one of the main reasons to use them.
EDIT: Even though that link is to information specific to Visual Basic, the same basic principles are relevant to C#.

I see them as lightweight events. You can have a reusable code file (usually autogenerated but not necessarily) and for each implementation, just handle the events you care about in your partial class. In fact, this is how it's used in LINQ to SQL (and why the language feature was invented).

Here is the best resource for partial classes in C#.NET 3.0: http://msdn.microsoft.com/en-us/library/wa80x488(VS.85).aspx
I try to avoid using partial classes (with the exception of partials created by Visual Studio for designer files; those are great). To me, it's more important to have all of the code for a class in one place. If your class is well designed and represents one thing (single responsibility principle), then all of the code for that one thing should be in one place.

Related

What is the advantage of partial classes over inheritance?

C# has the concept of partial classes. One instance I've seen this used is in WSDLs. Visual Studio could contact a server to find a service, and automatically generate a partial class based on it. Visual Studios would then provide you with a blank partial class to match it so that you can add your own code.
I feel this approach is rather confusing. Is there any advantage to partial classes over inheritance?
Partial classes are there to address a particular issue - solving a problem of separating generated and hand-programmed code. Without partial classes programmers would need to either refrain from modifying generated classes, or rely on a design pattern to achieve the separation.
One very important point is that generated portions of partial classes have implementation. This sets them apart from interfaces, which do not contain implementation.
In a sense, this makes them similar to an abstract class, without making them abstract. You are allowed to extend and alter functionality without subclassing it.
Partial class:
You can define a class in more than one file in a same project. You might end up create a file that contains method, another file contains properties, and so on. At compile time, it will be the same as you create one large file that contains everything.
Read more about partial class and method
Inheritance:
You can extend functionality of existing class both within the same project or on another project. With inheritance, you can extend function, feature, etc. of existing class on a new class.
Agreed partial classes are much more about splitting a class definition among multiple source files than inheritance.
It always seemed to me that the main reason for them was so that frameworks could generate boiler-plate code for you and you could also add methods without your code being overridden by the stuff visual studio created for data access or web service generation.
It always seemed wrong-headed and lazy of Microsoft to me.
this is an invitation to the developer to implement method if desired in a second declaration for partial class
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
}

Can't abstract replace partial?

The biggest argument I've seen so far for partial classes is in the case of auto-generated code.
From a Java perspective, I don't see why this can't simply be done using abstract classes, can't the auto-generated code simply be an abstract class with protected abstract methods that it expects the user to override?
Aside from the auto-generated code cases, every other case I saw was either extremely rare (and the coders were just using partial as a hack), or it can also be solved using abstract or some other concept that already exists.
Inheritance is observable on the compiled assembly while partial is not. This makes inheritance unsuitable for libraries where you need to control the surface area tightly. The .NET BCL could never use this for example.
It is also a hack because inheritance is not meant to stitch together classes. It is primarily meant as a means to create substitutability and abstraction.
partial is meant for exactly this use case. The parts of a partial class can refer to each other which is not possible with inheritance.
Partial methods allow you to create methods that might exist in the compiled result, or not. LINQ to SQL uses them to give you callback hooks into various parts of the DataContext and entity classes. If you don't use them there is no performance cost at all because partial methods that are declared but never defined are just deleted.
For me, partial classes is a way to devide classes into more logical parts. Sometimes cause they are partly auto generated, sometimes because they are really complex.
Abstract is for inheritage, and why use that when nothing is really "shared".

What are the pros and cons of making a FAT class a partial one & splitting it into partial classes?

Recently I was considering a class that seems to become fat because of too many methods in it.
A legacy code...
That has many business logic-wise methods doing all types of CRUD on various 'Etntities'.
I was thinking
make this class partial
and then grouping all methods by their target entities they work on
and splitting them into separate physical files that will be part of the partial class
Question:
Can you list pros and cons of such a refactoring, that is making a fat concrete class a partial class and splitting it into slimmer partial classes?
One pro I can think of is the reduction of conflicts/merges in your source control. You'll reduce the number of parallel check-outs and the merging headaches that invariably come when the devs check-in their work. A big pro, I think, if you have a number of devs working on the same class quite often.
I think that you are talking only about simplicity to handle the class. Performance or behaving pros and cons shouldn't be because when compiled it should generate the same result:
It is possible to split the definition of a class or a struct, or an interface over two or more source files. Each source file contains a section of the class definition, and all parts are combined when the application is compiled.
Now answering pros and cons I can think in (only about simplicity):
Pro: less conflicts / merges if working in a team.
Pro: easier to search code in the class.
Con: You need to know which files handles each code or it can get a little annoying.
I would go for the refactor. Specially considering all facilities given by the IDE where you just have to click F12 (or any other key) to go to a method, instead of opening the file.
Splitting a large class into partial classes perhaps makes life easier in the short term, but it's not really an appropriate solution to the code bloat that your class is experiencing.
From my experience, the only benefit that splitting an existing large class up gives you is that it's easier to avoid having to constantly merge code when working with other developers on said class. However, you still have the core problem of unrelated functionality being packaged into one class.
It's better to treat the breaking down to partial classes as the the very first step in a full refactoring. If you're able to easily extract related methods and members into their own partial classes (without breaking things) then you can use this as the basis for creating entirely standalone classes and rethinking the relationship between them.
Edit: I should clarify that this advice is given under the assumption that your legacy code has unrelated functionality in one class as a result of years of "just add one more method here". There are genuine reasons for having functionality spread across partial classes, for example, I've worked on code before that has a very large interface in one file, but then has all the methods grouped into partial classes based on areas of product functionality - which I think is fine.
I would say Partial class would help to maintain the code and will be more helpful when we have legacy code to avoid more changes on the reference side. Later will help to refactor easily
If you're concerned about how to refactor a class, I suggest reading into SOLID design principles.
I think you should focus on Single responsibility principle (the S in SOLID), which states an object should only have one responsibility.
I think my answer is not directly answering your question whether using partial classes would be beneficial to you, but I believe if you focus on the SOLID design principles that should at least give you some ideas on how to organize your code.
I see partial classes only as a way of extended a class that's code was generated (and can be re-generated at any time) that you would like to extend without your custom code being overwritten. You see this with the Form generated code and Entity Framework DbContext generated code for example.
Refactoring a large legacy class should probably be done by grouping and separating out single responsibilities into separate classes.

Refactoring to Partial Classes - Guidance

I am dealing with a huge codebehind of a an ASP.NET user control. I am taking the approach of refactoring the huge class into a number of partial clasees separted by UI intent.
Is there guidance on:
Number of partial classes I am must constrain myself to.
Naming or names to be given toof the partial class files.
There's no limit to the number of Partial Class files you can use. They all compile into a single class at compile time. The more partial class files, though, the more confusing things could be when trying to find different functionality in the class.
I would name the files starting with the class name and then follow up with which concern the file was addressing. That way you're a little more clear about what is in each file.
You should also be careful about your class. If a single class is addressing several different UI Concerns to the point that you feel it should be separated into separate files it sounds like your class should be broken up into several smaller, more concise classes (rather than a single monolithic class defined across several files).
I'm not familiar with a partial classes limitation.
About file naming, again - no limitation. It could be anything.
My personal preference would be [MainClassName].[aspect].cs,
for example: MyHugeControl.Reports.cs, MyHugeControl.Data.cs, etc.

please illustrate a problem that partial methods solve

I'm still not really getting the upside of partial methods. Can anyone illustrate a problem that partial methods are ideally suited to solve?
From Partial Class and Methods (C# Programming Guide) on the MSDN:
A partial class or struct may contain a partial method. One part of the class contains the signature of the method. An optional implementation may be defined in the same part or another part. If the implementation is not supplied, then the method and all calls to the method are removed at compile time.
Partial methods enable the implementer of one part of a class to define a method, similar to an event. The implementer of the other part of the class can decide whether to implement the method or not. If the method is not implemented, then the compiler removes the method signature and all calls to the method. The calls to the method, including any results that would occur from evaluation of arguments in the calls, have no effect at run time. Therefore, any code in the partial class can freely use a partial method, even if the implementation is not supplied. No compile-time or run-time errors will result if the method is called but not implemented.
Partial methods are especially useful as a way to customize generated code. They allow for a method name and signature to be reserved, so that generated code can call the method but the developer can decide whether to implement the method. Much like partial classes, partial methods enable code created by a code generator and code created by a human developer to work together without run-time costs.
In my opinion, I would recommend to avoid using these unless you have a particular, specific need for them.
Essentially, the most useful purpose of partial methods is for a code generation system to provide an API for extending the capability of its properties and methods without using inheritance.
Take a look at any Linq to SQL data model for a quick example.
The generated code includes partial methods which, if implemented in your own partial class, grant the ability to execute validation logic, event notifications, etc. within existing properties.
What makes partial methods appealing is that, if you do not implement them in your own partial class, they are not emitted into the compiled code at all, which provides a modest efficiency boost.
Here's a decent blog entry that demonstrates the use of partial methods to inject validation logic:
http://www.davidhayden.com/blog/dave/archive/2007/07/24/LINQToSQLValidationEnterpriseLibraryValidationApplicationBlock.aspx
Generated code. Plain and simple this was the number one reason they were implemented. Look at something like WPF. The UI is done declaratively in XAML and the "code-behind" is in C#. Both parts are the same class split by using the partial class concept
As I understand it, one of the main benefits is the ability to have a code-generated "stub" that you can choose whether to implement. So your code-gen creates a partial method and calls some Validate method. In order to "plug in" your validation, you just implement the partial method. The "partial" keyword allows for a relatively clean development process.

Categories