Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do TryParse methods uses an out parameter and not a ref

Tags:

c#

parsing

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?

like image 988
aqwert Avatar asked Feb 29 '12 00:02

aqwert


1 Answers

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.

like image 94
SLaks Avatar answered Sep 18 '22 14:09

SLaks