18 March 2013

partial methods in .net c# (page 2)

Partial methods can be declared in one partial class and can have implementation in other partial class file.

In the first post talked about what are partial methods and usage of partial methods. In this post let's validate whether partial methods and its invocation will be removed during compilation when the implementation is not found in another partial method.

Consider the below program with partial methods:

namespace Partial_Method_Example
{
 class Program
 {
     static void Main(string[] args)
     {
      Partial_Method_Illustration partial_class_intance = 
           new Partial_Method_Illustration();
      partial_class_intance.InvokePartialMethod();
      Console.ReadLine();
     }
 }

 public partial class Partial_Method_Illustration
 {
   partial void EventHandler(object arguments)
   {
     Console.WriteLine("From partial method");
   }
 }

 public partial class Partial_Method_Illustration
 {
   public void InvokePartialMethod()
   {
     // Do something else

     // Call partial method
     EventHandler(new object());

     // Do something else
     }
    
    partial void EventHandler(object arguments);
 }
}

Partial method validation using ILDASM when implementation provided:

After compiling the above code, open the executable assembly in ILDASM. Partial methods compiled version illustrated using ILDASM

EventHandler() partial method can be seen in compiled version. That is because partial method has the implementation provided.

Now let's look an example of partial methods declaration without implementation provided:

namespace Partial_Method_Example_Without_Implementation_Provided
{
 class Program
 {
  static void Main(string[] args)
   {
    Partial_Method_Illustration partial_class_intance = 
        new Partial_Method_Illustration();

    partial_class_intance.InvokePartialMethod();
    Console.ReadLine();
   }
 }

public partial class Partial_Method_Illustration
{
 public void InvokePartialMethod()
  {
    // Do something else

    // Call partial method
    EventHadler(new object());

    // Do something else
  }
  
  partial void EventHadler(object arguments);
 }
}

Open the assembly in ILDASM

Partial methods removed in compiled version illustrated using ILDASM

Cannot seen EventHandler() partial methods in the compiled version of the assembly. The partial method and its invocation are removed at compilation. This is because implementation not provided for the partial method.

<< First page