In visual basic, extension methods are useful to extend the behavior of existing types by adding new methods without modifying, deriving or recompiling the original types such as class, structure or interface.
In visual basic, we can implement our own extension methods for any .NET type such as custom class, .NET framework class or third party classes.
To create an extension method, we need to import the System.Runtime.CompilerServices namespace in module and implement an extension method by adding <Extension()> attribute with the required parameters. The first parameter of the method will specify the type on which the extension method will operate on.
Following is the example of implementing an extension method for the System.String class.
Imports System.Runtime.CompilerServices
Imports System.Text.RegularExpressions
Module StringExtension
' Extension Method for String type
<Extension()>
Function IsValidEmail(ByVal str As String) As Boolean
Dim result = Regex.IsMatch(str, "^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$")
Return result
End Function
End Module
If you observe the above example, we are extending the behavior of string type by creating the IsValidEmail extension method.
Now, we need to include StringExtension namespace in our application wherever we want to access the IsValidEmail extension method like as shown below.
Import ConsoleApp1.StringExtension
After adding the namespace, we can access the extension method as an instance method of extended type like as shown below.
Dim mail As String = "support@tutlane.com"
Dim result = mail.IsValidEmail()
Following is the example of accessing IsValidEmail extension method by including StringExtension namespace.
Imports ConsoleApp1.StringExtension
Module Module1
Sub Main(ByVal args As String())
Dim mail As String = "support@tutlane.com"
Dim result = mail.IsValidEmail()
Console.Write("Is valid: {0} ", result)
Console.ReadLine()
End Sub
End Module
If you observe the above example, we included StringExtension namespace in our program and we are able to access the IsValidEmail extension method as an instance method of string extension type.
When we execute the above program, we will get the result like as shown below.
In the above example, we extended the behavior of .NET framework System.String class type. The same way we can extend the behavior of custom classes also based on our requirements.
While creating an extension method for a specific type, we need to make sure that the same signature of method will not exist for the specified type otherwise the extension method will never be called.
Following are the important points which we need to remember about extension methods in visual basic.