You assign it if x is 0-9. What would you expect from this if x were 123? Although you may know that only values ββbetween 0 and 9 will be passed, the compiler does not do this - so it needs to consider what will happen differently.
One way to avoid this is to have a default case in your switch statement, which you can use to throw an exception if the value is not in the expected range:
switch (x) { case 0: alphaChar = 'A'; break; case 1: alphaChar = 'B'; break; case 2: alphaChar = 'C'; break; case 3: alphaChar = 'D'; break; case 4: alphaChar = 'E'; break; case 5: alphaChar = 'F'; break; case 6: alphaChar = 'G'; break; case 7: alphaChar = 'H'; break; case 8: alphaChar = 'I'; break; case 9: alphaChar = 'J'; break; default: throw new ArgumentOutOfRangeException(); }
Here's a slightly simpler alternative that completely removes the switch statement:
if (x < 0 || x > 9) { throw new ArgumentOutOfRangeException(); } char alphaChar = (char)('A' + x);
Please note that when using arithmetic you need to be careful. In Java and C #, the basic representation is guaranteed to be Unicode, which makes life a lot easier. I believe this is good for such things (and hexagoring / formatting), but when you go into more exotic scenarios, it fails. Again, this is true for many code simplification methods ... if they are applied inappropriately, you get a mess.
Jon skeet
source share