How to: Create a Partial Method (Visual Basic)

Partial methods give developers a way to insert custom logic into designer-generated code, often for the purpose of data validation. There are two parts to creating a partial method: defining the method signature and writing the implementation. Typically, the definition is written by the designer of a code generator, and the implementation is written by a developer who uses the generated code. For more information, see Partial Methods (Visual Basic).

To define the method signature

In a partial class, begin the signature with the keyword Partial.

Use Private as the access modifier.

Add the keyword Sub. The method must be a Sub procedure.

Write the name of the method.

Provide the parameter list for the method.

Finish the method with End Sub.

To implement the method

Use Private as the access modifier.

Add any other modifiers that you want to include.

Write the name of the method, which must match the name in the signature definition.

Add the parameter list. Parameter names must match the names in the signature. Parameter data types can be omitted.

The definition and implementation of a partial method are generally in separate files, which are created by using a partial class. Typically, the purpose of a partial method is to provide notification that something in the project has been changed.

In the following example, a partial method named OnNameChanged is developed and called. The method signature is defined in partial class Customer in file Customer.Designer.vb. The implementation is in partial class Customer in file Customer.vb, and an instance of Customer is created in a project that uses the class.

' In a separate file, a developer who wants to use the partial class' and partial method fills in an implementation for OnNameChanged.PartialClass Customer
' Implementation of the partial method.PrivateSub OnNameChanged()
MsgBox("Name was changed to " & Me.Name)
EndSubEndClass