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
The implementation of
TryParsehas to default theoutparameter before returning otherwise it won’t compile – regardless of whether you have initialised theoutparameter from the calling side. This is the case for any method withoutparameters and is not specific toTryParse.The people who coded it chose to default the parameter to zero when the parsing fails.
The important part is you should not think that any
outparameter methods will honour the original value of theoutparameter when it is passed in. In fact, it can never honour the parameter as the compiler will report:If you attempt to use the parameter value before assigning to it inside the method. So you can actually guarantee that any value you assign and give to as an
outparameter will be ignored / overwritten.