Switch use readonly variables in case



  • I have the following code

    static void Main(string[] args)
            {
                string value = "value1";
                // switch с const переменными работает
                switch(value)
                {
                    case ConstVariable.VALUE1:
                        Console.WriteLine(ConstVariable.VALUE1);
                        break;
                    case ConstVariable.VALUE2:
                        Console.WriteLine(ConstVariable.VALUE2);
                        break;
                    case ConstVariable.VALUE3:
                        Console.WriteLine(ConstVariable.VALUE3);
                        break;
                }
    
            // ЗДЕСЬ ОШИБКА!!! switch c readonly переменными не работает
            switch (value)
            {
                case ReadOnlyVariable.VALUE1:
                    Console.WriteLine(ConstVariable.VALUE1);
                    break;
                case ReadOnlyVariable.VALUE2:
                    Console.WriteLine(ConstVariable.VALUE2);
                    break;
                case ReadOnlyVariable.VALUE3:
                    Console.WriteLine(ConstVariable.VALUE3);
                    break;
            }
        }
    
    
        static class ReadOnlyVariable
        {
            public static readonly string VALUE1 = "value1";
    
            public static readonly string VALUE2 = "value2";
    
            public static readonly string VALUE3 = "value3";
    
        }
    
        static class ConstVariable
        {
            public const string VALUE1 = "value1";
    
            public const string VALUE2 = "value2";
    
            public const string VALUE3 = "value3";
    
        }
    

    I can use variable const in the block, but if I use readonly, I get a mistake.

    A constant value is expected

    Why is it that the variables readonly are not defined at the compilation stage?



  • readonly means that the field must be initialized in the designer and the subsequent modification of the field is prohibited. This is a guarantee that once the field is initiated in the design, it can no longer be changed in other parts of the class. But it doesn't really make it a compilation time - no, it's protected from reinitiation, but it's not a constant.

    Details https://msdn.microsoft.com/ru-ru/library/acdd6hb7.aspx




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2