Strange behaviour of switch case with boolean value

前端 未结 5 1703
-上瘾入骨i
-上瘾入骨i 2020-12-19 19:19

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 NumberT         


        
5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-19 19:44

    Well, there's been good explanation for causes of this issue, but there is one more solution to the problem, which was not mentioned. Just put default instead of second case:

        private string NumberToString(int number, bool flag)
        {
            string str;
    
            switch (flag)
            {
                case true:
                    str = number.ToString("00");
                    break;
                default:
                    str = number.ToString("0000");
                    break;
            }
    
            return str;
        }
    

    It leaves compiler with no further thoughts about flag variable value as we always assign a default value in our switch statement.

    Also consider if-else statement equivalent solution:

        private string NumberToString(int number, bool flag)
        {
            string str;
    
            if (flag)
                str = number.ToString("00");
            else
                str = number.ToString("0000");
    
            return str;
        }
    

    I am not particularly fond of 'one-liners' (one line solutions), as they lack extendability and moreover - readability, but as the last resort just use ternary operators like this:

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

    While I am at it - consider using extension method + defaulting boolean to false, for example:

    public static class intExtensions
    {
        public static string NumberToString(this int number, bool flag = false)
        {
            return flag ? number.ToString("00") : number.ToString("0000");
        }
    }
    

    and then in main class:

            int intVal = 56;
            string strVal1 = intVal.NumberToString(true);
            string strVal2 = intVal.NumberToString();
    

提交回复
热议问题