Take the 2-minute tour ×

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;


int type = 0;
int.TryParse(someString, out type);
share|improve this question
Anyone trying to understand the code will wonder the same thing. –  Strilanc Nov 1 '10 at 0:12
Since it's an out parameter, it must be assigned before TryParse return (unless it throws an exception). –  Gabe Nov 1 '10 at 1:16

4 Answers 4

up vote 8 down vote accepted

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.

share|improve this answer
Hmm, interesting. I did not see that part. –  anthony-arnold Nov 1 '10 at 0:01

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.

share|improve this answer

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

share|improve this answer

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
  ; // type is set to zero, do nothing
share|improve this answer

Your Answer


