-1

I want to receive something from WriteLine and associate a variable and after verify is what the user write is a int.

i have this

Console.WriteLine("Idade:");
int idade2 = Convert.ToInt32(Console.ReadLine());
if (???)
{
     Console.WriteLine("Insira um número não uma string:");
}
else
{
     pessoa.idade = idade2;
}

i see some stuff in other post internet etc about int.TryParse ( variavel_string, out variavel_int) but for me dont make sense and i dont think i need it.

in other language is very simple isnumeric(variable) and works in c# i dont know what to do.

What i need put in if condition to work?

Pedro Pinheiro
  • 133
  • 1
  • 12
  • 5
    `TryParse` is definitely the way to go. – Martin Feb 11 '20 at 12:31
  • Well, you indeed need `int.TryParse()`. What's wrong with it ? – Cid Feb 11 '20 at 12:31
  • "_i see some stuff in other post internet etc about int.TryParse ( variavel_string, out variavel_int) but for me dont make sense and i dont need it._" `Int.TryParse()` seems like exactly what you need here - why do you think it isn't? – Diado Feb 11 '20 at 12:31
  • Are you looking for this: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/how-to-convert-a-string-to-a-number ? – Jabberwocky Feb 11 '20 at 12:31
  • https://stackoverflow.com/questions/1019793/how-can-i-convert-string-to-int – ZedLepplin Feb 11 '20 at 12:32

1 Answers1

5

Using TryParse seems like the most appropriate way to solve your issue. Consider your code with the change to use it:

if (int.TryParse(Console.ReadLine(), out int idade2)
{
    pessoa.idade = idade2;
}
else
{
    Console.WriteLine("Insira um número não uma string:");
}

TryParse verifies that the entered string is an int and returns a boolean that indicates this, which you can use to verify it before proceeding.

On the other hand, your use of Convert:

Convert.ToInt32(Console.ReadLine());

Will result in an Exception if the string is not a valid int. Not graceful and although it can be handled with a Try...Catch block, it's not necessary.

Martin
  • 16,093
  • 1
  • 29
  • 48