Click here to Skip to main content
Click here to Skip to main content
Go to top

Introduction to Partial Methods

, 23 Oct 2008
Rate this:
Please Sign up or sign in to vote.
This article explains partial methods - a new feature in .NET 3.0

Introduction

Partial methods are a new feature in the .NET programming world. The earlier versions of .NET had partial class, partial structures, partial interface. With the introduction of ".NET Framework 3.0", the partial family gets a new member partial method, which allows to separate method definition and implementation. Partial methods are not really complicated. In this article, I will try to explain the basic rules of partial methods and how simple it is to use partial methods.

Partial Methods

The first impression from the name partial method will be a method with multiple implementations but let me make it clear that partial methods have only one implementation or no implementation at all. As a developer, it becomes important to learn how to implement partial methods and know where to expect them if you have to maintain code. To keep it simple, partial keyword before a method is a way to notify the compiler that it is not mandatory for this method to have an implementation.

A partial method is like a usual method in a class except that the user may or may not implement it. A partial method gets executed only when it has an implementation. What is the use of a method that does not have an implementation? Such methods can act as hooks for plugging in code, for instance take a code generation tool that generates a class. It can have partial methods, the user of the class can implement them or just leave them. If the user leaves them, the compiler does not include them in the final code thus improving the overall performance. If the user writes some implementation code for them, then they act as normal methods.

The use of partial methods improves the performance because any call to a partial method without an implantation is removed from the assembly code by the compiler. Partial methods are intended to solve a major problem that is caused by code-generation tools. Similar functionality can be achieved with sub classing, but it creates a performance overhead and moreover partial methods are more clear to understand.

A general thing to note is that a partial method has no more than one implementation, usually the definition of a partial method is in one part of the partial class and implementation in another, but it is legal to have both in the same part of the partial class. Also you can use a partial method in a partial structure but not in partial interface. Microsoft’s intention behind the partial concept was to provide the ability of splitting the definition of a class, a structure, a interface, a method in different source files. This partial source is combined during the time of compilation generating a single output. Some developers view the partial concept as a way of hiding code from some user, but it's not really hiding. I would rather say it is a way to isolate code from a set of developers. If you have a team of developers that can be classified in a set of highly experienced and a set of fresh developers and you want them to distribute the load of creating a very complicated class. By using the partial concept, you can easily isolate the complex task to the experienced developer and pass on the simple development task to the fresh guys.

Rules for Partial Methods

You need to know the rules of partial class to work with partial methods, also the knowledge of partial structure and partial interface can be helpful. A number of articles are present on the internet about them, so I am not going to go in details about partial classes. There are several rules to follow with partial class and there are several rules to follow with partial method as defined by Microsoft. Those rules are listed below:

  • Partial methods are indicated by the partial modifier.
  • Partial methods must be private.
  • Partial methods must return void.
  • Partial methods must only be declared within partial classes.
  • Partial methods do not always have an implementation. 
  • Partial methods can be static and generic.
  • Partial methods can have arguments including ref but not out. 
  • You cannot make a delegate to a partial method.

C# Example of Partial Method

After knowing the rules and basics about partial methods, we should test what they can do so let’s create a simple class with a partial method. Our objective is to check the effects of partial method in the generated code. We will be using the popular de-assembler tool ILdasm to view the generated code in the form of assembly language. I assume that you have basic knowledge of the assembly or the IL, don't worry if you have not used the de-assembler before it is explained in the steps below.

To compile the code in this article, you will need .NET Framework 3.0 or higher with Visual Studio 2008. Even if you don't have Visual Studio 2008, you can use the C# 3.0 command line compiler CSC.EXE to compile the code. I have tested it on a Windows XP computer with 3.5 Framework installed and no Visual Studio. Note that if you have any pre-release or beta versions of the .NET Framework, you might run into compilation errors. You can download the latest .NET 3.5 Framework from the Microsoft web site.

namespace ParMethod
{
    partial class Program
    {
        static void Main()
        {     
            myMethod();
        }
         static partial void myMethod();
    }

    partial class Program
    {
        static partial void myMethod(){}
    }
}

The above code is a very simple C# console application. It has only one namespace ParMethod and a class named as Program. It is a partial class split in two, the first has the Main() function and the definition of partial method named as myMethod and the second has the implementation of myMethod. You should compile the program and generate the executable file. To view the assembly code, go to the Start Menu -> Programs -> Microsoft .NET Framework SDK -> SDK Command Prompt and type ILDASM or ILDASM.EXE. This will pop-up the Disassembler tool. Highlight the tool window, go to the file menu and click on Open, navigate to the output folder of your project where your executable is and select the file.

figure22.JPG

Ildasm.exe will show you a tree structure of the namespace, in our case named as ParMethod, expanding the namespace you will find our class 'ParMethod.Program'. Further expanding the class, all methods in the class are listed. Click on Main:void () and a window will pop-up containing the assembly code of our program. You will find a call to the partial method commented as void ParMethod.Program::myMethod(). This proves that the call to the partial method having an implementation is compiled in the assembly code which is a normal behavior of the compiler.

figure33.JPG

Now to check the effect if no implementation of the partial method is provided. Comment out the function definition from the second partial class. Follow the same procedure for the disassembler and  click on main:void() - it will open up a window. If you compare the IL code with the previous IL, you will find that it has no call to myMethod(). This concludes that the compiler will remove code for a partial method that has no definition, and it also proves that it is perfectly legal to call a method declared as partial that does not have a definition or implementation.  

    partial class Program
    {
       // static partial void myMethod(){}
     }

