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:

  1. sub-class the string class and add the functionality
  2. write a separate function that takes a string and a regular expression as parameters
  3. 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.

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

Computer languages in which I have developed applications

Assembler (DEC, Data General, 8080, GE, SEL, IBM 360)
WATFOR (Waterloo FORTRAN)
FORTRAN (SEL)
APL (IBM 360, IBM VSAPL)
PL/1
C/C++
Borland Paradox
VB.net
vbScript

The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.