Saturday, 20 July 2019

C# - Fix Error - Index and length must refer to a location within the string. - Check against string length

Watch this example on YouTube


Fix error

An exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll but was not handled in user code

Additional information: Index and length must refer to a location within the string.

To fix it replace 

  string s1 = "ab";
  string s2 = s1.Substring(0, 100);
          
with

  string s1 = "ab";
  string s2 = s1.Substring(0, s1.Length> 100 ? 100: s1.Length);

No comments:

Post a Comment