ZetCode

C# char type

last modified October 18, 2026

In this article we show how to work with the char type in C#.

A string in C# is a sequence of UTF-16 code units. The System.Char type represents one such code unit. The char keyword is an alias for the System.Char type.

.NET uses the Char structure to represent characters with the UTF-16 encoding. The value of a Char object is its 16-bit numeric (ordinal) value. A char is an unsigned 16-bit integer type that has a character interpretation, so it converts to and from int and takes part in arithmetic.

type range size .NET type
char U+0000 to U+FFFF 16 bit System.Char

The default value of the char type is \0 (U+0000).

Note: A char is not necessarily equivalent to a single Unicode character. Characters outside the first 65,536 code points, such as emoji, need two char values (a surrogate pair), and what a reader sees as one character can consist of several code points. The last sections of this tutorial deal with this.

In C# code, a character can be represented by

C# char simple example

The following is a simple example with the char type.

Program.cs
char a = 'f';
Console.WriteLine(a);

Console.WriteLine(a.GetType());
Console.WriteLine(typeof(char));

Console.WriteLine((int)char.MaxValue);
Console.WriteLine((int)char.MinValue);
Console.WriteLine(sizeof(char));
Console.WriteLine((int)default(char));
Console.WriteLine(char.MaxValue == '￿');

We define a char variable and show its type, its size, and its smallest and largest value.

$ dotnet run
f
System.Char
System.Char
65535
0
2
0
True

C# char literals and escape sequences

Char values are enclosed in single quotes. Strings use double quotes.

Program.cs
Console.OutputEncoding = System.Text.Encoding.UTF8;

char c = 'л';
Console.WriteLine(c);

char c2 = 'л';
Console.WriteLine(c2);

char c3 = '\x43b';
Console.WriteLine(c3);

char c4 = (char)1083;
Console.WriteLine(c4);

Console.WriteLine(c == c2 && c2 == c3 && c3 == c4);

// special characters
Console.WriteLine('\'');
Console.WriteLine('\\');
Console.WriteLine((int)'\n');
Console.WriteLine((int)'\t');
Console.WriteLine((int)'\0');
Console.WriteLine('é');

The example represents the same character in four ways: with a character literal, a Unicode escape sequence, a hexadecimal escape sequence, and a cast of a number. Then it prints a few special characters.

char c3 = '\x43b';

The hexadecimal escape sequence takes up to four digits, so '\x43b' is U+043B. Digits that follow the intended ones are swallowed in strings, as in "\x43bad", which is the reason to prefer \u.

Console.WriteLine('\'');
Console.WriteLine('\\');
Console.WriteLine((int)'\n');

The single quote and the backslash must be escaped in a character literal. The other common escapes are \n (line feed, code 10), \t (tab, 9), \r, and \0.

$ dotnet run
л
л
л
л
True
'
\
10
9
0
é

C# array of chars

To convert a char array to a string, we pass the array to the constructor of string. To convert the string to a char array, we call the ToCharArray method.

Program.cs
char[] vals = { 'a', 'n', ' ', 'o', 'l', 'd', ' ', 'f', 'a', 'l', 'c', 'o', 'n' };
Console.WriteLine(vals);
Console.WriteLine(vals.GetType());

Console.WriteLine("------------------------");

string msg = new(vals);
Console.WriteLine(msg);
Console.WriteLine(msg.GetType());

Console.WriteLine("------------------------");

char[] vals2 = msg.ToCharArray();
Console.WriteLine(vals2);
Console.WriteLine(vals2.GetType());

// reverse a string through a char array
Array.Reverse(vals2);
Console.WriteLine(new string(vals2));

// build a string from a part of the array
Console.WriteLine(new string(vals, 3, 3));

In the example, we convert a char array into a string and the string back into a char array. Then we reverse the string with Array.Reverse.

Console.WriteLine(vals);

Console.WriteLine has an overload for char[] that prints the characters as text, not the name of the type.

Console.WriteLine(new string(vals, 3, 3));

The constructor can take a part of the array: the start index and the length.

$ dotnet run
an old falcon
System.Char[]
------------------------
an old falcon
System.String
------------------------
an old falcon
System.Char[]
noclaf dlo na
old

Reversing by chars breaks text with surrogate pairs and combining characters; see the last sections.

C# iterate over string elements

A C# string is a sequence of char elements, which can be enumerated.

