codebeater

General .NET, ASP.NET, C# and VB.NET discussion

About the author

Author Name is someone.
E-mail me Send mail

Recent comments

Authors

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008

Extension methods in Visual Basic

In my previous article about extension methods I discussed how to implement them only in C#, as I had not yet looked at them in Visual Basic.  Today I decided to finally take a look and was expecting something similar to how it is implemented in C# but what I found was different enough to warrant talking about it again, I believe.  Anyway, let's get to it.

The first big difference I notice is that, in Visual Basic, you must define extension methods in a module.  I'm not sure why this is the case, but it is.  The second difference is that you must mark your extension methods with the extension attribute <Extension()> from the System.Runtime.CompilerServices namespace.  So once you have your module and you've imported the System.Runtime.CompilerServices namespace you're ready to create an extension method.  Here's the Visual Basic version of a sample extension from Scott Guthrie's blog:

Imports System.Text.RegularExpressions
Imports System.Runtime.CompilerServices

Module MyExtensions

    <Extension()> _
    Public Function IsValidEmailAddress(ByVal s As String) As Boolean
        Dim regex As New Regex("^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$")
        Return regex.IsMatch(s)
    End Function

End Module

In this function I've extended the string type.  Using this approach I can now call IsValidEmailAddress on the string variable itself.  I think this example is a perfect demonstration of the ease in which extension methods can be created and used.  A word of caution is in order, though, as it is quite easy to cause some namespace and method name collisions or make your code a little more difficult to debug.  As an example, some of the examples I used when creating the C# post on this topic don't seem to work very well using VB, so use with care. 

vb_extensionmeth

If you want more information please read the C# post or visit the MSDN article regarding Extension Methods in Visual Basic.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:
Posted by jeff on Sunday, April 27, 2008 4:50 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Related posts

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

Thursday, November 20, 2008 9:40 AM