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.
Related
I know the title might not be totally clear, but I didn't want to make it too long.
One thing boggles me when thinking about restrictions placed on partial methods. It seems to me that the rules are inconsistent. As you probably know:
Partial methods must always have a return type of void, and they
cannot have any parameters marked with the out modifier. These
restrictions are in place because at run time, the method may not
exist and so you can’t initialize a variable to what the method might
return because the method might not exist. Similarly, you can’t have
an out parameter because the method would have to initialize it and
the method might not exist. [1]
It sounds sensible to me. But at the same time:
If there is no implementing partial method declaration, then you
cannot have any code that attempts to create a delegate that refers
to the partial method. Again, the reason is that the method doesn’t
exist at run time. [1]
At first, all these rules seem to follow the same compiler logic. There is a difference, though. As stated in the second quotation, compiler issues an error only when there is no method implementation of the partial method. Why can't it also check for the implementation at compile-time in other scenarios? This would allow much more flexibility when using partial methods and the logic behind all rules would be identical.
I am afraid that the only answer I can get is "Because that's how it was implemented", but maybe there is something more to it?
[1] CLR via C#, Fourth Edition
The whole point of partial methods is to facilitate extensibility in generated code scenarios without runtime performance impact. The code generator emits a partial method signature, and then emits code that calls this partial method.
Now, at compile time, if the method isn't implemented, these call sites get entirely removed, and the remaining code has to be valid. The quotes are confusing in this regard, because they're talking about "runtime existence" of the method. That's nonsense: everything is resolved at compile time.
This is the reason for the difference: the rules you quoted first impose restrictions on the method signature, whereas the delegate rule imposes a restriction on method usage.
The rules about the signature make sure you can call the method in a manner the code will remain valid if the method call is removed. And the intended use case for partial methods is for them to be absent 99% of the time. If you require them to be implemented then that's not the feature you should be using in the first place. Use an abstract method or something alike.
Building a delegate to a method is like taking the pointer to the method, and you can't do that if the method doesn't exist (well, I suppose you could argue the compiler could just replace the delegate with null at this point, but you can't write, say, new Action(null)), yet there is no reason to disallow it if the method does exist, for the implementer's convenience. But the code generator shouldn't emit code that creates delegates to the method.
Keep in mind that the reason for partial methods is so they can be used in designer-generated code, i.e. the designer can generate calls to the methods and leave their (optional) implementation to a human developer (who will later compile the code). If, as you suggest, the calls gave compile-time errors when the method is not implemented, then there are cases where the generated code would not compile until the developer either changed the generated code (usually a bad idea) or until he implemented all the methods.
C# already has interfaces and abstract methods to force method implementation, partial methods try to do something else.
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".
I have to write large amount of code which is going to be used in three asp.net pages.
I want to know the key points so that I can decide whether I should create Static Helper class , or create base class for common codes.
I am agree that creating single helper class vs creating multiple helper classes must be a careful job depending on various things like performance etc.., but the question still remain same , you can think me as a smart coder that can create perfect number of helper classes.
I think I am going to use these code only from these three asp.net pages.
Thanks for all your answers friends, but I need more inputs, can you please send more specific points.
Thanks.
If it is code that is being shared by all three ASP.NET pages and not by other code, a baseclass is a good idea.
The code is not exposed to the 'outside world' (by making the methods protected) and you define a context in which the methods should be used. They can only be called from an ASPX page that defines trough inheritance that it is-a certain base type where the methods make sense. A Helper method could be called from everywhere in your code by just passing the right parameters, even if this is conceptual invalid.
If it's code that's going to be called from different places (for example a ValidateEmail function) then a static helper class could help.
But if you opt for the helper class, you still have to decide how many helper classes you are going to create. Dumping all your helper functions in one class is probably not a good idea from maintenance perspective.
Create a base page and inherit from that and then put your helper method and properties on the base page.
I'm updating my code generator and have a choice between implementing a method stub as a Virtual Method in a base class or a partial method in the generated code. Is there any performance difference between the two?
If you implement the partial method, then I would expect there to be no noticeable difference. C# always uses callvirt to invoke instance methods, even if they aren't virtual, so there won't be much change.
If you don't implement the partial method, then the call itself is removed - so there is never a stack to prepare etc. This will be infintessimally quicker, which is why it is fine for generated code to include a ludicrous number of partial method stubs: if you don't use them, they don't exist.
The bigger reason to use partial methods is simply so you don't have to subclass the object. You can't declare "abstract"/"virtual" and "override" parts of a virtual method in the same class (even if partial). Partial methods solves this problem, and the problem of advertising extensibility points (without having to use reflection).
Very good for code-generation tools ;-p
There may be a minor difference, but it should be negligible unless the method is called repeatedly in a loop.
Partial methods are just syntactic sugar that allow the splitting of a class across multiple files.
When compiled, they are exactly the same as if all of the methods had been in the one file. In other words, the only 'slowdown' you are likely to see with a partial method is the slightly longer compile time :)
EDIT: And as the answer below says, they're not even in there if they can't be found during the compile.
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.