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

荒凉一梦 提交于 2019-12-17 20:51:33

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/1078512/why-does-integer-tryparse-set-result-to-zero-on-failure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!