Extensions are a great way to call often used methods to tweak a value while shortening code length and improving readability.
If you’ve done much .NET programming, you’ve already used built-in extensions, for example ToLower:
Dim tmpString1 As String = "BLAH" Dim FinalValue As String = tmpString1.ToLower
But another cool feature of VB.NET is that you can define your own extensions. You must define your extensions in side a module (not a class). Here are the example extensions I’ll use for the rest of this article:
Imports System.Runtime.CompilerServices Module StringExtensions <Extension()> _ Function SafeConvertToLong(ByVal TheString As String, Optional ByVal DefaultValueWhenBlankOrInvalid As Long = 0) As Long If TheString = "" Then Return DefaultValueWhenBlankOrInvalid Dim ReturnLong As Long If Long.TryParse(TheString, ReturnLong) Then Return ReturnLong End If Return DefaultValueWhenBlankOrInvalid End Function <Extension()> _ Public Function FirstWord(ByVal TheString As String) As String Dim SpacePosition As Integer = InStr(TheString, " ") If SpacePosition = 0 Then Return TheString Return Left(TheString, SpacePosition).Trim End Function End Module
Extensions can be used via the DOT notation after a variable of the same type as the first parameter to the extension. For example, since the two example extensions above both have a String value as their first parameter, then they “extend” the String type.
The code below shows some examples of using the “SafeConvertToLong” example String extension:
Dim tmpLong1 As Long Dim tmpLong2 As Long Dim tmpLong3 As Long tmpLong1 = "3832".SafeConvertToLong tmpLong2 = "blah".SafeConvertToLong tmpLong3 = "blah".SafeConvertToLong(-1L) Console.WriteLine("tmpLong1 = " & tmpLong1.ToString) Console.WriteLine("tmpLong2 = " & tmpLong2.ToString) Console.WriteLine("tmpLong3 = " & tmpLong3.ToString)
and this code produces the following output:
tmpLong1 = 3832 tmpLong2 = 0 tmpLong3 = -1
Even though you’ve declared a function as an extension, you can use it just like a normal function as well:
Dim tmpLong4 As Long tmpLong4 = StringExtensions.SafeConvertToLong("75") Console.WriteLine("tmpLong4 = " & tmpLong4.ToString)
Will produce this output:
tmpLong4 = 75
Extensions get even cooler when you stack multiples together and even use your own extensions along with the built-in ones:
Dim tmpString2 As String tmpString2 = "THIS IS A TEST".FirstWord.ToLower Console.WriteLine("tmpString1 = " & tmpString2)
Which produces this output:
tmpString1 = this
Extensions are a great way to implement highly reusable code that slightly transforms a value. Used correctly, they can reduce the size of your code and make it much more readable.