Saturday, November 28, 2009

Partial Methods

Partial classes was a great feature added in .NET framework 2.0.
Mainly,this feature allows us to add a custom code, when working with auto-generated code after adding a new form, DataSet, web-service etc..

Microsoft has extended this feature and introduced partial methods in C# 3.0.
With partial method we can define a method signature in one part of a partial class and its implementation in another part of the same type.
It enables class creators to provide method hooks that developers may decide to implement,very similar to events provider-subscriber relationship.

Example:

public partial class Department
{
//partial method signature
partial void OnCreated();

public Department()
{
OnCreated();
}
}

//could be placed in separate file.
public partial class Department
{
partial void OnCreated()
{
Console.WriteLine("OnCreated");
}
}


Partial method should comply with following rules:

1. Signatures in both parts of the partial type must match.

2. The method must return void.

3. No access modifiers or attributes are allowed. Partial methods are implicitly private.

You can find additional info about partial methods here:

http://msdn.microsoft.com/en-us/library/6b0scde8.aspx
http://geekswithblogs.net/sdorman/archive/2007/12/24/c-3.0---partial-methods.aspx

No comments:

Post a Comment