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?
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With