Home > database >  System.ArgumentOutOfRangeException Message=Length cannot be less than zero. (Parameter 'length&
System.ArgumentOutOfRangeException Message=Length cannot be less than zero. (Parameter 'length&

Time:10-23

Why is this code giving me a "length cannot be less than zero" error message?

class Fraction
     {
         private double Numerator = 0;
         private double Denominator= 1;

         public static Fraction Parse(string str)
         {
             Fraction newFrac = new Fraction();

             int indexSlash = str.IndexOf("/");
             newFrac.Numerator = int.Parse(str.Substring(0, indexSlash));
             newFrac.Denominator = int.Parse(str.Substring(indexSlash   1));

             return newFrac;
         }
     }

CodePudding user response:

string.IndexOf() returns -1 when the string does not contain the expected sequence (a slash in this case). So when you call Parse() with a string that does not contain a slash ("/"), the next line calls str.Substring(0, -1), which is obviously illegal.

CodePudding user response:

The cause of the message is that str doesn't contain /:

// when str doesn't contain "/", the result of IndexOf is -1
// So indexSlash == -1 
int indexSlash = str.IndexOf("/");
// str.Substring(0, indexSlash)
//   is now
// str.Substring(0, -1)
//   which throws the exception
newFrac.Numerator = int.Parse(str.Substring(0, indexSlash));

I suggest starting implementation from TryParse:

class Fraction {
  ...
  public static bool TryParse(string value, out Fraction result) {
    result = null;

    if (value is null)
      return false;

    int index = value.IndexOf('/');

    if (index <= 0)
      return false;

    if (!int.TryParse(str.Substring(0, index), out var num) || 
        !int.TryParse(str.Substring(index   1), out var den))
      return false;

    result = new Fraction() {
      Numerator   = num, 
      Denominator = den
    };

    return true;
  }

And based on it Parse which is very simple now:

  public static Fraction Parse(string value) => TryParse(value, out var result)
    ? result
    : throw new FormatException("Not a valid format for fraction");
  • Related