Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the reason behind not being able to use readonly fields in switch blocks?

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?

like image 654
ldam Avatar asked Jan 23 '17 09:01

ldam


1 Answers

The reason for this is that C# switches are modelled after C/C++ switches, which have the same constraint.

There are two reasons for this constraint:

  • 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.
  • Correctness: A switch statement has provably unique cases at compile time, but without constant cases that would not be provable at compile time.
like image 179
Matthew Watson Avatar answered Oct 02 '22 18:10

Matthew Watson