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

后端 未结 5 1638
萌比男神i
萌比男神i 2021-01-01 09:06

I read this from msdn about Int32.TryParse()

When this method returns, contains the 32-bit signed integer value equivalent to the num

5条回答
  •  盖世英雄少女心
    2021-01-01 09:23

    The method returns a boolean indicating success or failure. Use that. The integer is a reference parameter passed into the method, and has nothing to do with the return value of the method.

    Here's the prototype of Int32.TryParse() from the documentation. It's very clear that it returns a boolean. The second parameter is an out int which means that argument is passed by reference, so it will be mutated by the method.

    public static bool TryParse(
        string s,
        out int result
    )
    

    So to check success or failure, do this:

    int value;
    
    if (Int32.TryParse("0", out value))
        Console.WriteLine("Parsed as " + value);
    else
        Console.WriteLine("Could not parse");
    

提交回复
热议问题