Summary: in this tutorial, you’ll learn about the C# char type and how to use it to declare variables that hold a single character.
Introduction to the C# char type
C# uses the char keyword to represent the character type. A variable of the char type can hold a single character. The char is an alias for the .NET System.Char type.
C# char literals
C# provides you with three ways to represent a character literal:
- A character literal.
- A Unicode escape sequence.
- A hexadecimal escape sequence.
All three character literals are surrounded by single quotes.
For example, the following declares a variable that holds the character ‘a’:
char key = 'a';Code language: C# (cs)A Unicode escape sequence starts with \u and is followed by a four-symbol hexadecimal representation of the character code. For example:
char c = '\u002B'Code language: C# (cs)A hexadecimal escape sequence starts with \x and the hexadecimal representation of the character code:
char c = '\x002C'Code language: C# (cs)Operators
The char type support equality, comparison, increment, and decrement operators.
For example, the following compares two character variables and returns True because they are the same character 'a':
char c1 = 'a',
c2 = 'a';
bool result = c1 == c2;
Console.WriteLine(result);Code language: C# (cs)Output:
TrueCode language: C# (cs)If you assign the character 'b' to the c2 variable, the result of the equality test will be false:
char c1 = 'a',
c2 = 'b';
bool result = c1 == c2;
Console.WriteLine(result);Code language: C# (cs)Output:
FalseCode language: C# (cs)Similar to the equality operator, you can use other comparison operators like <, >, <=, and => to compare two characters:
char c1 = 'a',
c2 = 'b';
bool result = c1 < c2;
Console.WriteLine(result);Code language: C# (cs)Output:
TrueCode language: C# (cs)Summary
- Use the
charkeyword to represent the character type that holds a single character.