Sunil
Sunil

Reputation: 2905

Index and length Error - Any better logic...?

Following code throws the error
'Index and length must refer to a location within the string. Parameter name: length'.

Sub Main()
  Dim Ex As String
  Dim yy As String = 
       (If(String.IsNullOrEmpty(Ex), "", Ex)).ToString().Substring(0, 1000)
End Sub

From above code it is clear that the error is due to string Ex is nothing.
But to resolve the issue

1. Need to check
   a. Whether the string is Null Or Empty
   b. If not, 
      a. Has more than 1000 chars.....? extract 1000 chars.
      b. Else use the string as it is.

To implement above logic, need least 2 If clauses.
Do we have any better logic to implement above…?

Thanks in advance.

Upvotes: 1

Views: 83

Answers (1)

Heinzi
Heinzi

Reputation: 172388

Since you are using VB.NET, all you need is:

Dim Ex As String
Dim yy As String = Left(Ex, 1000)

The Left function already knows how to deal with Nothing and with strings that are shorter than the specified length.


If you want to stick to .NET methods, the solution would look as follows:

Dim Ex As String
Dim temp As String = If(Ex, "")
Dim yy As String = If(temp.Length > 1000, temp.Substring(0, 1000), temp)

I have added an extra variable for clarity:

The two-parameter If operator returns the second argument if the first one is Nothing (otherwise, it returns the first argument). It's equivalent to C#'s ??.

The last line checks the length of the string before using Substring, thus avoiding the error message you get in your example.

Upvotes: 1

Related Questions