|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer|
Partial methods enable developers to insert custom logic into code. Typically, the code is part of a designer-generated class. Partial methods are defined in a partial class that is created by a code generator, and they are commonly used to provide notification that something has been changed. They enable the developer to specify custom behavior in response to the change.
The designer of the code generator defines only the method signature and one or more calls to the method. Developers can then provide implementations for the method if they want to customize the behavior of the generated code. When no implementation is provided, calls to the method are removed by the compiler, resulting in no additional performance overhead.
The generated code marks the definition of a partial method by placing the keyword Partial at the start of the signature line.
The definition must meet the following conditions:
The method must be a Sub, not a Function.
The body of the method must be left empty.
The access modifier must be Private.
The implementation consists primarily of filling in the body of the partial method. The implementation is typically in a separate partial class from the definition, and is written by a developer who wants to extend the generated code.
The previous example duplicates the signature in the declaration exactly, but variations are possible. In particular, other modifiers can be added, such as Overloads or Overrides. Only one Overrides modifier is permitted. For more information about method modifiers, see Sub Statement (Visual Basic).
You call a partial method as you would call any other Sub procedure. If the method has been implemented, the arguments are evaluated and the body of the method is executed. However, remember that implementing a partial method is optional. If the method is not implemented, a call to it has no effect, and expressions passed as arguments to the method are not evaluated.
In a file named Product.Designer.vb, define a Product class that has a Quantity property.
Partial Class Product Private _Quantity As Integer Property Quantity() As Integer Get Return _Quantity End Get Set(ByVal value As Integer) _Quantity = value QuantityChanged() End Set End Property ' Provide a signature for the partial method. Partial Private Sub QuantityChanged() End Sub End Class
In a file named Product.vb, provide an implementation for QuantityChanged.
Finally, in the Main method of a project, declare a Product instance and provide an initial value for its Quantity property.
A message box should appear that displays this message:
Quantity was changed to 100