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.

225 Views
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
About the Author

I completed my Computer Science degree at the University of Manitoba in 1976. I did two and a half years of programming in medical research followed by twenty-nine years at Manitoba Hydro (electric utility). Most of that was spent on doing development and maintenance on an AGC/SCADA (real-time programming/process control) system. The last ten years of that was spent doing application and infrastructure support and development. I have programmed in FORTRAN (mostly), APL, PL/1, COBOL, Lisp, SNOBOL, ALGOL, Assembler (several flavours), C, C++, Paradox, VB, vbScript and more recently, Python. I am married with two grown children of whom I am very proud, and a most beautiful wife. I am currently retired (and loving it).

ddanbe 2,720

Nice! Did something similar in C#.