Extension methods are new in Visual Basic 2008. This short blog series explores how extension methods can be used to add Subs and Functions to the .NET String type.
Click here for an index of this blog series.
Here's this post's sample code:
Module StringExtensions
' Declare a String extension method named Browse
' that uses the string assigned to a variable of type String as a url
' to open a browser and navigate to the url.
<Extension()> _
Public Sub Browse(ByVal url As String)
System.Diagnostics.Process.Start(url)
End Sub
' Declare a String extension method named SplitCommaDelimited
' that splits a comma delimited string assigned to a variable of type String,
' splits it into a String array, then calls the String array's ToList method to
' return a List(Of String)
<Extension()> _
Public Function SplitCommaDelimited(ByVal commaDelimitedString As String) As List(Of String)
Dim strings = commaDelimitedString.Split(",")
Return strings.ToList
End Function
' Delcare a String extension method name ValidateEmailAddress
' that uses a regular expression to validate a string is an email address.
<Extension()> _
Public Function ValidateEmailAddress(ByVal source As String) As Boolean
Dim EmailRegex As Regex = New Regex("(?<user>[^@]+)@(?<host>.+)")
Dim IsValid As Match = EmailRegex.Match(source)
Return If(IsValid.Success, True, False)
End Function
End Module
A new extension method, ValidateEmailAddress, has been added to the StringExtensions module created in a previous post. The comments in the code explain what this new extension method does.
Here is an example that tests the new method:
Dim emailAddress = "mikemc@getdotnetcode.com"
' The following line will display True if the string contains and email address;
' False if it does not.
MessageBox.Show(emailAddress.ValidateEmailAddress)