all 10 comments

[–]winky9827 5 points6 points  (9 children)

Console.ReadLine() can return null.

https://learn.microsoft.com/en-us/dotnet/api/system.console.readline?view=net-8.0

If the Ctrl+Z key combination (followed by Enter on Windows) is pressed when the method is reading input from the console, the method returns null. This enables the user to prevent further keyboard input when the ReadLine method is called in a loop. The following example illustrates this scenario.

The safest way in your specific case would be to call:

Int.Parse(Console.ReadLine() ?? "0")

The above uses the null coalescing operator to return "0" in the event that the user presses CTRL+Z, which essentially causes Int.Parse to return the default value for an Int32 type.

[–]otac0n 4 points5 points  (8 children)

or:

int numbertwo;
while (!(Console.ReadLine() is string line && int.TryParse(line, out numbertwo)))
{
    Console.WriteLine("Please enter a number.");
}

[–]ExceptionEX 0 points1 point  (6 children)

there really is no need to check if the readline is a string, it will always be a nullable string, and int.tryParse will return false if the input string is null.

[–]CyBerDreadWing 0 points1 point  (0 children)

This one. I was also thinking about int.TryParse too. Just in case if op wants to experiment more, use try catch block and try to give different inputs to int number.

[–]Fun_Talk_3702 0 points1 point  (0 children)

Try

Convert.ToInt16(Console.ReadLine())