If statement not being executed as intended

As the commenters have already pointed out, numeric characters are not numbers, 1 != '1'. I won’t follow that one up, I figure you already got that message.

Since this is designed to interact with a user it might be clearer and more useful to use the Console.ReadKey method to acquire keypresses. The return value is a structure that contains a lot more information about the key that was pressed, including the modifier keys and so on. Instead of doing comparisons with characters there is an enum that names each key.

This is how I’d approach your problem:

string worldName = string.Empty;

// wait for keypress, don't display it to the user
// If you want to display it, remove the 'true' parameter
var input = Console.ReadKey(true);

// test the result
if (input.Key == ConsoleKey.D1 || input.Key == ConsoleKey.NumPad1)
{
    Console.Write("Insert World's name: ");
    worldName = Console.ReadLine();
}
else if (input.Key == ConsoleKey.D2 || input.Key == ConsoleKey.NumPad2)
{
    Console.WriteLine("Loading World: {0}", worldName);
}

And so on.

What it also allows you to do, which the Console.Read method does not, is to handle keypresses that are not alphanumeric. For example, if you want to use function keys instead:

// F1
if (input.Key == ConsoleKey.F1)
{
    Console.Write("Insert World's name: ");
    worldName = Console.ReadLine();
}
// F2
else if (input.Key == ConsoleKey.F2)
{
    Console.WriteLine("Loading World: {0}", worldName);
}

And of course handling keyboard modifiers:

// Shift-F1
if (input.Key == ConsoleKey.F1 && input.Modifiers == ConsoleModifiers.Shift)
{
    Console.Write("Insert World's name: ");
    worldName = Console.ReadLine();
}
// F2 with any comnination of modifiers that does not include Alt
// (F2, Shift-F2, Ctrl-F2, Ctrl-Shift-F2)
else if (input.Key == ConsoleKey.F2 && !input.Modifiers.HasFlag(ConsoleModifiers.Alt))
{
    Console.WriteLine("Loading World: {0}", worldName);
}

Leave a Comment