Program.cs
string msg = "an old falcon";

foreach (var e in msg)
{
    Console.Write($"{e} ");
}

Console.WriteLine("\n-----------------------------");

foreach (var e in msg)
{
    Console.Write($"{(int)e} ");
}

Console.WriteLine("\n-----------------------------");

byte[] data = { 97, 110, 32, 111, 108, 100, 32, 102, 97, 108, 99, 111, 110 };

foreach (var e in data)
{
    char c = (char)e;
    Console.Write($"{c} ");
}

Console.WriteLine();

// a cast to byte truncates characters above 255
string text = "žltý kôň";
foreach (var e in text)
{
    Console.Write($"{e}:{(int)e}->{(byte)e} ");
}

Console.WriteLine();

The example loops over a string and outputs each char separately. It converts the chars to their numeric codes, and the codes back to chars.

foreach (var e in msg)
{
    Console.Write($"{(int)e} ");
}

We cast each element to an int and get its code.

foreach (var e in text)
{
    Console.Write($"{e}:{(int)e}->{(byte)e} ");
}

A cast to byte keeps only the lowest eight bits. For ASCII text it is fine, but "ž" (382) becomes 126 and "ň" (328) becomes 72. To get the bytes of a string, use an Encoding, such as Encoding.UTF8.GetBytes, which also handles the characters above 255 correctly.

$ dotnet run
a n   o l d   f a l c o n
-----------------------------
97 110 32 111 108 100 32 102 97 108 99 111 110
-----------------------------
a n   o l d   f a l c o n
ž:382->126 l:108->108 t:116->116 ý:253->253  :32->32 k:107->107 ô:244->244 ň:328->72

C# char.GetUnicodeCategory

The char.GetUnicodeCategory method categorizes a Unicode character into a group identified by one of the UnicodeCategory values. The categories are the basis of the methods like IsLetter and IsPunctuation.

Program.cs
string msg = "There are 22 apples in the basket.";

foreach (var e in msg.Take(12))
{
    var category = char.GetUnicodeCategory(e);
    Console.WriteLine($"'{e}' - {category}");
}

Console.WriteLine("--");

foreach (var e in "€$+_-(é9¼")
{
    Console.WriteLine($"{e} - {char.GetUnicodeCategory(e)}");
}

In the example, we show the Unicode category of the first twelve characters of a string, and of several characters from different groups.

