Monday, August 27, 2012

.NET : Partial Methods

A partial class or struct may contain a partial method. One part of the class contains the signature of the method. An optional implementation may be defined in the same part or another part. If the implementation is not supplied, then the method and all calls to the method are removed at compile time.
Partial methods enable the implementer of one part of a class to define a method, similar to an event. The implementer of the other part of the class can decide whether to implement the method or not. If the method is not implemented, then the compiler removes the method signature and all calls to the method. The calls to the method, including any results that would occur from evaluation of arguments in the calls, have no effect at run time. Therefore, any code in the partial class can freely use a partial method, even if the implementation is not supplied. No compile-time or run-time errors will result if the method is called but not implemented.
A partial method declaration consists of two parts: the definition, and the implementation. These may be in separate parts of a partial class, or in the same part. If there is no implementation declaration, then the compiler optimizes away both the defining declaration and all calls to the method.
Example:
// Definition in file1.cs
partial void onNameChanged();

// Implementation in file2.cs
partial void onNameChanged()
{
  // method body
}
The Rules:
  • Partial method declarations must begin with the contextual keyword partial and the method must return void.
  • Partial methods can have ref but not out parameters.
  • Partial methods are implicitly private, and therefore they cannot be virtual.
  • Partial methods cannot be extern, because the presence of the body determines whether they are defining or implementing.
  • Partial methods can have static and unsafe modifiers.
  • Partial methods can be generic. Constraints are put on the defining partial method declaration, and may optionally be repeated on the implementing one. Parameter and type parameter names do not have to be the same in the implementing declaration as in the defining one.
  • You can make a delegate to a partial method that has been defined and implemented, but not to a partial method that has only been defined.
Source : http://msdn.microsoft.com/en-us/library/wa80x488.aspx

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.