Does Int32.TryParse(String, Int32) alter the int argument on failure?
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开发者_如何转开发);
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.
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
精彩评论