figure44.JPG

The figure below elucidates that the compiler will take the two partial classes and check if the partial method defined in the first part has an implementation or not. If the compiler finds an implementation, then it will bind the call with the implementation else it will behave as no method calls are declared. In this way, partial methods declaration behave as a hook that will bind to the partial method implementation if it is provided by the developer.

figure11.JPG

C# Example of Partial Method with Parameters

using System;
namespace ParMethod
{
    partial class Program
    {
        static void Main()
        {     
            int value=1;            
            myMethod(value++);   
            Console.WriteLine(" Main : {0}", t1);
        }
         static partial void myMethod(int value);
    }

    partial class Program
    { 
        static partial void myMethod(int value)
        {            
        }
    }

This is a very interesting effect of partial methods. In the above example, anyone should be able to predict that the output will be displayed as ' Main : 2 '. The fact is if we comment out the definition of the partial method in the second part of the partial class, we will have the output as ' Main : 1 '. This proves that the compiler removes any calls to a partial method missing implementation. The statement value++ was never executed and so the variable is not incremented.  

Once should take a note that partial methods can have arguments including ref but not out. Out parameters are like return values which must be assigned by the callee.We know a partial method may or may not have an implantation in the case if it does not have a implementation how will it assign value to the out parameters. A partial method cannot have access modifiers like the virtual, abstract, override, new, sealed, or extern modifiers. The reason is same if the partial method does not have an implantation, how will the external callers know if the method exists or not.

C# Example of Generic Partial Method

A partial method can be generic. To increase the usability of a class, many architects prefer to have a generic class. So let’s modify the above code to make it a generic class and check the output generated by the compiler.

namespace ParMethod
{
    partial class Program
    {
        static void Main()
        {     
            int value=new int ();
            myMethod(value);
        }
         static partial void myMethod<t>(T value);
    }

    partial class Program
    {
        static partial void myMethod<t>(T value){}
    }
}

figure55.JPG

C# Example with Events

Let's create a simple program to generate a effect similar to the partial method. We can use events with subclassing to provide a similar functionality. I have created a Base class that has an event named as Handler and a method named as InvokeEvent(). We can have two scenarios, a user hooks a method with event or he does not. We have class Derived1 that does not hook the method, infact for simplicity there is no code in it and the class Derived2 hooks and implements the method. The method is named as myMethod(). When it is called, it brings up a message box. We create an instance of both the classes and call the InvokeEvent. Only the second instance will show the message box. You can check the assembly code by using the de-assembler.

using System;
using System.Windows.Forms;
namespace ParMethod
{
    class Program
    {  
        static void Main()
        {
            Derived1 P1 = new Derived1();
            P1.InvokeEvent();
            Derived2 P2 = new Derived2();
            P2.InvokeEvent();
        }        
    }

    partial class Base
    {
        protected event EventHandler Handler;

        public void InvokeEvent()
        {
            if (Handler != null)
                Handler.Invoke(this, null);
        }
    }

    partial class Derived1: Base
    { 
    }

    partial class Derived2: Base 
    {
        public Derived2()
        {
            Handler += myMethod;
        }

        protected void myMethod(object sender, EventArgs e)
        {
            MessageBox.Show("myMethod");            
        }
    }
}

Points of Interest

To download .NET 3.5, click here.

To download Visual Studio 2008, click here.

History

  • 13th October, 2008: Article created

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

vikas amin
Software Developer (Senior)
India India
My name is Vikas Amin ,my childhood dream was to be a rocket scientist so many times ended with burned hand meshing with firecracker rockets. Now I mesh with computer's using C#,VC++,C,C++,VB,ASP,Silverlight,WPF,WCF,Assebly language some vbscript and javascript.

Comments and Discussions

 
QuestionWhy partial methods required Pinmembermirdana13-Jul-14 1:09 
AnswerRe: Why partial methods required PinmemberChrisWaldron5-Aug-14 14:00 
GeneralRe: Why partial methods required Pinmembermirdana5-Aug-14 22:36 
Questioncorrection about delegates [modified] PinmemberVov23-Nov-13 10:28 
QuestionManage Code to invoke partial methods Pinmembershadab2910-Dec-12 18:33 
GeneralMy vote of 5 Pinmembershadab2910-Dec-12 4:04 
GeneralMy vote of 5 PinmemberJackssen2-Jun-12 17:25 
Generalvery good article Pinmemberemilioarp28-Jul-09 6:16 
GeneralGreat article... one typo PinmemberMark Kamoski10-Jun-09 4:15 
GeneralI Don't Get It PinmvpJohn Simmons / outlaw programmer28-Oct-08 7:52 
GeneralRe: I Don't Get It PinmemberPaul Conrad29-Oct-08 10:27 
GeneralRe: I Don't Get It PinmemberMember 444846018-Oct-10 19:00 
GeneralRe: I Don't Get It PinmemberPaul Conrad18-Oct-10 21:16 
GeneralRe: I Don't Get It PinmemberMember 444846019-Oct-10 8:28 
JokeRe: I Don't Get It PinmemberPaul Conrad19-Oct-10 8:58 
GeneralRe: I Don't Get It PinmemberMember 444846019-Oct-10 11:49 
GeneralRe: I Don't Get It Pinmemberjibalt16-Jul-14 15:19 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140916.1 | Last Updated 23 Oct 2008
Article Copyright 2008 by vikas amin
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid