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
Note that the
Extensionattribute can only be applied to a method (a
Functionprocedure) in a Visual Basic Module. If you apply it to a method in a
Structure, the Visual Basic compiler generates error BC36551, "Extension methods can be defined only in modules."
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(para1 As ExtendedType, <other parameters>) ' < Body of the method > End Sub
The following example declares an extension method in module
StringExtensions. A second module,
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(aString As String, punc As String) Console.WriteLine(aString & punc) End Sub End Module
' Import the module that holds the extension method you want to use, ' and call it. Imports ConsoleApplication2.StringExtensions Module Module1 Sub Main() Dim example = "Hello" example.PrintAndPunctuate("?") example.PrintAndPunctuate("!!!!") End Sub End Module
Notice that the method is defined with two parameters and called with only one. The first parameter,
aString, in the method definition is bound to
example, the instance of
String that calls the method. The output of the example is as follows: