Extending VB.NET objects that are marked as NotInheritable

One of the neat things in VB.Net is something called an "Extension" which allows you to extend the ability of other classes (even if its not possible to subclass the object with inheritance).  For example, in vb6 a lot of times we use Left$() and Right$() to work with strings, and there is a vb.net version of these (right() and left()) but it doesn't exist as a method as part of the string itself.  For example,

dim MyString as string = "hello"
debug.print left(myString,1) <-- prints 'h'

but you can use the ToUpper method right off the string itself...

debug.print myString.ToUpper <-- the same as ucase(myString)

The code below adds 'left' and 'right' extensions to the string class so you can do this ..

Imports Example.Code.StringExtensions
debug.print mystring.toupper.left(1) 

I also added 'qptrim' as an extension of the trim method that strips out nulls as well.  

debug.print mystring.qptrim

Below is how you implement extensions in VB.NET.  You can use this to add extensions to type or class in your project. 

Imports System.Runtime.CompilerServices   '' Adds <Extension()> 

Namespace Global.Example.Code

Module StringExtensions
<Extension()> '' Add QPTrim() method to a standard String
Public Function QPTrim(ByVal myStr As String) As String
Return Replace(myStr, Chr(0), "").Trim
End Function

<Extension()> '' Add Right() method to a standard String
Public Function Right(ByVal myStr As String, ByVal nChars As Integer) As String
Return myStr.Substring(myStr.Length - nChars, nChars)
End Function

<Extension()> '' Add Left() method to a standard String
Public Function Left(ByVal myStr As String, ByVal nChars As Integer) As String
Return myStr.Substring(0, nChars)
End Function

<Extension()> '' Add NoSlash() method to a standard String
Public Function NoSlash(ByVal myStr As String) As String
While myStr.Right(1) = "\"
myStr = myStr.Left(myStr.Length - 1)
End While
Return myStr
End Function
End Module
End Namespace

Arguably, .NET Purists see this as syntactic sugar.  True, the extension is merely an alternative to calling a function and passing the current string into the function.  However I think the extensions really contribute to readability, especially when you combine multiple methods together.  


Popular posts from this blog

Installing OTRS 4.0 on Ubuntu Linux 14.04 with a MSSQL Backend

that new old thing: a date2num implementation in vb.net

Getting Started with GitHub and Visual Studio 2017