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
Решение
The implementation of TryParse
has to default the out
parameter before returning otherwise it won't compile - regardless of whether you have initialised the out
parameter from the calling side. This is the case for any method with out
parameters and is not specific to TryParse
.
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 out
parameter methods will honour the original value of the out
parameter when it is passed in. In fact, it can never honour the parameter as the compiler will report:
use of unassigned out parameter 'blah'
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 out
parameter will be ignored / overwritten.
Другие советы
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.
if it fails it will return false
and the code in the if statement won't be executed.
In the case the conversion fails it will also retun 0
that's why output=0
In C#, out
parameters have to be assigned to and cannot be initially read from. (When a method starts, the out
parameters are treated like uninitialized variables.)
Therefore, the previous value of output
is irrelevant. It had to be overwritten by the people who wrote the TryParse
method, otherwise it could not have been compiled.
At the same time, the TryParse
method has no access to the previous value of output
. Therefore, some value has to be chosen. In this case, the developers chose 0
.