Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

int

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?

like image 980
NLV Avatar asked Dec 29 '10 08:12

NLV


People also ask

What does TryParse return on 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.

What does Int32 TryParse do?

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.

What does TryParse return in C#?

TryParse method returns false i.e. a Boolean value.

What method parameter type is used by TryParse method?

The type of this parameter is System. Char.


2 Answers

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.

like image 134
Jon Skeet Avatar answered Sep 21 '22 13:09

Jon Skeet


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"); 
like image 24
BoltClock Avatar answered Sep 25 '22 13:09

BoltClock