Wednesday, November 27, 2013

Creating Extension Methods in VB .NET

An "extension method" is a method of a class or interface that is actually defined in a different module, usually by a different author. They are usually used to "extend" the functionality of existing types without creating new ones.

In C#, creating extension methods is pretty easy. Simply put a "this" before the type on the first argument, which indicates that it is the instance on which the method is running. In VB, it's slightly different but still pretty simple. First, import System.Runtime.CompilerServices at the top of the file containing the module. Then, apply the <Extension> attribute to the Sub or Function. When writing the method body, write as if the first argument is the current object. It obviously has to be the same type as the type to which you'd like to apply the extension.

Here's one I like to add to the string type:

Imports System.Runtime.CompilerServices

Module Extensions
 <Extension> Public Function EqCaseless(This As String, _
  Other As String) As Boolean
  Return String.Equals(This, Other, _
   StringComparison.InvariantCultureIgnoreCase)
 End Sub
End Module

Then, I can compare strings caselessly like this:

If input.EqCaseless("splosions") Then End

No comments:

Post a Comment