Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
820 views
in Technique[技术] by (71.8m points)

vb.net - Why does Integer.TryParse set result to zero on failure?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...