Wednesday, November 7, 2012

Partial Methods in C#

All of us know that partial type allows us to split definition of type across multiple files but do you know C# also provides supports for partial methods too. Partial methods are used when your code is auto generated by code generation tool. The tool will write only method definition and leave the implementation of for developer if they want to customize.


Basically partial method contains two parts, method definition and implementation. The definition is mostly written by code generation tool and implementation is written manually by developer. If no implementation provided then compiler removes method signature at compile time.

Below things should be kept in mind while creating partial method

  • Partial methods must be declared inside a partial class.
  • Partial methods can have ‘ref’ parameters but not ‘out’ parameters.
  • Partial methods are implicitly private therefore they can’t be Virtual.
  • Partial methods must be void.


Below example demonstrate use of partial methods.

public partial class MyClass
{
    partial void MyMethod();
}
public partial class MyClass
{
    public MyClass()
    {
        MyMethod();
    }
    partial void MyMethod()
    {
        Console.WriteLine("Hello");
    }
}

Thanks for reading!!

No comments:

Post a Comment

^ Scroll to Top