Search code examples
c#tryparse

What value is returned in TryParse()?


I was reading the book Fundamentals of Computer Programming with C#

string str = Console.ReadLine();
int Value;  
bool parseSuccess = Int32.TryParse(str, out Value);
Console.WriteLine(parseSuccess ? "The square of the number is " + (Value * Value) + " . "  : "Invalid number!" );

So my question is that in the third line bool parseSuccess = Int32.TryParse(str, out Value); the Int32.TryParse() won't it return an int value? How can that be bool? And what exactly does the keyword out mean?


Solution

  • Int32.TryParse returns a Boolean to indicate whether the parsing was successful or not (if the string contained non-numeric characters then the conversion would fail).

    out means that the parameter is passed by reference (this means that what is passed to the TryParse function is the memory address of your variable).