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 method just as if it were part of the String class. The following code uses the MatchesRegexp method to decide whether the phone_number variable contains a value that looks like a valid United States phone number:

If Not phone_number.MatchesRegexp("^[2-9]d{2}-d{4}$") Then
    MessageBox.Show("Not a valid phone number")
End If

If used haphazardly, extension methods can blur the purpose of a class. They can make the class do things for which it was never intended. They add behaviors that the class’s original authors did not have in mind. The result may be a class that does too many poorly defined or unrelated things, and that is confusing and hard to use properly. They weaken the class’s encapsulation by adding new features that are not hidden within the control’s code.

If you have access to the class’s source code, make changes to the class within that code. Then if there is a problem, at least all of the code is together within the class. If you really need to add new methods to a class that is outside of your control, such as adding new methods to String and other classes defined by Visual Basic and the .NET Framework, you can use extension methods.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.97.187