Search code examples
c#visual-studioconsolesyntax-errorconsole-application

How can I send and error when I get an input that is not a number? [C#]


I want an error to appear when the client writes a symbol or a letter

int n = 0;
string ent;

ent = Console.ReadLine();
n = int.Parse(ent);

if (n.GetType() != typeof(int)) {
    Console.WriteLine("Must be a number");
}


Solution

  • Take a look at the official docs and the example usage:

    Either wrap the int.Parse in a try-catch block as suggested in the official docs or use int.TryParse() here.

    Try catch example:

    int n = 0;
    string ent;
    
    ent = Console.ReadLine();
    try {
        n = int.Parse(ent);
    } catch (FormatException) {
        Console.WriteLine("{0}: Must be a number", ent);
    }