Assign Value to a variable that the user puts C#

Asked

Viewed 92 times

-3

I am learning C# (Good at the beginning of learning) and I saw that anything that the user inserts by "Console.Readline();" is considered as a string automatically by Visual Studio, but how do I convert the value to another type of variable? The "Name" part works normally because it is a variable of type "string", but the "Age" part I can’t do the attribution of it because it is "int", what would I have to add or change to work? (do not call the last readline, it is only for the program does not close automatic)

        string nome;
        int idade;
        
        Console.WriteLine("Insira seu nome: ");
        nome = Console.ReadLine();
        Console.ReadLine();

        Console.WriteLine("insira sua idade: ");
        idade = Console.ReadLine();
        Console.ReadLine();

        Console.WriteLine("seu nome é:"+ nome);
        
        Console.WriteLine("sua idade é:"+ idade);
        
        Console.ReadLine();
  • 3

    é considerada como uma string automaticamente pelo Visual Studio no, see https://answall.com/q/101691/101. And the answer given only works in practice if the person enters the correct value, gives error in real application. It is good the people who come to Sopt to be attentive because today a lot of the answers given are teaching to do wrong, it was the time that the answers were almost always good.

  • @Maniero feel free to post your reply.

  • 3

    This has already been answered a huge number of times. Read: https://pt.meta.stackoverflow.com/q/8573/101

1 answer

-4


You need to convert what is typed to int first, here I used the function Convert.ToInt32()

string nome;
int idade;
        
Console.WriteLine("Insira seu nome: ");
nome = Console.ReadLine();

Console.WriteLine("insira sua idade: ");
idade = Convert.ToInt32(Console.ReadLine());
        
Console.WriteLine("seu nome é:"+ nome);
        
Console.WriteLine("sua idade é:"+ idade);

Source of SO-Eng

  • understood what you did, taking advantage, how would you convert into other type of string? type float, decimal, double, bool, string and char? I don’t know why, but I can’t find anything related to that

  • 1

    @Brenoleonetti You can continue using Convert, if you have autocomplete in your IDE, you will see that by giving Convert. will appear a range of options, for float would be Convert.Todouble(), also has options related to int.Parse() and for a double double.Parse()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.