I’m not looking for any specific code examples, but could someone explain why I can’t get the ‘-1’ to function at the end of this switch statement? It keeps saying that there are “too many literals” for type char. (something close to that). Would I have to convert this to another type?
Thanks for any help, and please, just explain without giving code. I would love to learn this by hands on experiance 😀
Convert 7 char passed from ProcessInput() by reference to upper case
Use switch statement to translate char into their corresponding digits (case statement for each digit and each valid uppercase letter)
**TROUBLES WITH THIS PART***Write default case that returns error code (-1) for invalid letters
If no invalide letters, return 0
static void ToDigit(ref char digit)
{
digit = Char.ToUpper(digit);
char result;
switch (digit)
{
case '0': result = '0';
break;
case '1': result = '1';
break;
case '2':
case 'A':
case 'B':
case 'C': result = '2';
break;
case '3':
case 'D':
case 'E':
case 'F': result = '3';
break;
case '4':
case 'G':
case 'H':
case 'I': result = '4';
break;
case '5':
case 'J':
case 'K':
case 'L': result = '5';
break;
case '6':
case 'M':
case 'N':
case 'O': result = '6';
break;
case '7':
case 'P':
case 'Q':
case 'R':
case 'S': result = '7';
break;
case '8':
case 'T':
case 'U':
case 'V': result = '8';
break;
case '9':
case 'W':
case 'X':
case 'Y':
case 'Z': result = '9';
break;
//Says I can't enter -1 as char "too many characters in character literal
default: result = 'e';
break;
}
digit = result;
}
A
charis, as the name implies, a single character. A group of characters all “strung together” is called astringin C#.If you want the integer value -1 as a char then you can do that by saying
unchecked((char)(-1))(*) but you should be aware that this is a very bad idea. I assume that this is your assignment:That’s not how things work in C#; returning a “bad” value to indicate failure is a “worst practice” — it is characteristic of 1970’s style C programming, but not C#.
The right thing to do here is to either (1) have no error cases at all; if there is no upper case form then just don’t transform the character at all, or (2) throw an exception if the input is bad, or (3) return a nullable char, and return null for the “bad” value.
Also, the fact that your program takes a
refrather than returning a value is deeply suspicious. AToDigitmethod should be computing and returning result not mutating a variable.I think whatever course of study you are taking was written decades ago, originally targetted a different language entirely, and was never updated to use modern best practices. I would seriously question the value of such materials.
Always say
(T)(-1)in C# when casting the constant-1to the typeT, rather than(T)-1. If you write it the latter way, the reader can get confused about whether you mean “subtract one from T” or “cast negative one to type T”.