Jon Skeet said:
Ben Voigt said:
Jon said:
Jon Skeet [C# MVP] wrote:
Ranges are a possibility, so long as you can always check that a
value falls in only one range.
The compiler should simply generate a compile error if the ranges
overlap, like it does in Pascal. Then, only one range can apply. If
you'd allow overlapping ranges, the first match could win.
Yes - as I say, it's easy enough to tell for the built-in numeric
types. There may be other types where it's not so obvious though.
switch is only allowed on built in integral types and string anyway
Well yes, at the moment - but if we're considering possible changes, we
should consider the possibility of a more flexible switch.
It really goes back to what the point of switch is. If it's to use a
lookup to avoid a series of if/else statements for performance reasons,
I'm not sure its place is really deserved in C#.
If its purpose is to find one matching piece of code from a number of
options, there are ways it could be significantly more flexible.
As a newbie/amateur, I was disappointed with both case statements and enums
in C#; both are weaker than what I expected. (Almost everything else was way
better than I expected!).
As I understand it, I have to write
..
..
..
thisday = (int) dayofweek.Sunday
..
..
..
switch (thisday);
{case (int) dayofweek.Sunday: dostuff();break;
case (int) dayofweek.Monday: dostuff(); break;
..
..}
What I was hoping for was:
thisday=Sunday;
switch (thisday);
{case Sunday: dostuff(); break;
case Monday: dostuff(); break;}
Or even:
switch(thisday);
{case Sunday: dostuff(); break;
case Monday..Friday: dostuff(); break;
case Saturday: dostuff(); break;}
The continual need to cast back to integers reduces the readability of the
code.
Also, as someone else pointed out, the ++ operator for enums should loop. If
you have a statement:
thisday++;
and thisday was (int)dayofweek.Saturday, it returns what in reality is an
out-of-range enum (as there is no day of the week after Saturday).
What I think would have been more useful is thisday++ being equivalent to
thisday++; if (thisday>(int)dayofweek.Saturday) thisday=(int)
dayofweek.Sunday;
or even better
thisday++; if (thisday>Saturday) thisday=Sunday;
Its probably too late to change this and keep backwards compatibility, so I
think C# is stuck with ++ working for enums as it does for integers.
As somebody else pointed out, Pascal (now 30 years old) had user defined
types which work a little like enums, but in a more readable, maintainable
and intuitive form.