Partial Methods

We are seeing more and more features added to Visual Studio to support code generation. We first had partial classes, which allowed Visual Studio to hide all its necessary designer code from the developer so he/she didn't have to tip-toe around it. It is also used in other Code Generator to allow the developer to extend code generated classes without being concerned with that code being overwritten if and when the class is generated again.
In Orcas Beta 2 we will see partial methods, which again provides a hook for developers to “inject” code into partial classes without running the risk of that code being overwritten when the class is being generated in the future. Partial Methods look-to-be a less flexible, but lighter-weight alternative to events for use with code generation such as:
partial class Subscriber
{
private string _email;
public string Email
{
get { return _email; }
set
{
OnBeforeUpdateEmail();
_email = value;
OnAfterUpdateEmail();
}
}
partial void OnBeforeUpdateEmail();
partial void OnAfterUpdateEmail();
}
partial class Subscriber
{
partial void OnBeforeUpdateEmail()
{
// Validate...
}
}

As shown above, we have the option of implementing the OnBeforeUpdateEmail and OnAfterUpdateEmail Partial Methods in a separate partial class. If you don't implement a Partial Method, the compiler does not emit the call in IL, which means you don't have the overhead of making a call to a partial method which doesn't exist or has no code.
This is where the light-weight alternative to events comes in, because with events you always have to check if a listener has subscribed to your event.
There are a few notable things here:
1. Partial methods must be declared within partial classes
2. Partial methods are indicated by the partial modifier
3. Partial methods do not always have a body (well look at this more below)
4. Partial methods must return void
5. Partial methods can be static
6. Partial methods can have arguments (including this, ref, and params modifiers)
7. Partial methods must be private

Comments

Ameya said…
Could you please provide a link to official Orcas website which talks about this? This is too new for me and sounds weird.

Thanks,
Ameya

Popular Posts