Extension Methods in VS 2008

by Rob Teegarden 13. April 2008 18:28

Extension Methods in VS 2008
If you ever wish you could add a method to an existing class without having to inherit, then you can rest easily knowing that this new feature in VS 2008 could save you some headaches. 

Let’s say for example you have the need to strip HTML tags from strings all throughout your code.  You could write a shared function and call it like so:

    Dim comments As String
    comments = WebUtils.StripHtml(Me.txtComments.Text)

Where the shared function to strip the HTML looks like:

    Public Shared Function StripHtml(ByVal html As String) As String
        If html Is Nothing OrElse html = String.Empty Then
            Return String.Empty
        Else
            Return Regex.Replace(html, "<(.|\n)+?>", String.Empty)
        End If
    End Function

Which isn’t a bad way to go, but what if you could extend that sealed String class?  What if you would like it to show up using IntelliSense?  Would that make things much easier?

    Dim comments As String
    comments = Me.txtComments.Text.StripHtml

I would say the code is even more readable then the previous example.  The only difference between the two methods is the added:  <Extension()> _

    <Extension()> _
    Public Function StripHtml(ByVal html As String) As String
        If html Is Nothing OrElse html = String.Empty Then
            Return String.Empty
        Else
            Return Regex.Replace(html, "<(.|\n)+?>", String.Empty)
        End If
    End Function

Once you have your [Extension()] ready to go, you can see the results using IntelliSense.  Notice your new extension method has a down arrow just to the left of the extension name?  Thus you will always know if you are calling an extension method, or a native method of the class.


The obvious downfall of using extension methods would be software engineers starting to use them like they are going out of style.  If the situation calls for it one should use inheritance, but this could be a quick way to add that one method you need without having to use the inherited class all throughout your code.

Comments are closed
Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my wife's view in anyway, unless she wrote it.

© Copyright 2010 Teegarden.net