tags:

views:

911

answers:

2

My understanding of the Integer.TryParse() function was that it tried to parse an integer from the passed in string and if the parse failed the result integer would remain as it did before.

I have an integer with a default value of -1 which I would like to remain at -1 if the parse fails. However the Integer.TryParse() function on failing to parse is changing this default value to zero.

Dim defaultValue As Integer = -1
Dim parseSuccess As Boolean = Integer.TryParse("", defaultValue)
Debug.Print("defaultValue {0}", defaultValue)
Debug.Print("parseSuccess {0}", parseSuccess)

My expectation is that the code snippet above should output:

defaultValue -1
parseSuccess False

However instead it outputs:

defaultValue 0
parseSuccess False

Is my understanding correct?

+2  A: 

You are correct, TryParse uses 0 if it fails. (MSDN says this quite clearly) But you could check paseSuccess and return your default value if this is what you want to.

bernhardrusch
+6  A: 

It's an out parameter, which means it must be set by the method (unless it throws an exception) - the method can't see what the original value was.

The alternative would have been to make it a ref parameter and only set it on success, but that would mean forcing callers to initialize the variable first even if they didn't want this behaviour.

You can write your own utility method though:

public bool TryParseInt32(string text, ref int value)
{
    int tmp;
    if (int.TryParse(text, out tmp))
    {
        value = tmp;
        return true;
    }
    else
    {
        return false; // Leave "value" as it was
    }
}
Jon Skeet