79

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?

Community
  • 1
  • 1
Jinx
  • 807
  • 1
  • 6
  • 3

6 Answers6

150

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 = "==";
Grant Thomas
  • 44,454
  • 10
  • 85
  • 129
12

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;
}
Only Bolivian Here
  • 35,719
  • 63
  • 161
  • 257
2

You cannot treat == or || as chars, since they are not chars, but a sequence of chars.

You could make your switch...case work on strings instead.

driis
  • 161,458
  • 45
  • 265
  • 341
2

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 "&&": 
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
2

I faced the same issue. String.Replace('\\.','') is not valid statement and throws the same error. Thanks to C# we can use double quotes instead of single quotes and following works String.Replace("\\.","")

sud
  • 41
  • 2
1

I believe you can do this using a Unicode encoding, but I doubt this is what you really want.

The == is the unicode value 2A76 so I belive you can do this:

char c = '\u2A76';

I can't test this at the moment but I'd be interested to know if that works for you.

You will need to dig around for the others. Here is a unicode table if you want to look:

http://www.tamasoft.co.jp/en/general-info/unicode.html

Abe Miessler
  • 82,532
  • 99
  • 305
  • 486
  • 3
    U+2A76 is 'THREE CONSECUTIVE EQUALS SIGNS', not two (cf: http://www.fileformat.info/info/unicode/char/2a76). And it has nothing to do with the character sequence `==` as you would find it in a typical source file. – Joe White Apr 09 '11 at 18:33