Partial Methods

Partial methods is a new feature available in C# 3.0. Partial methods allow hooks into automatically generated code. Partial method basically consist of definition and implementation. Usually you define and declare partial method in one partial class and implement in another. Partial methods are heavily used by code generated from linq to SQL.

image

Above is the code generated by linq to SQL designer. Notice in the setter of ContactName, there are extensibility points provided like OnContactNamingChanging and OnContactNameChanged. These are basically partial methods which allows you to tap into process before and after the value of contact Name is changed. The most common use of partial methods would be for validation such as you want to ensure that contact name should not contain Mr or Mrs. Let's go ahead and work on a simple example that illustrates that behavior.

image

In the above code, I have created a class called Person with Name property. In order to provide hooks into the code I have declared a partial Method called OnNameChanging. Partial method starts with partial keyword and can only be defined inside a partial class. Since partial method may not have an implementation defined, it must return a void type and cannot have out parameters. You cannot declare partial methods as virtual or or define accessor methods on them such as private public or protected. In order to specify an implementation for partial method, I have created another partial class called person and declared the body of the partial method. Notice that the implementation method must also have the partial keyword specified. In the implementation I am forcing a rule that name passed in cannot have Mr or Mrs in it. Partial method can be static or instance level. Partial methods can be used with generics and be exposed as extension methods as well.

One of the reasons partial method is efficient is, if there is no implementation specified for the partial method than compiler skips method invocation. The final class obtained after merging partial classes would not contain the line that makes a call to the partial method if there is no implementation defined for the partial method.You can confirm this behavior by not specifying an implementation like not defining the implementation of OnNameChanging. When you look at the IL generated by the compiler, you would not see any reference of OnNameChanging being called anywhere inside the setter of Name property. I have created an example below which confirms that partial methods with no body does not get invoked by the compiler.

image

image

Above code returns a value of 0 which indicates that number++ operation does not even execute. The reason is because there is no implementation defined for the partial method. If this is not the behavior you expect, than it would be better to increment the value of number before calling Increase method.

No Comments