0
int resultid;
Int32.TryParse(collection["id"],out resultid);

the values are coming in collection["id"] but resultid showing 0 for some of the values greater than 8 digit numbers. So that I tried with long also same issue ,getting resultid as 0. Could please suggest?

5
  • 4
    What is the value of collection["id"] exactly? Commented Dec 20, 2013 at 13:30
  • Posting an example of these values that cannot be parsed would be useful Commented Dec 20, 2013 at 13:30
  • Zero is default value for int, so it means you are putting wrong value and tryparse fails. It's why resultid is 0 Commented Dec 20, 2013 at 13:31
  • Make sure that the number is in the correct format too. It's best if there's nothing but numbers (and a single minus sign if appropriate). The number could be formatted with thousands separators for example, which might require you to use culture dependent parsing or somesuch. Commented Dec 20, 2013 at 13:39
  • collection["Id"] values like 123456789123456789123456789123456789123456789,32112312312,12312312312 etc like that getting zero in out result varieable . Commented Dec 21, 2013 at 4:19

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You didn't mentioned to use what is exactly collection["id"] but..

From Int32.TryParse Method (String, Int32)

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

Looks like your conversation fails because of your collection["id"] is bigger than Int32.MaxValue but since you didn't tell us more information, it is almost not possible to give exact answer..

Int64 also has a TryParse method that I think it can hold your value like;

int resultid;
bool success = Int64.TryParse(collection["id"], out resultid);

Comments

-1
string s1 = "1234"; 
string s2 = "1234.65"; 
string s3 = null; 
string s4 = "123456789123456789123456789123456789123456789";


 success = Int32.TryParse(s1, out result); //-- success => true; result => 1234 
 success = Int32.TryParse(s2, out result); //-- success => false; result => 0 
 success = Int32.TryParse(s3, out result); //-- success => false; result => 0 
 success = Int32.TryParse(s4, out result); //-- success => false; result => 0 

1 Comment

Nice examples, but a bit of context would have helped

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.