Question

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);
Was it helpful?

Solution

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.

OTHER TIPS

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.

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

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top