Search code examples
c#.netparsingtry-catchtryparse

TryParse places 0 on the variable when parse fails


Take this code snippet.

string input = "";
int value = 10;
bool success = int.TryParse(input, out value);

Whatever I use in input, be it null, "", "a", etc, when it's not a valid number, it returns false and paces 0 into value.

Isn't TryParse() meant to return a bool informing about sucess on the parse? When parse fails, shouldn't it just leave the variable unchanged?

This is annoying. So I'll need a variable to hold the value before calling TryParse(), and make a if to verify its result, and in case of failure copy the previous value back into the variable?

Update. I didn't find this behavior described in official doc, can you point where Microsoft describes it?

I mean, parsing in general, and TryParse()specially, isn't meant just to parse a string. It's also meant to validate the string. If TryParse() fails and returns false, it's not an error or exception, it means the string isn't a valid int (or whatever the data type), so I must handle this invalid string. That probably requires the previous value of the variable. If the variable is set to 0, the previous value is lost.

Why place a junk value and lose the previous value? This way, as I said, I'd need a second variable to hold that value, it's a waste.

I can extend or wrap TryParse(), but I'll need to do that to all data types.


Solution

  • int.TryParse will Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the operation succeeded; so what we can do is:

    if(int.TryParse(input, out value))
    {
     // proceed with your code
    } 
    else 
    {
     // show some message that the input is not valid
    }