Search code examples
c#stringintswitch-statementconsole.readline

Error says that it can't transform string into int


      string num;
            num = Console.ReadLine();
            Console.WriteLine(num);
            switch (num)
            {case 1:
            Console.WriteLine(one);

I'm trying to do a c# project where you type a number from 1 to 100 and you see the wrote version of it.


Solution

  • The variable num is a string. But you're trying to compare it with an integer here:

    case 1:
    

    The quickest solution would be to compare it with a string:

    case "1":
    

    Alternatively, and possibly as a learning experience for you, you may want to try converting num to an int. Take a look at int.TryParse for that. An example might look like this:

    string num = Console.ReadLine();
    int numValue = 0;
    if (!int.TryParse(num, out numValue)) {
        // The value entered was not an integer.  Perhaps show the user an error message?
    }