Palindrome string test function in C#

Verifying that a string of characters is a palindrome in C#

Recently an acquaintance shared with me what must be a common technical exercise – write code to detect whether a sequence of characters is a palindrome. That is determining if a word, phrase, a sentence or a number can be read exactly the same backwards. So, if all the text was reversed, with the last letter or digit becoming the first and ignoring all spaces and separators, then it should remain the same, with all symbols in the same positions. Letter case is not important. So, Abba is a palindrome, because it’ll remain the same word if it’s reversed. Same with "madam".

As the exercise isn’t as quite as demanding as some other famous coding challenges involving string processing, such as finding anagrams (which may require writing a trie algorithm), the entertaining factor then becomes making the code as succinct as possible with C# syntax, without unnecessary verbosity and/or operations. Below is my take on string palindrome test in C#:

public static bool IsPalindrome(string input)
{
    if (input == null)
        throw new ArgumentNullException(nameof(input));

    var lastIndex = input.Length-1;
    var index = 0;
    var spaces = 0;
            
    while (index <= lastIndex)
    {
        if (char.IsWhiteSpace(input[index]))
            index++;
        else if (char.IsWhiteSpace(input[lastIndex]))
            lastIndex --;
        else if (char.ToLower(input[index++]) != char.ToLower(input[lastIndex--]))
            return false;
        else continue;

        spaces++;
    };

    //Should an empty string be considered a palindrome?
    //Probably not, because most dictionaries would define it as
    //a word, number, phrase, or otherwise a sequence of characters,
    //whereas space (and separators) - to be ignored.
    if (spaces == input.Length)
        return false;

    return true;
}





Information Error Confirmation required