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

Categories

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

c# - Strange behaviour of switch case with boolean value

My question is not about how to solve this error(I already solved it) but why is this error with boolean value.

My function is

private string NumberToString(int number, bool flag)
{
    string str;

    switch(flag)
    {
        case true: 
            str = number.ToString("00");
            break;
        case false:
            str = number.ToString("0000"); 
            break;
    }

    return str;
}

Error is Use of unassigned local variable 'str'. Bool can only take true or false. So it will populate str in either case. Then why this error?

Moreover this error is gone if along with true and false case I add a default case, but still what can a bool hold apart from true and false?

Why this strange behaviour with bool variable?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Writing a switch statement on a boolean variable seems kinda wasty to me. Why not use the conditional operator (?:):

private string NumberToString(int number, bool flag)
{
    return flag ? number.ToString("00") : number.ToString("0000"); 
}

The code seems a bit more concise and you don't need local variables.

But back to your question about why your code doesn't compile => it is because variables must always be assigned and this assignment should not happen inside conditional statements.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...