EXTENSION METHODS
Extension methods let you add new subroutines or functions to an existing class without rewriting it or deriving a new class from it even if you don’t have access to the class’s source code.
To make an extension method, create a new method in a code module and place the System.Runtime.CompilerServices.Extension attribute before the method’s declaration. (If you like, you can add the statement “Imports System.Runtime.CompilerServices” at the top of the file so you only need to use the name Extension for the attribute.)
Then make a normal subroutine or function that takes one or more parameters. The first parameter determines the class that the method extends. The method can use that parameter to learn about the item for which the method was called. The other parameters are passed into the method so it can use them to do its work.
For example, the following code adds a MatchesRegexp subroutine to the String class:
' Return True if a String matches a regular expression.
<Extension()>
Public Function MatchesRegexp(the_string As String,
regular_expression As String) As Boolean
Dim reg_exp As New Regex(regular_expression)
Return reg_exp.IsMatch(the_string)
End Function
The Extension attribute tells Visual Basic that this is an extension method. The method’s first parameter is a String so this method extends the String class. The second parameter is a regular expression. The method returns True if the String matches the regular expression.
The program can use the extension ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access