Validate an int and pass it to string

1

Good people, how are you? , I'm new to programming and I have a doubt

Console.WriteLine("Ingresar un tipo");

int unTipo = Convert.ToInt32(Console.ReadLine());
if (unTipo == 1)
{

}

As you can see in the code, it is a console test in C # and what it asks is to enter a number and that the variable, according to the number entered that variable would have to take a value String , How can I do that?

Thank you very much

    
asked by Metallico 06.04.2017 в 21:14
source

1 answer

1

You can use Int32.TryParse ()

Console.WriteLine("Ingresar un tipo");
String input = Console.ReadLine();
    if(Int32.TryParse(input, out opcion))
    {
          switch(opcion) 
          {
               case 1:
                     //Opcion 1
                     break;
               case 2:
                    //Opcion 2
                    break;
               default:
                    Console.WriteLine("No es un tipo valido.");
               break;
          }

    } 

But you can also take the character directly without converting it:

 Console.WriteLine("Ingresar un tipo");

    string opcion = Console.ReadLine();
    switch(opcion)
    {
        case "1":
            //Opcion 1
            break;
        case "2":
            //Opcion 2
            break;
        case "3":
            //Opcion 3
            break;
        case "4":
            break;
        default:
            Console.WriteLine("No es un tipo valido.");
            break;
    }
    
answered by 06.04.2017 в 21:22