In my previous article about extension methods I discussed how to implement them only in C#, as I had not yet looked at them in Visual Basic. Today I decided to finally take a look and was expecting something similar to how it is implemented in C# but what I found was different enough to warrant talking about it again, I believe. Anyway, let's get to it.
The first big difference I notice is that, in Visual Basic, you must define extension methods in a module. I'm not sure why this is the case, but it is. The second difference is that you must mark your extension methods with the extension attribute <Extension()> from the System.Runtime.CompilerServices namespace. So once you have your module and you've imported the System.Runtime.CompilerServices namespace you're ready to create an extension method. Here's the Visual Basic version of a sample extension from Scott Guthrie's blog:
Imports System.Text.RegularExpressions
Imports System.Runtime.CompilerServices
Module MyExtensions
<Extension()> _
Public Function IsValidEmailAddress(ByVal s As String) As Boolean
Dim regex As New Regex("^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$")
Return regex.IsMatch(s)
End Function
End Module
In this function I've extended the string type. Using this approach I can now call IsValidEmailAddress on the string variable itself. I think this example is a perfect demonstration of the ease in which extension methods can be created and used. A word of caution is in order, though, as it is quite easy to cause some namespace and method name collisions or make your code a little more difficult to debug. As an example, some of the examples I used when creating the C# post on this topic don't seem to work very well using VB, so use with care.
If you want more information please read the C# post or visit the MSDN article regarding Extension Methods in Visual Basic.