RSS

VB Left() and Right() equivalent in VB.NET

20 Mar

When trying to rewrite VB string manipulation codes into .NET framework version, old VB Left() and Right() methods could be seen in the lines very often. At first I rewrote them as :

'Declaration
'Public Function Substring ( _
'    startIndex As Integer, _
'    length As Integer _
') As String

' str = Left(str, length) equivalent
str = str.Substring(0, length)
' str = Right(str, length) equivalent
str = str.Substring(str.Length - length)

Generally this works fine but could potentially cause startIndex and length out of range exception in conditions like:

Dim str As String = "01234"
str = Left(str, 6)           'str = "01234"
str = str.Substring(0, 6)    'Exception

There’s a much more feasible solution on stackoverflow by Noldorin which uses Math.Min() for Left() to make sure the out of range exception won’t happen. Here are the refined equivalents according to Noldorin’s solution:

' str = Left(str, length) equivalent
str = str.Substring(0, Math.Min(length, str.Length))
' str = Right(str, length) equivalent
str = str.Substring(Math.Max(str.Length, length) - length)
Advertisements
 
Leave a comment

Posted by on March 20, 2012 in .NET, VB

 

Tags:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: