How to: Write an Extension Method (Visual Basic)
Extension methods enable you to add methods to an existing class. The extension method can be called as if it were an instance of that class.
To define an extension method
Open a new or existing Visual Basic application in Visual Studio.
At the top of the file in which you want to define an extension method, include the following import statement:
Within a module in your new or existing application, begin the method definition with the extension attribute:
Declare your method in the ordinary way, except that the type of the first parameter must be the data type you want to extend.
<Extension()> Public Sub subName (ByVal para1 As ExtendedType, <other parameters>) ' < Body of the method > End Sub
The following example declares an extension method in module StringExtensions. A second module, Module1, imports StringExtensions and calls the method. The extension method must be in scope when it is called. Extension method PrintAndPunctuate extends the String class with a method that displays the string instance followed by a string of punctuation symbols sent in as a parameter.
' Declarations will typically be in a separate module. Imports System.Runtime.CompilerServices Module StringExtensions <Extension()> Public Sub PrintAndPunctuate(ByVal aString As String, ByVal punc As String) Console.WriteLine(aString & punc) End Sub End Module