Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 182 ยท Variables and Types

bool and char

Learn the C# bool and char types - true and false, logical operators, char as a UTF-16 code unit, escape sequences, char.IsLetter and friends, surrogate pairs and char arithmetic.

Two small types do a surprising amount of work in every program. A bool holds a yes-or-no answer and drives every if, loop and filter. A char holds a single character, the building block of every string. They look trivial, but each has details worth knowing: bool has no implicit link to numbers (unlike C or JavaScript), and char is not "one letter on the screen" but one 16-bit unit of UTF-16 text, which matters the moment you meet emoji.

By the end of this lesson you will write conditions confidently, escape special characters, classify characters with the char helper methods, do arithmetic on characters (a classic way to build a Caesar cipher) and understand why one emoji can be two char values. Strings, which are sequences of char, get their own lesson: Strings.

bool: true or false

bool is the C# keyword for System.Boolean. It has exactly two values, the literals true and false. You get a bool from comparisons (==, !=, <, >, <=, >=) and combine booleans with logical operators:

Operator Name Meaning
! NOT flips the value
&& AND (short-circuit) true only if both sides are true
|| OR (short-circuit) true if at least one side is true
& and | AND / OR (non-short-circuit) always evaluate both sides
^ XOR true if exactly one side is true
C# Booleans and logical operators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice that true prints as True. If you build JSON or a config file by hand, remember to lowercase it. Also notice bool.TryParse("yes", ...) returns false and leaves parsed as false: only the words "true" and "false" (case-insensitive, surrounding whitespace allowed) are accepted.

No truthiness

In JavaScript, Python and C, "empty" or "zero" values count as false. C# is strict: a condition must be a real bool. if (count) or if (name) is a compile error. This catches a whole family of bugs, including the classic if (x = 5) assignment typo, which C# rejects because x = 5 is an int, not a bool.

C# Conditions must be bool (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The compiler reports error CS0029: Cannot implicitly convert type 'int' to 'bool'. The fix is to say what you mean: if (count != 0), or if (count > 0).

Short-circuiting

&& and || stop as soon as the answer is known. In a && b, if a is false the right side is never evaluated. This is not just an optimization; it is how you write safe guards:

C# Short-circuit evaluation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Use && and || almost always. The single-character & and | on booleans are rarely what you want, except when both sides must run for their side effects (even that is usually a sign of code that should be split up).

Booleans in memory

A bool takes one byte, not one bit, so an array of one million bool uses about 1 MB. When you need millions of flags, a BitArray or manual bit manipulation (see Operators) is far denser. A nullable bool? has three states (true, false, null); we cover that in Nullable Value Types.

Name booleans like questions: isReady, hasItems, canRetry. A line such as if (isReady && !hasErrors) then reads like English. Avoid comparing with literals: write if (isReady), never if (isReady == true).

char: one UTF-16 code unit

A char (System.Char) is a 16-bit unsigned value that represents one UTF-16 code unit. Literals use single quotes: 'A', '7', 'รฉ', 'โ‚ฌ'. Double quotes make a string, a different type, so char c = "A"; is an error.

Underneath, a char is a number, and you can convert between the two:

C# A char is a number in disguise

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The last line surprises beginners: 'Z' < 'a' is true because the code for Z is 90 and for a is 97. Ordinal comparison is not alphabetical order. For human-friendly sorting you compare strings with a culture or comparer (see Strings).

Escape sequences

Some characters cannot be typed directly in a literal: a newline, a tab, the quote that ends the literal. C# uses a backslash escape for them:

Escape Character
\n newline (line feed)
\r carriage return
\t tab
\0 the null character (code 0)
\\ a backslash
\' single quote
\" double quote
\a, \b, \f, \v alert, backspace, form feed, vertical tab
\e escape (code 27), added in C# 13
\uXXXX the code unit with four hex digits
\UXXXXXXXX a code point with eight hex digits (strings only)
\xH to \xHHHH one to four hex digits (easy to get wrong; prefer \u)
C# Escape sequences in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Unlike C, a C# string does not end at \0; the length is stored separately, so "a\0b" has three characters. For file paths, Windows backslashes are easier to read in a verbatim string, which you will meet in Raw, Verbatim and UTF-8 String Literals.

