NLV NLV - 11 months ago 68
C# Question

Int32.TryParse() returns zero on failure - success or failure?

I read this from msdn about


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

But what happens if the passed string itself is a string representation of '0'. So the
will return zero. How can I know if it is a success or a failure?

Answer Source

No, TryParse returns true or false to indicate success. The value of the out parameter is used for the parsed value, or 0 on failure. So:

int value;
if (Int32.TryParse(someText, out value))
    // Parse successful. value can be any integer
    // Parse failed. value will be 0.

So if you pass in "0", it will execute the first block, whereas if you pass in "bad number" it will execute the second block.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download