Home > Software design >  System.FormatException: 'Input string was not in a correct format.' c# complete beginner
System.FormatException: 'Input string was not in a correct format.' c# complete beginner

Time:02-27

give other advice on how to improve the code. when I launch the program, and I select the second option and put the info in, it comes up with error.

 static void InsertRecord()
    {
        records.Add(" name"); // 0
        records.Add(" name");  // 1
        records.Add(" name");  //2
        Console.WriteLine("Please enter first name");
        string fName = Console.ReadLine();
        Console.WriteLine("Please enter Last name");
        string lName = Console.ReadLine();
        int loc = Convert.ToInt32(Console.ReadLine()); // this line has the error
        if (loc > records.Count)
        {
            Console.WriteLine("Location out of range");
        }
        else
        {
            records.Insert(loc, fName   lName);
        }
        Console.ReadKey();
    } 

CodePudding user response:

Instead of using Convert.ToInt32, use Int32.TryParse, which:

Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the operation succeeded.

For documentation, please have a look here.

The benefit of using that method instead of Convert.ToInt32 is that it will not throw any exception, when the input isn't the expected one. It will just return false, indicating that the parse failed.

So we have to delete the following line:

int loc = Convert.ToInt32(Console.ReadLine());

and try the following:

if (Int32.TryParse(Console.ReadLine(), out int loc))
{
    if (loc > records.Count)
    {
        Console.WriteLine("Location out of range");
    }
    else
    {
        records.Insert(loc, fName   lName);
    }
}

You could also add an else statement in the above, for the inputs that parsing fails and inform the user of your application that the input wasn't the expected one.

  •  Tags:  
  • c#
  • Related