Checking Palindromes in C#: Decide What Counts as the Same Text

Editorial illustration.

Originally published 23 June 2023; rewritten and reviewed on 15 October 2026.

Checking whether a word is a palindrome is one of those classic exercises that shows up in junior developer interviews across Kuala Lumpur and in every beginner C# course. On the surface, "level" or "katak" takes five lines of code. Give the same function "Kasur ini rusak" or "Madam, I'm Adam", though, and your assumptions about spaces, casing, and punctuation immediately decide whether the test passes or fails.

Before writing a loop, decide what “palindrome” means for your specific case.

Start with a clear two-pointer contract

Most beginners reach for LINQ and reverse the string:

bool isPalindrome = word.SequenceEqual(word.Reverse());

That works for quick throwaway scripts, but Reverse() allocates an iterator and buffers characters in memory just to compare them from both ends. In C#, a two-pointer scan over ReadOnlySpan<char> (or string) checks the same condition with zero heap allocations and stops the moment it hits a mismatch.

Here is a strict version that compares characters case-insensitively while keeping spaces and punctuation significant:

public static bool IsPalindrome(string value)
{
    ArgumentNullException.ThrowIfNull(value);

    int left = 0;
    int right = value.Length - 1;

    while (left < right)
    {
        if (char.ToUpperInvariant(value[left]) != char.ToUpperInvariant(value[right]))
        {
            return false;
        }

        left++;
        right--;
    }

    return true;
}

Under this contract, null throws an ArgumentNullException (fail fast rather than quietly returning false), an empty string "" and a single character "a" return true, and "Level" returns true. Meanwhile, "nurses run" returns false because the space at index 6 does not match 's' at index 3.

Skipping spaces and punctuation without extra allocations

If you want phrase-level palindromes—where "A man, a plan, a canal: Panama" should return true—you do not need Regex.Replace or a StringBuilder to build a cleaned copy of the string first. You can advance the two pointers past any non-alphanumeric character right inside the loop:

public static bool IsPhrasePalindrome(ReadOnlySpan<char> value)
{
    int left = 0;
    int right = value.Length - 1;

    while (left < right)
    {
        if (!char.IsLetterOrDigit(value[left]))
        {
            left++;
            continue;
        }

        if (!char.IsLetterOrDigit(value[right]))
        {
            right--;
            continue;
        }

        if (char.ToUpperInvariant(value[left]) != char.ToUpperInvariant(value[right]))
        {
            return false;
        }

        left++;
        right--;
    }

    return true;
}

Accepting ReadOnlySpan<char> lets callers pass a string directly or slice a substring with .AsSpan(start, length) without allocating a new string. It also keeps the normalisation rule—ignoring anything that is not a letter or digit—explicit in the code.

Where UTF-16 char indexing breaks down

C# string and char use UTF-16 code units. For ASCII and standard Latin letters, one char equals one visible character. For emojis or supplementary Unicode characters (anything outside the Basic Multilingual Plane), a single symbol takes two char values (a surrogate pair).

If someone passes "😀a😀" to the char-based loop above, value[0] is the high surrogate of the emoji and value[^1] is the low surrogate, so the comparison fails even though the text looks symmetrical. Similarly, accented characters decomposed into a base letter plus a combining mark won’t match a precomposed character unless you normalize the string first with value.Normalize(NormalizationForm.FormC).

For 99% of business logic, char indexing is fine. If you are building a text-processing tool that handles arbitrary Unicode or emojis, iterate using System.Text.Rune or StringInfo.GetTextElementEnumerator instead of raw char indices.

Test the boundaries, not just "racecar"

When writing unit tests for a helper like this, "racecar" and "hello" only cover the obvious path. Make sure your test cases include:

  • An empty string "" and single character "x"
  • Even-length ("noon") and odd-length ("civic") words
  • Mixed casing ("KaTaK")
  • A mismatch right in the middle ("abca" or "abccba" vs "abcdba")
  • Whitespace and punctuation ("Madam, I'm Adam" vs " ")
  • null input to verify the guard clause

Even a tiny algorithm becomes dependable once the edge cases are spelled out in tests and two developers reading the method can immediately agree on what it returns.