tags:

views:

66

answers:

4

Out of interest, is it safe to assume that if Int32.TryParse(String, Int32) fails, then the int argument will remain unchanged? For example, if I want my integer to have a default value, which would be wiser?

int type;
if (!int.TryParse(someString, out type))
    type = 0;

OR

int type = 0;
int.TryParse(someString, out type);
A: 

If it fails, it returns false and sets type to zero. This would be wisest, as a result:

int type;

if (int.TryParse(someString, out type)) 
  ; // Do something with type
else 
  ; // type is set to zero, do nothing
Michael Goldshteyn
+2  A: 

TryParse sets the result to 0 before doing anything else. So you should use your first example to set a default value.

MikeP
+7  A: 

TryParse will set it to 0.

Since it's an out parameter, it wouldn't be possible for it to return without setting the value, even on failure.

SLaks
+7  A: 

The documentation has the answer:

contains the 32-bit signed integer value equivalent to the number contained in s, if the conversion succeeded, or zero if the conversion failed.

Joel Coehoorn