Search

Mar 25, 2009

Partial Methods in C# 3.0

In C# 2.0 Partial Class has been added, which was I personally believe very good features to work in multi-developer environment.

One more new feature added in C# 3.0; Partial Method. I already talked about Automatic Properties, and Object-Collection Initialization which also introduced in C# 3.0. Partial Method is a method which must reside [only signature] into Partial Type [Partial Class] and if define somewhere then will get executed. This basically a rule created by one, if other want to implement then go ahead or leave it blank. I can compare it with Interface method; although its major difference between Interface method and Partial method. In Interface method if you does not implement then the type which implement that interface MUST be abstract; but in the case of Partial Method, its not abstract but its Partial.

There are few rules if you want to work with Partial Methods:

  • A method must be declared within Partial Class or Partial Structure
  • A method cannot have access modifiers. [virtual, abstract, new, sealed...]. They are always private
  • A method must return void
  • A method cannot have out parameter
  • A method definition hast to end with ';'
Here is the simple example of Partial Methods

partial class PartialMethods
{
partial void DoSomeWork();
}

If you build with this code, it will work fine although we haven't write body of this function. If you see the Manifest you wont find this method anywhere. The only constructor will part of PartialMethods class.

PartialMethod1

Now let me write body for the method and check manifest again

partial class PartialMethods
{
partial void DoSomeWork();
}

public partial class PartialMethods
{
partial void DoSomeWork()
{
//Do your work here
}
}


PartialMethod2

Now we can see the method, this class is not full class but as partial methods are private, you cant not access from outside, you have to call within that class. Partial method allow developer to create rule which can be implemented later but only once.

1 comment:

Shuaib said...

Well explained imran...