Friday, May 18, 2007

.NET Left & Right Replacements

Back in the days of VB6 there were two trusty functions that programmers could rely on to truncate string: Left and Right. These functions live on in the .NET Framework, but they live in the dreaded Microsoft.VisualBasic namespace, a namespace both shunned and feared by many. But do not loose hope, fair .NET programmer, for there is a “pure” way to easily reproduce the functionality of the Left and Right function with out resorting to the Microsoft.VisualBasic namespace methods.

All silliness aside, there is a simple way to reproduce the functionality of the Left and Right functions using non-Microsoft.VisualBasic namespace methods. The typically answer to this question is to use the Substring method, but the Substring method requires to use valid startIndex and length arguments.

In VB6 if you had a three-character string called TestString and called Left(TestString, 5), you would get your three-character string back. In .NET if you were to have this same string and call TestString.Substring(0, 5) method, you would get a ArgumentOutOfRangeException exception.

I colleague of mine came up with the following way to reproduce the functionality of the old VB6 Left function: TestString.Substring(0, Math.Min(5, TestString.Length))

The old VB6 Right function can be reproduced by using the following: TestString.Substring(TestString.Length – Math.Min(5, TestString.Length), Math.Min(5, TestString.Length))