How to: Call an Extension Method (Visual Basic)
Updated: July 20, 2015
For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.
Extension methods enable you to add methods to an existing class. After an extension method is declared and brought into scope, you can call it like an instance method of the type that it extends. For more information about how to write an extension method, see How to: Write an Extension Method.
The following instructions refer to extension method
PrintAndPunctuate, which will display the string instance that invokes it, followed by whatever value is sent in for the second parameter,
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
The method must be in scope when it is called.
Declare a variable that has the data type of the first parameter of the extension method. For
PrintAndPunctuate, you need a String variable:
Dim example = "Ready"
That variable will invoke the extension method, and its value is bound to the first parameter,
aString. The following calling statement will display
Notice that the call to this extension method looks just like a call to any one of the String instance methods that require one parameter:
Declare another string variable and call the method again to see that it works with any string.
Dim example2 = " or not" example2.PrintAndPunctuate("!!!")
The result this time is:
The following code is a complete example of the creation and use of a simple extension method.
Imports System.Runtime.CompilerServices Imports ConsoleApplication1.StringExtensions Module Module1 Sub Main() Dim example = "Hello" example.PrintAndPunctuate(".") example.PrintAndPunctuate("!!!!") Dim example2 = "Goodbye" example2.PrintAndPunctuate("?") End Sub <Extension()> Public Sub PrintAndPunctuate(ByVal aString As String, ByVal punc As String) Console.WriteLine(aString & punc) End Sub End Module ' Output: ' Hello. ' Hello!!!! ' Goodbye?