Search code examples
c#.netint

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


I read this from msdn about Int32.TryParse()

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 TryParse will return zero. How can I know if it is a success or a failure?


Solution

  • 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
    }
    else
    {
        // 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.