Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Cheat sheets: all cheat sheets

    Working with bool, char, and string in Everyday C#

    Learn how C# boolean, character, and string types behave in real code, including comparisons, text handling, and common pitfalls that matter in production.

    Learning outcome

    By the end of this note, you should be able to choose between bool, char, and string with confidence, use them correctly in conditions and text processing, and avoid the mistakes that cause brittle validation and subtle bugs.

    Intuition

    These three types look simple, but they solve different problems:

    • bool represents a yes/no state.
    • char represents one UTF-16 code unit, often a single displayed character for basic text.
    • string represents a sequence of characters, which is how you store names, messages, identifiers, and user input.

    In real applications, you constantly combine them. For example, a login form may store a bool for whether the password is valid, inspect char values when validating input, and use string for the full username or email address.

    A practical rule is: use the smallest type that correctly models the data. If the value can only be true or false, use bool. If you need one UTF-16 code unit, use char. If you need text, use string.

    Deep dive

    bool

    bool has only two values: true and false. It is the natural result of comparisons and logical checks.

    Use booleans for state and decisions, not for encoding magic numbers or strings like "yes" and "no". That keeps code readable and safer.

    char

    char stores one UTF-16 code unit and is written in single quotes.

    A common beginner mistake is treating char as if it always means a full user-perceived character. Most everyday ASCII letters fit well, but some Unicode characters may require more than one code unit. For professional code, remember that char is a building block for text, not always the full story of what a human sees.

    string

    string stores text and is written in double quotes.

    Strings are immutable: an existing string's contents cannot be changed. Reassigning a variable changes which string it refers to. That matters when building text repeatedly. For small amounts of text, simple concatenation is fine. For larger or repeated composition, prefer helpers like interpolation or StringBuilder when appropriate.

    Comparing text and characters

    • Use == for value comparison with string and char in everyday code.
    • Avoid reference-equality assumptions for strings.
    • Use culture-aware or ordinal comparisons intentionally when correctness depends on user language or protocol rules.

    Reading user input safely

    Console input often arrives as text, even when you need a yes/no decision. Validate the input before inspecting a character. The example below returns early for null, empty, or whitespace-only input, so it never indexes those values. A check performed after userName[0] cannot protect that earlier access.

    If you combine checks with &&, put the safe guard on the left and the character access on the right. The right operand is skipped when the left is false; & evaluates both operands. See the conditional AND reference for the evaluation rule.

    Failure modes

    1. Using string where bool is appropriate: this makes validation harder and encourages invalid states.
    2. Confusing char and string: 'A' and "A" are different types and are not interchangeable.
    3. Assuming every visible character is one char: Unicode text can be more complex than a single code unit.
    4. Comparing strings without thinking about comparison rules: protocol text, keys, and identifiers often need ordinal comparison; user-facing text may need culture-aware handling.
    5. Ignoring immutability: repeated string concatenation in loops can hurt performance.
    6. Checking too late: reject missing input before indexing. Empty strings have no element at index 0.

    Interview drill with answers

    1. How do char and string differ? A char holds one UTF-16 code unit, such as 'A'. A string holds text, such as "Ada", and may contain many code units.
    2. When should a field use bool? Use it for a two-state decision such as whether a password check passed. A string would also allow accidental values such as "maybe".
    3. What does string immutability mean? An existing string's contents remain unchanged. Assigning a different string to one variable does not rewrite a string that other variables still reference.
    4. Why is one visible character not always one char? Some Unicode text uses multiple code units. Code-unit indexing alone is therefore insufficient for every human-visible character operation.
    5. Why must validation happen before indexing? An empty string has no element at index 0. The guard must run first, as in the program below; a later check cannot undo an exception.

    Revision checklist

    • I can declare and initialize bool, char, and string values.
    • I know that true/false are bool, single quotes are for char, and double quotes are for string.
    • I can use boolean expressions in if statements.
    • I understand that strings are immutable.
    • I can explain why Unicode can make character processing more advanced than basic ASCII.
    • I compare text intentionally instead of by accident.
    • I reject null or empty input before indexing a string.

    A small validation example

    The runnable program below combines text, a character, and a Boolean decision. Its rule is deliberately narrow: accept nonblank text whose first UTF-16 code unit is uppercase. This is a teaching rule, not a complete policy for human names or production usernames. It does not trim input: " Mina" fails the rule because its first code unit is a space.

    Code walkthrough

    • string? userName can hold text or null; nullable annotations are enabled for this example.
    • string.IsNullOrWhiteSpace(userName) is checked before any index access. The early return ends the program for missing or blank input.
    • Only the remaining path evaluates userName[0] and stores that code unit in char firstLetter.
    • char.IsUpper(firstLetter) returns the bool printed as Valid. "Mina" passes this demonstration rule; "mina" does not.
    • The program prints a first-letter line only on the guarded, nonblank path.

    For the broader curriculum, this note sits in the types and expressions module and supports later topics like control flow, validation, and input handling. The same ideas will reappear in collection keys, parsing, testing, and API design.

    Fact-check notes

    • bool, char, and string are core C# types and remain valid in .NET 10 / C# 14.
    • string is immutable in .NET.
    • char represents a UTF-16 code unit, not always a full Unicode scalar or user-perceived grapheme.
    • String comparison behavior depends on the comparison method used; choice of ordinal vs culture-aware comparison is version-stable but important to apply intentionally.

    Executable code examples

    Validating text with bool, char, and string

    Copy this complete program into Program.cs. Change the userName initializer to explore the cases listed below.

    Program.cs

    C#Runs
    #nullable enable
    using System;
    
    string? userName = "Mina";
    Console.WriteLine($"Name: {userName ?? "<null>"}");
    
    if (string.IsNullOrWhiteSpace(userName))
    {
        Console.WriteLine("Valid: False");
        return;
    }
    
    char firstLetter = userName[0];
    bool isValidName = char.IsUpper(firstLetter);
    
    Console.WriteLine($"First letter: {firstLetter}");
    Console.WriteLine($"Valid: {isValidName}");

    Expected results

    • "Mina": Name: Mina, First letter: M, then Valid: True.
    • "mina": Name: mina, First letter: m, then Valid: False.
    • null, "", or " ": the name line, then Valid: False; no first-letter line and no index access.
    • " Mina": the leading space is preserved and inspected; Valid: False.

    Sources and further reading