Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Too many characters in character literal error"

Tags:

c#

char

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?

like image 863
Jinx Avatar asked Apr 09 '11 17:04

Jinx


People also ask

What does too many characters in character literal?

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.

What do you mean by character literal?

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.

How do you escape C#?

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.


2 Answers

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 = "=="; 
like image 118
Grant Thomas Avatar answered Sep 20 '22 17:09

Grant Thomas


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; } 
like image 37
Only Bolivian Here Avatar answered Sep 21 '22 17:09

Only Bolivian Here