TheDeveloperBlog.com


C# char.IsDigit Method, Test Number Chars

Char.IsDigit. The char.IsDigit method checks character values. It determines if a character in the string is a digit character—meaning it is part of an Arabic number—in the range 0-9. It is useful in certain parsing, scanning or sorting algorithms.


Example. First, the char.IsDigit method is a static method on the System.Char struct, which is aliased to the char keyword in the C# programming language. It returns a Boolean value, which tells you whether the character is a digit character.

Bool Method

Also: It contains some logic for globalization, which checks for Latin characters.

C# program that tests for digits

using System;

class Program
{
    static void Main()
    {
	string test = "R2D2/C3P0";
	foreach (char value in test)
	{
	    bool digit = char.IsDigit(value);
	    Console.Write(value);
	    Console.Write(' ');
	    Console.WriteLine(digit);
	}
    }

    /// <summary>
    /// Returns whether the char is a digit char.
    /// Taken from inside the char.IsDigit method.
    /// </summary>
    public static bool IsCharDigit(char c)
    {
	return ((c >= '0') && (c <= '9'));
    }
}

Output

R False
2 True
D False
2 True
/ False
C False
3 True
P False
0 True

The program defines the Main entry point and an input string containing the names of two characters from the Star Wars movies. The string contains four digits: 2, 2, 3, and 0. In the output, IsDigit returned True only for those values.


Unicode. As Raymond Chen at Microsoft notes, the IsDigit method has some interesting behavior on non-Latin numbers, meaning certain rare Unicode characters. This is mainly a security concern when using it in input validation.

Therefore: Using the custom IsCharDigit method in the above code is safer for simple tasks.

Also: The logic in IsCharDigit is actually taken directly from the main part of char.IsDigit.

Char.IsDigit matches: MSDN Blogs

Summary. The char.IsDigit method works in normal situations with the digits 0-9. We used it in a foreach-loop. And we noted that it has an unusual behavior that complicates its behavior. This could lead to unexpected behavior.

Tip: You can extract the character-testing logic for more predictable behavior and slightly better performance.