I talked about fixed the IsNullOrEmpty method on the string object here.
But another aspect of the string object that has irritated me for a while is the Length property.
Obviously, the Length property returns the length of the current instance of a string variable.
However, because it’s an instance property, it can only be invoked against variables that have actually already been initialized to some value.
If you try and run this code, you’ll get an Object Not Set error when you execute the second line:
dim s as string
debug.print s.Length
Now, anybody that’s coded in VB intuitively knows that an unitialized string has a length of 0, and such a request should certainly not result in throwing an error. It doesn’t matter one whit whether this is technically incorrect or not. I my book, those issues are for the compiler to work out, NOT the programmer.
Since the string class is an intrinsic type and we really can’t inherit from it or extend it in any traditional way, is there any way to correct this gaff?
With VB 2008, there is.
I blogged a bit about extension methods in the previous mentioned post and that’s what I’ll use to fix the Length property as well.
Unfortunately, as I also mentioned in my previous post, Length is a property and not a method, so you can’t create an extension method for it directly, which is a shame.
However, long time VB programmers don’t think to use “Length” anyway, you always retrieved the length of string via LEN(stringname), and LEN is not a member of the string object.
So, just add the following to a module to your application:
Imports System.Runtime.CompilerServices
Module StringExtensions
''' <summary>
''' Returns length of the string or 0 if the string is empty or has never been assigned (is nothing)
''' </summary>
''' <param name="aString"></param>
''' <returns></returns>
<Extension()> _
Public Function Len(ByVal aString As String) As Integer
Return Microsoft.VisualBasic.String.Len(aString)
End Function
End Module
and you’ll have a LEN function available directly from any string variable that will work regardless of whether the variable is initialized or not.
Also, note the <summary> comment. This will be displayed by Intellisense in the IDE, which can be quite handy.
And finally, you can’t use Return Len(aString) in the function, because doing so would be treated as a recursive call to the Len Extension method itself! Thus, I fully qualify the call to the Microsoft.VisualBasic.Strings LEN function.
All of this begets the obvious next question, “Why not just use Len(stringvar)“?
To which, I have no good answer.
Maybe it’s just a .NET thing<g>