There is a better way of avoiding null inputs in
Console.ReadLineinstead of if statements
The answer is yes.
Though it’s worth noting, there are more things that can go wrong with user input than just
null. In fact
null is pretty rare, it’s everything else you need to worry about.
The most idiomatic way to validate user numeric input is with
TryParse style methods, which return a bool when the value can’t be parsed and returns a value through an
out parameter when
Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the operation succeeded.
You can take it a step further by using a validation loop
int m1 = 0; while (!int.TryParse(Console.ReadLine(), out m1)) Console.WriteLine("You hard one job! Now try again");
Essentially the above says, while the number can’t be converted to an integer, which includes typos, empty input, and Ctrl+c (null), write a message.
CLICK HERE to find out more related problems solutions.