little Substring question (vb.net)

Vampie

Newcomer
Joined
May 8, 2008
Messages
4
hi all,

Got a little question about Substring (yes, its a .net 2.0 application i'm using it in)

if you use the following code on MyString that is less then 30 characters long, i get an error: (ArgumentOutOfRangeException) :(
Visual Basic:
MyString.Substring(0, 30)
I got 2 solutions:
Solution 1:
Visual Basic:
If MyString.Length < 30 Then
    Myfield = MyString
Else
    Myfield = MyString.SubString(0,30)
End If
Solution 2:
Visual Basic:
MyField = MyString.PadRight(30).Substring(0, 30)

What is the best solution?
Or is there a method that can take everything if it is less then 30 and only the 30 first chars if it is longer than 30 chars?
 
Last edited:
I would use Solution 1, since it involves a check and then action based on that check. I'd avoid padding a string just to use substring on it since string operations are generally "slow" compaired to a check on (int < int).
 
Unless you are doing at least thousands upon thousands of string comparisions, there really is no legitimate concern about performance. It is good to know which method is faster, but the real reason that I would go with option # 1 is because it is more straight-forward and self-explanitory, even if it is longer. In this particular instance, I think either solution would be perfectly adequate, but in terms of general coding style it is best to avoid the potentially cryptic and stick with code that spells out what it is doing.
 
I think that marble has a valid point about clarity and in general I agree with him that the performance gain is negligible; however, all the applications which make this assumption in a few places burn extra CPU cycles for no reason. Over several applications and an OS this can lead to a noticable slow down.

IMHO
 
Back
Top