I'm well aware that C# does not allow readonly fields in switch blocks, which is what this question addresses.
I'd like to understand why this is the case. Is it just an arbitrary language specification quirk, or is there a technical reason behind it, and if so, what is that technical reason?
Let me make it clear that I understand the difference between const and readonly, and I know that C# switch requires const values, or values known at compile time. To me, functionally, using a bunch of if..else if statements has the same outcome as using a switch statement, because whatever I can do with a switch statement I can achieve with an if as well, for example:
const int MyConstantValue = 10; int myCompareValue = 3; if(myCompareValue == MyConstantValue) { //... } else { //... } switch(myCompareValue) { case MyConstantValue: //... break; default: //... break; } Both of these constructs have the same outcome: the else or default block is executed, but the if can do it without compile time constants or known values. Why can an if do that where a switch cannot?
C#switches are modelled afterC/C++switches, which have the same constraint. The reason is for performance: A switch statement can be compiled into a very efficient "jump table", which wouldn't be possible if the cases were not known at compile time. So the answer is "to ensure that a switch statement is performant". Another point is that a switch statement has provably unique cases at compile time, but without constant cases that would not be provable at compile time.