C# char.IsLetterOrDigit Method

Use the char.IsLetterOrDigit method. Test the performance of this method.
Char.IsLetterOrDigit. The char.IsLetterOrDigit method tests a char. It determines if the char is a letter or digit. We run this method through a simple test to demonstrate its use. We present some example input and output.Char
Example. Let's get started with a simple Console program that uses an input string containing various characters. We loop over these characters with the foreach-loop construct, and pass each character to the char.IsLetterOrDigit method.

Then: We display a character to indicate whether the input character was considered a letter or digit.

Info: The letters and digits, but not the spaces, hyphen and other punctuation received a true value from IsLetterOrDigit.

True, False

Note: The method's output is equivalent to the expression (char.IsLetter(letter) || char.IsDigit(letter)).

C# program that uses char.IsLetterOrDigit using System; class Program { static void Main() { string input = "dot net perls 867-5309?!"; Console.WriteLine(input); foreach (char letter in input) { bool isLetterOrDigit = char.IsLetterOrDigit(letter); if (isLetterOrDigit) { Console.Write('^'); } else { Console.Write(' '); } } Console.WriteLine(); } } Output dot net perls 867-5309?! ^^^ ^^^ ^^^^^ ^^^ ^^^^
Performance. The performance of character-testing methods is often improved with a lookup table. This reduces the cost of the method to a single array access. Most often, though, char.IsLetterOrDigit is not something that needs to be optimized.
Frequency analysis can yield improvement. If most of your characters are digits, testing first to see if the character is a digit would be fastest. In my limited testing, char.IsLetterOrDigit does not test for digits first.

So: Its performance on a digit is worse than (char.IsDigit(letter) || char.IsLetter(letter)).

Info: The char.IsLetterOrDigit method seemed to take somewhat less than 3 nanoseconds on my computer.

Summary. We looked at the behavior of the char.IsLetterOrDigit method from the .NET Framework and noted its performance. Largely a convenience method over using char.IsLetter and char.IsDigit, this method can yield a simplification.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Dot Net Perls