Somewhat on the back of this question that asks about the behaviour of the out
parameter but more focused as to why these TryParse
methods use out
and not ref
.
There have been some scenarios where you do want to initialise a value to the argument before parsing and keep that when the parsing fails but do not really care if it does fail. However because of the out
parameter the value is reset.
This scenario could look like this...
int arg = 123;
Int32.TryParse(someString, ref arg);
However because of the out
parameter we have to write it like this, which is more verbose...
int arg;
if(!Int32.TryParse(someString, out arg)
{
arg = 123;
}
I realise that knowing that the parsing failed can be very useful however the use of ref
does not preclude this.
So why do these TryParse methods use out
and not ref
?
Because the normal use pattern is exactly the opposite of what you're describing.
People should be able to write
int arg;
if (!Int32.TryParse(someString, ref arg)) {
Waaah;
}
Had TryParse
taken a ref
parameter, this would require a useless initialization.
The real question is why there isn't an int? int.TryParse(string)
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With