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?
TryParse method converts a string value to a corresponding 32-bit signed integer value data type. It returns a Boolean value True , if conversion successful and False , if conversion failed. In case of failed conversion, it doesn't throw any exception and 0 is assigned to the out variable.
TryParse(String, Int32) Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded.
TryParse method returns false i.e. a Boolean value.
The type of this parameter is System. Char.
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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With