1 Previous Next 

VS 2008: Extension Methods


Visual Basic 2008 adds a new features called extension methods.   These allow you to add a method, or function to a type.  For this example we will add an IsGuid function to strings.  All extension methods must be placed in a module.  The function or method must be marked as an extension and the first argument is the type the method extends.

Imports System.Runtime.CompilerServices
Imports System.Text.RegularExpressions

Module Module1

    Sub Main()
        Dim g As String = "82ee4145-632c-42a1-83b9-57ec163eaa17"
        Dim g1 As String = "82ee4145-632c-42a1-83b9-57ec163ea17"

        Console.WriteLine(g & IIf(g.IsGuid, " is ", " is not ") & "a valid guid")
        Console.WriteLine(g1 & IIf(g1.IsGuid, " is ", " is not ") & "a valid guid")
    End Sub

End Module

Public Module MyExtensions

    <Extension()> _
    Public Function IsGuid(ByVal s As String) As Boolean
        Dim regGuid As New Regex("^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$", RegexOptions.Compiled)
        Return regGuid.IsMatch(s)
    End Function
End Module




1 Previous Next