Question:
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";
}
In a switch block I can use const variables, but if I use readonly variables I get an error
A constant value is expected
Why is that, aren't readonly variables defined at compile time?
Answer:
readonly
means that the field must be initialized in the constructor and subsequent modification of this field is prohibited. Those. it is a guarantee that once the field is initialized in the constructor, it can no longer be changed in other parts of the class. But that doesn't make it a compile-time entity – no, it's protected from reinitialization, but it's not const.
Read more in the documentation