开发者

out parameter - why does it not work

The following is a failing unittest explaining a bug I found today:

    [TestMet开发者_JAVA技巧hod]
    public void WFT()
    {
        string configDebug = "false";
        bool configDebugEnabled = bool.TryParse(configDebug, out configDebugEnabled);

        Assert.AreEqual(false, configDebugEnabled);
    }

This is how to make the test go from red to green:

    [TestMethod]
    public void WFT()
    {
        string configDebug = "false";
        bool configDebugEnabled;
        bool.TryParse(configDebug, out configDebugEnabled);

        Assert.AreEqual(true, configDebugEnabled);
    }

I haven't been able to find the paragraph explaining this in the C# specification but there's most likely a decent explanation to this behaviour. Can anybody explain to me why the first test is failing?


Because the TryParse method always returns true if the parsing succeeds and false if not. In the first case the parsing succeeds so configDebugEnabled = true which is not what you assert.

Btw the second test will also fail unless you write string configDebug = "true".


The reason it's failing is that you are using the same variable to store the success or failure of the TryParse itself. As the parsing succeeds (the string does translate to a boolean value) you are overwriting the returned value of false with true.


Because the return parameter from bool.TryParse is "true" if it was able to do the conversion or not -- the return parameter is not the result of the conversion.

You're overwriting the result (in the out parameter) with the return from bool.TryParse() itself.


In this line

bool configDebugEnabled = bool.TryParse(configDebug, out configDebugEnabled);

the variable configDebugEnabled is first set to false (as a result of the parse), but immediately after is set to true (because TryParse returns true if the parse was successful). Why not just use bool.Parse?


Why would you expect the out parameter to return true?


bool.TryParse returns a bool to specify whether the parse was successful. You are assigning that result to the same bool variable that you are putting in the out parameter.

You need a separate variable to test for the success of the function.


You assign the variable configDebugEnabled from both the return value and from the out parameter. If the variable is false at the end you don't know if parsing failed or the parsed value was false.

do it this way:

bool IsOk;
bool configDebugEnabled = bool.TryParse(configDebug, out IsOk);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