C# 3.0 : Partial Methods

C# 2.0 and Partial class, in one of the amazing features to work with one class separated in multiple physical files. Not only that, it also helps us to extend designer generated code such as Typed DataSet, Designer generated code etc.

 

With this C# 3.0, we can now have partial method. Partial methods are the code block which reside inside a partial type and gets executed only when it has definition. This gives us the extensibility and if user wants to implement the rule, they can go ahead and define the body but if they do not want it will not. This improves the performance as you are not loading/creating unwanted methods.

 

Here I am going to explain what is that? People already have documented about this feature in so many places, here I am,

 

Let us consider this piece of code,

 

public partial class MyClass

{

    //Public Constructor

    public MyClass(int iInput)

    {

        //Calling Partial Method

        GetMessage(iInput);

    }

    //Public Property

    public string Messgae { get; set; }

    //Partial Method

    partial void GetMessage(int iVal);

}

 

In the partial method declaration I cannot have any body. So, where we need to define the body of our method?

 

Should be in another partial class (I will explain that later). But since there is no body, the method actually will have no existence in IL.

 

clip_image001

Notice no existence for the method GetMessage(int iVal)

 

Calling block,

static void Main(string[] args)

{

    MyClass obj = new MyClass(10);

    Console.WriteLine(obj.Messgae);

}

 

Now if you define the body of the function in a partial class the IL will look different as well as the Console.WriteLine()will print the value.

 

PartialMethod2

 

Notice this IL, this has got the definition for GetMessage in it.

 

How the definition would look like,

 

public partial class MyClass

{

    partial void GetMessage(int iVal)

    {

        this.Messgae =

"The value entered by you is : " + iVal.ToString();

    }

}

 

Some golden rules on Partial Methods, (these are the typical errors you will get from Visual Studio if anything is missing)

 

You must visit wesdyer’s blog for more detailed specification.

 

Ø A partial method must be declared within a partial class or partial struct

Ø A partial method cannot have access modifiers or the virtual, abstract, override, new, sealed, or extern modifiers

Ø Partial methods must have a void return type

Ø A partial method cannot have out parameters

Ø Definition has to end with “;” No {} is allowed in this scope.

 

 

Some good resources,

 

https://community.bartdesmet.net/blogs/bart/archive/2007/07/28/c-3-0-partial-methods-what-why-and-how.aspx

 

Namoskar!!!