-3

I'm trying to understand int.TryParse to check if the user inputted the correct thing (in this case an int) but unsure what to type in after out.

Console.WriteLine("write a number into the console");

int thisnumber = Convert.ToInt32(Console.ReadLine()); // this line is converting user inputs string into a int number.
if (!int.TryParse(thisnumber, out )) 
{
    Console.WriteLine("Not an integer");
}
else
{
    Console.WriteLine("this is a integer");
}
Callum Watkins
  • 2,844
  • 4
  • 29
  • 49
  • https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse – Herohtar Feb 09 '20 at 02:49
  • 1
    Always check the documentation; there are usually examples of how to use it. However, since you are using `Convert.ToInt32` first, `thisnumber` is already an integer and you do not need to *also* use `TryParse`. (And you'll also get an exception if the input is not something that `Convert.ToInt32` can handle). You should only use one of them. – Herohtar Feb 09 '20 at 02:51
  • It's better to use int.TryParse than convert.ToInt32, because a format exception will be raised if the input can't be converted to a int. when using the int.TryParse, you need to specify the type that you want to parse,ie, you are trying to see if the input is an int. variable of type int is required, this will hold the value of the parsing. if (!int.TryParse(input, out int result )) { Console.WriteLine("Not an integer"); } else { Console.WriteLine("this is a integer"); } – Richard Feb 09 '20 at 03:04
  • Does this answer your question? [How the int.TryParse actually works](https://stackoverflow.com/questions/15294878/how-the-int-tryparse-actually-works) – Manish Feb 09 '20 at 03:34

1 Answers1

1

Check if input is a number like this,

Console.WriteLine("wrtie a number into the console");
int thisnumber;
if (!int.TryParse(Console.ReadLine(), out thisnumber))
{
    Console.WriteLine("Not an integer");
}
else
{
    Console.WriteLine($"this is an integer : {thisnumber}");
}
TheGeneral
  • 79,002
  • 9
  • 103
  • 141
Jawad
  • 11,028
  • 3
  • 24
  • 37