I'm struggling with a piece of code and getting the error:
Too many characters in character literal error
Using C# and switch statement to iterate through a string buffer and reading tokens, but getting the error in this line:
case '&&':
case '||':
case '==':
How can I keep the ==
and &&
as a char?
A char can hold a single character only, a character literal is a single character in single quote, i.e. '&' - if you have more characters than one you want to use a string, for that you have to use double quotes: case "&&": Follow this answer to receive notifications.
A character literal contains a sequence of characters or escape sequences enclosed in single quotation mark symbols, for example 'c' . A character literal may be prefixed with the letter L, for example L'c' . A character literal without the L prefix is an ordinary character literal or a narrow character literal.
C# includes escaping character \ (backslash) before these special characters to include in a string. Use backslash \ before double quotes and some special characters such as \,\n,\r,\t, etc. to include it in a string.
This is because, in C#, single quotes (''
) denote (or encapsulate) a single character, whereas double quotes (""
) are used for a string of characters. For example:
var myChar = '='; var myString = "==";
Here's an example:
char myChar = '|'; string myString = "||";
Chars are delimited by single quotes, and strings by double quotes.
The good news is C# switch statements work with strings!
switch (mytoken) { case "==": //Something here. break; default: //Handle when no token is found. break; }
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