I have this code:
switch (currentLetter)
{
case 'A': return 'B';
case 'B': return 'C';
case 'C': return 'D';
case 'D': return 'E';
case 'E': return 'F';
case 'F': return 'G';
case 'G': return 'H';
case 'a': return 'b';
case 'b': return 'c';
case 'c': return 'd';
case 'd': return 'e';
case 'e': return 'f';
case 'f': return 'g';
case 'g': return 'h';
}
I thought of many ways to change it but I’m not sure on which to choose. I could replace all the returns with (char)(currentLetter + 1), use if statements with ASCII values to determine range and then do (char)(currentLetter + 1), use Enumerable.Range.Contains and then see if the value is within the range, replace the switch with an if, etc.
This code will not be repeated anywhere else and I’m not sure if this isn’t the best way of doing it since it’s very clear to the reader of the code to what’s going on and they don’t have to think of character codes, arithmetic, etc. Also, there will never be any more characters to add to the case statements so it won’t get unwieldy.
Not sure if I should leave it as is or change it.
Use
If you need to perform a range test
It is visible immediately, that the next letter in the alphabet is returned without inspecting a long list of cases. Also it’s less prone to errors.
UPDATE:
charis considered to be a numeric type in C# and can implicitly be converted to other numeric types that are at least 16 bit wide. You can even apply the increment and decrement operators on them. Therefore a shorter solution with no casting exists:Note: This changes the original value of
currentLetter, but sincecharis not a reference type, this should not be a problem, ifcurrentLetterwas a method parameter. Also, the pre-increment operator must be used, as the old value would be returned with the post-increment operator!