$ dotnet run
'T' - UppercaseLetter
'h' - LowercaseLetter
'e' - LowercaseLetter
'r' - LowercaseLetter
'e' - LowercaseLetter
' ' - SpaceSeparator
'a' - LowercaseLetter
'r' - LowercaseLetter
'e' - LowercaseLetter
' ' - SpaceSeparator
'2' - DecimalDigitNumber
'2' - DecimalDigitNumber
--
€ - CurrencySymbol
$ - CurrencySymbol
+ - MathSymbol
_ - ConnectorPunctuation
- - DashPunctuation
( - OpenPunctuation
é - LowercaseLetter
9 - DecimalDigitNumber
¼ - OtherNumber

The underscore is a punctuation character, not a symbol, and the vulgar fraction ¼ is a number but not a decimal digit.

C# char classification methods

The char type has static methods to test a character: IsLetter, IsDigit, IsLetterOrDigit, IsUpper, IsLower, IsWhiteSpace, IsPunctuation, IsSymbol, and IsControl. They know about all Unicode scripts. Since .NET 7, there are also the IsAscii... variants, which accept only the ASCII characters.

Program.cs
string text = "Hello, World 42! žltý kôň\t.";

int letters = text.Count(char.IsLetter);
int digits = text.Count(char.IsDigit);
int upper = text.Count(char.IsUpper);
int spaces = text.Count(char.IsWhiteSpace);
int punctuation = text.Count(char.IsPunctuation);

Console.WriteLine($"letters: {letters}, digits: {digits}, upper: {upper}, whitespace: {spaces}, punctuation: {punctuation}");

Console.WriteLine(char.IsLetterOrDigit('_'));
Console.WriteLine(char.IsControl('\n'));
Console.WriteLine(char.IsSymbol('+'));
Console.WriteLine(char.IsAscii('é'));

// the same methods exist with a string and an index
Console.WriteLine(char.IsDigit("a1", 1));

// the digit characters of other scripts
Console.WriteLine(char.IsDigit('٣'));                 // Arabic-Indic digit three
Console.WriteLine(char.GetNumericValue('٣'));
Console.WriteLine(char.GetNumericValue('¼'));
Console.WriteLine(char.IsAsciiDigit('٣'));

The program counts the kinds of characters in a text and tries some special cases.

int letters = text.Count(char.IsLetter);

The method group is passed directly to LINQ's Count. The text contains accented letters, which IsLetter counts as letters.

Console.WriteLine(char.IsDigit('٣'));
Console.WriteLine(char.GetNumericValue('٣'));
Console.WriteLine(char.IsAsciiDigit('٣'));

IsDigit is true for the digits of any script, here the Arabic-Indic digit three. GetNumericValue returns its value as a double, and it also handles the fractions: ¼ is 0.25. When validating input such as an identifier or a number that is parsed later, IsAsciiDigit is the right test.

$ dotnet run
letters: 17, digits: 2, upper: 2, whitespace: 5, punctuation: 3
False
True
True
False
True
True
3
0.25
False

C# char conversion and arithmetic

A char converts implicitly to int, so arithmetic works, but the result is an int and needs a cast back to a char. Characters are compared by their codes.

Program.cs
Console.WriteLine(char.ToUpper('a'));
Console.WriteLine(char.ToLower('Ž'));
Console.WriteLine(char.ToUpperInvariant('ž'));
Console.WriteLine(char.ConvertFromUtf32(0x1F600));
Console.WriteLine(char.ConvertToUtf32("😀", 0));

// arithmetic: a char is promoted to int
char a = 'a';
Console.WriteLine(a + 1);
Console.WriteLine((char)(a + 1));
a++;
Console.WriteLine(a);
Console.WriteLine('z' - 'a');
Console.WriteLine('7' - '0');

// the letters of the alphabet
Console.WriteLine(string.Concat(Enumerable.Range('a', 26).Select(i => (char)i)));

// comparison is by code
Console.WriteLine('a' < 'b');
Console.WriteLine('Z' < 'a');
Console.WriteLine('a'.CompareTo('c'));
Console.WriteLine(char.Parse("x"));
Console.WriteLine(char.TryParse("xy", out _));

The example shows the conversions and the arithmetic.

Console.WriteLine(a + 1);
Console.WriteLine((char)(a + 1));
a++;

The expression a + 1 is the int 98; with the cast, it is the letter "b". The increment operator keeps the type, so a++ gives "b".

Console.WriteLine('7' - '0');

Subtracting '0' converts a digit character to its numeric value, a classic idiom. It is valid only for the ASCII digits 0 to 9.

Console.WriteLine(char.ConvertFromUtf32(0x1F600));
Console.WriteLine(char.ConvertToUtf32("😀", 0));

For code points above U+FFFF, which do not fit into a single char, the ConvertFromUtf32 method returns a string and ConvertToUtf32 returns the code point of the pair at a given index.

$ dotnet run
A
ž
Ž
😀
128512
98
b
b
25
7
abcdefghijklmnopqrstuvwxyz
True
True
-2
x
False

C# char Caesar cipher

A small practical example: the Caesar cipher shifts every letter by a number of positions and keeps the other characters as they are.

Program.cs
// a Caesar cipher: shifts letters, keeps everything else
string Encrypt(string text, int shift)
{
    return string.Create(text.Length, (text, shift), static (span, state) =>
    {
        for (int i = 0; i < state.text.Length; i++)
        {
            char c = state.text[i];

            if (char.IsAsciiLetterLower(c))
            {
                span[i] = (char)('a' + (c - 'a' + state.shift + 26) % 26);
            }
            else if (char.IsAsciiLetterUpper(c))
            {
                span[i] = (char)('A' + (c - 'A' + state.shift + 26) % 26);
            }
            else
            {
                span[i] = c;
            }
        }
    });
}

string secret = Encrypt("Hello, World!", 3);
Console.WriteLine(secret);
Console.WriteLine(Encrypt(secret, -3));

// counting character frequencies
var freq = "mississippi".GroupBy(c => c).OrderByDescending(g => g.Count()).ThenBy(g => g.Key);
foreach (var g in freq)
{
    Console.WriteLine($"{g.Key}: {g.Count()}");
}

// hexadecimal digit
Console.WriteLine(Uri.IsHexDigit('f'));
Console.WriteLine(Convert.ToInt32('f'.ToString(), 16));
Console.WriteLine(char.IsAsciiHexDigit('g'));

The program encrypts and decrypts a text, and counts the characters of a word.

span[i] = (char)('a' + (c - 'a' + state.shift + 26) % 26);

We subtract 'a' to get the index of the letter, add the shift, wrap around the 26 letters of the alphabet with the modulo operator, and add 'a' back. Adding 26 before the modulo handles negative shifts, since the % operator of C# can return negative values. The IsAsciiLetterLower and IsAsciiLetterUpper methods make sure we shift only the ASCII letters. The result is built with string.Create, which fills the new string through a span.

var freq = "mississippi".GroupBy(c => c).OrderByDescending(g => g.Count()).ThenBy(g => g.Key);

LINQ groups the characters, which gives the frequencies.

$ dotnet run
Khoor, Zruog!
Hello, World!
i: 4
s: 4
p: 2
m: 1
True
15
False

The last three lines test a hexadecimal digit and convert one to its value. Note that a Caesar cipher is not encryption in any real sense; it is a teaching example.

C# char and surrogate pairs

Unicode has more than a million code points, but a char has 16 bits. Code points above U+FFFF, such as emoji and many historic scripts and rare Chinese characters, are stored as two char values, a high and a low surrogate. A single char cannot hold them. This is a source of bugs in code that treats chars as characters.

Program.cs
using System.Text;
using System.Globalization;

Console.OutputEncoding = Encoding.UTF8;

string smile = "😀";                          // U+1F600 is outside the 16-bit range
Console.WriteLine(smile.Length);              // two char values: a surrogate pair
Console.WriteLine(char.IsHighSurrogate(smile[0]));
Console.WriteLine(char.IsLowSurrogate(smile[1]));
Console.WriteLine(char.IsSurrogatePair(smile, 0));
Console.WriteLine($"{(int)smile[0]:X4} {(int)smile[1]:X4}");

// char cannot hold it
// char c = '😀';      // error CS1012: too many characters in a character literal

// a Rune is a Unicode scalar value
Rune r = new Rune(0x1F600);
Console.WriteLine($"{r} {r.Value:X} {r.Utf16SequenceLength} chars, {r.Utf8SequenceLength} UTF-8 bytes");

foreach (Rune rune in "a😀é".EnumerateRunes())
{
    Console.WriteLine($"U+{rune.Value:X4} {rune}");
}

// "é" can be one char or two: e + combining acute accent
string e1 = "é";
string e2 = "é";
Console.WriteLine($"{e1} {e2} {e1.Length} {e2.Length} {e1 == e2} {e1.Normalize() == e2.Normalize()}");

// text elements (what a reader sees as one character)
string family = "👨‍👩‍👧";
Console.WriteLine($"{family.Length} chars, {family.EnumerateRunes().Count()} runes, {new StringInfo(family).LengthInTextElements} text element");

The program examines the emoji U+1F600, a rune, and combining characters.

Console.WriteLine(smile.Length);
Console.WriteLine(char.IsSurrogatePair(smile, 0));

The string with one visible character has a length of two. The IsHighSurrogate, IsLowSurrogate, and IsSurrogatePair methods recognize the halves. Cutting a string between the two halves, for example with Substring or Truncate, produces an invalid string.

Rune r = new Rune(0x1F600);
foreach (Rune rune in "a😀é".EnumerateRunes())

The Rune structure (namespace System.Text) represents a Unicode scalar value, a whole code point, whatever the number of chars. It knows the length of the code point in UTF-16 and in UTF-8, and has methods similar to those of char. EnumerateRunes iterates over the code points of a string.

string e1 = "é";
string e2 = "é";

Even a rune is not always what the user sees as a character. "é" can be one code point, or an "e" followed by a combining acute accent. The two strings look identical but are different, until we normalize them with Normalize. The family emoji is five runes (three people joined by two zero-width joiners), eight chars, and one text element. StringInfo in System.Globalization counts and enumerates the text elements. For the user-visible length of a text, such as for limiting a field, count text elements.

$ dotnet run
2
True
True
True
D83D DE00
😀 1F600 2 chars, 4 UTF-8 bytes
U+0061 a
U+1F600 😀
U+00E9 é
é é 1 2 False True
8 chars, 5 runes, 1 text element

Source

char type

In this article we have worked with the char type in C#.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.