Sometimes you want to add a little functionality to an existing class but you don't want to go to the trouble of sub-classing. A technique that you can use is known as Extending. For example, I frequently use regular expressions when working with strings. Wouldn't it be nice if strings supported regular expressions directly, but because they don't I have three choices:
- sub-class the string class and add the functionality
- write a separate function that takes a string and a regular expression as parameters
- Extend the string class
Extending can only be done within a module so to extend the string class create a module and call it StringPlus. Replace the module code with
Imports System.Runtime.CompilerServices
Imports System.Text.RegularExpressions
Module StringPlus
<Extension()> Public Function MatchesRegexp(str As String, strexp As String) As Boolean
Dim rexp As New Regex(strexp)
Return rexp.IsMatch(str)
End Function
End Module
Note that vb knows that you are extending String because the first parameter of your sub is of type String. When you invoke this method, the string will not be included as a parameter (see example below).
Now in the rest of your project you can use MatchesRegExp just like any other string method. For example
Dim pn As String = "633-0828"
If pn.MatchesRegexp("^[2-9]\d{2}-\d{4}$") Then
MsgBox("is phone number")
Else
MsgBox("is not phone number")
End If
While coding, your extension methods will appear in the intellisense pop-up lists.