Extending classes without sub-classing

Reverend Jim 1 Tallied Votes 376 Views Share

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
ddanbe 2,724 Professional Procrastinator Featured Poster

Nice! Did something similar in C#.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.