0

I have been learning the basics of C# with a Console Application. I was wondering if anyone knew how to use an IF statement with a String instead of an integer. It's a bit annoying and I need it so I can compare a value the user has outputted to the console. This is because the Console.ReadLine(); only likes Strings and not Integers. Below is my code:

string num = Console.ReadLine();

if (num == 9)
{
    Console.WriteLine("Ooh my number is 9");
}

Any help is appreciated!

Lennart
  • 9,657
  • 16
  • 68
  • 84
AyesC
  • 193
  • 2
  • 14

1 Answers1

1

You should always validate integer user input with TryParse

int.TryParse

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

string value = Console.ReadLine();

if(!int.TryParse(value, out var num))
{
    Console.WriteLine("You had one job!");
}
else if (num == 9)
{
    Console.WriteLine("Ooh my number is 9");
}
TheGeneral
  • 79,002
  • 9
  • 103
  • 141