Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TryParse() - Why does this code return 0, shouldn't the result be -1?

See the following code:

string test = "";
int output = -1;

if (int.TryParse(test, out output))
{
    Console.WriteLine("Parsed");
}

Console.WriteLine(output);

When TryParse() fails, shouldn't the block be skipped over, Console.WriteLine("Parsed") not called and the value of output be the same (-1)?

It's returning 0

like image 748
dtsg Avatar asked Jun 13 '12 09:06

dtsg


People also ask

What does TryParse return?

TryParse(String, Int32) Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded.

What does TryParse return in C#?

TryParse is . NET C# method that allows you to try and parse a string into a specified type. It returns a boolean value indicating whether the conversion was successful or not. If conversion succeeded, the method will return true and the converted value will be assigned to the output parameter.

What are the two things the TryParse () method does?

The TryParse() method receives two parameters. The first parameter is the string to be converted. The second parameter is the variable to store the converted value.

What happens when TryParse fails?

TryParse method converts a string value to a corresponding 32-bit signed integer value data type. It returns a Boolean value True , if conversion successful and False , if conversion failed. In case of failed conversion, it doesn't throw any exception and 0 is assigned to the out variable.


1 Answers

From MSDN:

When this method returns, contains the 32-bit signed integer value equivalent to the number contained in string, if the conversion succeeded, or zero if the conversion failed.

like image 149
Talha Avatar answered Sep 19 '22 13:09

Talha