C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Info: The literals are immutable and cannot be changed, but the variables that store those values simply denote storage locations.
Here: The const char in the program uses value semantics and cannot be reassigned. It is a named literal.
constString LiteralEscaped: Character literals are escaped with the "\" character, and this is how you can represent the newline "\n".
Environment.NewLineFinally: We print the literal values to the screen with Console.WriteLine—the backslash is no longer present.
ConsoleC# program that uses character literals
using System;
class Program
{
static char _literal5 = 'e'; // Static character literal.
const char _literal6 = '#'; // Constant character literal.
static void Main()
{
//
// Shows some example character literals.
// ... Also shows a local constant character literal.
// ... Then prints them.
//
char literal1 = 'A';
char literal2 = 'b';
char literal3 = '\\';
const char literal4 = '_';
Console.WriteLine(literal1);
Console.WriteLine(literal2);
Console.WriteLine(literal3);
Console.WriteLine(literal4);
Console.WriteLine(_literal5);
Console.WriteLine(_literal6);
}
}
Output
A
b
\
_
e
#
And: For a newcomer to C# this program could be a challenge to debug (we need double backslashes in the literal).
C# program that shows char syntax errors
class Program
{
static void Main()
{
char backslash = '\';
}
}
Output
Error CS1010
Newline in constant
Error CS1012
Too many characters in character literal
Error CS1002
; expected
Further: A const char can only be used as a value, not a variable. It is a way of referring to a character literal by a name.