Classifying and converting characters

The static methods on char answer questions about a character in a way that understands all of Unicode, not just English:

  • char.IsLetter, char.IsDigit, char.IsLetterOrDigit
  • char.IsUpper, char.IsLower
  • char.IsWhiteSpace, char.IsPunctuation, char.IsSymbol
  • char.ToUpper, char.ToLower (culture-sensitive) and char.ToUpperInvariant, char.ToLowerInvariant (always the same)
  • char.GetNumericValue and char.IsAscii* helpers (IsAsciiDigit, IsAsciiLetter, ...)

Prefer char.IsAsciiDigit over char.IsDigit when you parse numbers: IsDigit also accepts digits from other scripts (such as Arabic-Indic digits), which int.Parse-style code may not handle the way you expect.

C# Counting character kinds

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Arithmetic with characters

Because a char is a number, you can add and subtract. The result of char + int is an int, so you cast back to char when you want a character again. Two classic tricks: turn a digit character into its value with c - '0', and shift letters through the alphabet.

C# Digit values and a Caesar cipher

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The + 26 in Shift guards against negative numbers: % in C# keeps the sign of the left operand, so (-1) % 26 is -1, not 25. The same code is used to encrypt (+3) and decrypt (-3). Remember this is a toy: a Caesar cipher is trivially breakable and never suitable for real secrets.

Surrogate pairs: when one character is two chars

Unicode defines over a million code points, but a char has only 65,536 values. Code points above U+FFFF (most emoji, rare CJK characters, ancient scripts) are stored as a surrogate pair: two char values, a high surrogate followed by a low surrogate. Neither half is a character on its own.

That has a practical consequence: string.Length counts char values (UTF-16 code units), not what a person sees as characters.

C# Emoji are two chars

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

System.Text.Rune (a struct) represents one complete Unicode code point, and string.EnumerateRunes() walks a string code point by code point. Even a rune is not always "one visible character": an emoji with a skin tone, or e followed by a combining accent, is several code points that display as one. Those user-perceived characters are called grapheme clusters, covered in Unicode, Rune and Encoding.

For ordinary text processing in English and most European languages, looping over char works fine. Reach for Rune or grapheme-aware code only when you handle user-entered text that may contain emoji, flags or combining marks (reversing, truncating, counting "letters" in a display).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which of these compiles in C#?

    A comparison produces a bool. C# has no truthiness, so an int is never a condition and 0 is never false. Single quotes are for a single char, so 'abc' is also an error.
  2. 2. In a && Check(), when is Check() called?

    && short-circuits: if the left side is false the whole expression is false and the right side is skipped. That is what makes x != null && x.Length > 0 safe.
  3. 3. What is the type of the expression 'a' + 1?

    Arithmetic on a char promotes it to int, so 'a' + 1 is the int 98. Cast it back with (char)('a' + 1) to get 'b'.
  4. 4. What does "\U0001F431".Length return, where the string holds one cat emoji?

    The emoji lies above U+FFFF, so UTF-16 stores it as a surrogate pair of two char values. Length counts chars (code units), not visible symbols.
  5. 5. How do you turn the character '7' into the integer 7?

    (int)'7' gives the code 55. Digits are consecutive in Unicode, so subtracting the code of '0' (48) leaves the digit's value, 7.

Summary

  • bool is true or false only. Conditions must be bool; there is no truthiness, so write count != 0.
  • && and || short-circuit; use them for guards like x != null && x.Length > 0. bool prints as True/False.
  • char is a 16-bit UTF-16 code unit written in single quotes; it converts to and from numbers, and 'Z' < 'a' compares codes, not alphabet order.
  • Escape sequences (\n, \t, \\, \", \u20AC) write characters you cannot type directly. C# strings are not null-terminated.
  • Use char.IsLetter, IsDigit, IsWhiteSpace, ToUpperInvariant and the IsAscii* helpers to classify text; c - '0' converts a digit to its value.
  • char + int is an int; cast back to char when needed.
  • Emoji and other code points above U+FFFF take two char values (a surrogate pair); use Rune when you need whole code points.

Next: Type Conversion and Casting