
.NET 1.1+Character Testing with the Char Structure
When developing software that may be deployed in many countries, it is important to be able to determine the type of a character according to the rules of the local culture and language. The Char structure provides methods to simplify this process.
Char Structure
The Char structure is used to represent a Unicode character, often referring to a single character from a string. Although it is a very simple type, it does include several methods that are very useful for testing the type of character that it holds. These static methods, each with the prefix "Is", can be used to detect whether a character is a letter, digit, symbol or element of white space. The methods understand the character categories for Unicode character sets, making them especially useful for software that will be deployed internationally.
Checking for Numeric and Alphanumeric Characters
In this article we will use some of the common methods of the Char structure to test characters. The results will vary according to the configuration of your operating system and preferred character set. To provide examples that will function correctly for all readers, we will create a simple Windows Forms application that displays characters in a list box. To begin, create a new Windows Forms project. Add a list box named "CharacterList" to the form. The sample code below can be used within the form's Load event.
IsDigit
A very common requirement when dealing with user input is to check if a character is a numeric digit. To perform this check, you can use the IsDigit method. The method has two overloaded versions. The first accepts the character to be tested as a parameter and returns a Boolean value.
To demonstrate, add the following code to the form's Load event handler. The code loops through several thousand possible characters and adds those that are categorised as numeric digits to the list box.
for (char c = (char)0; c < 65535; c++)
{
if (char.IsDigit(c)) CharacterList.Items.Add(c);
}
The outputted characters on a standard UK English configuration of Windows are shown below. Note that in addition to the digits 0 to 9, the method identifies non-English digit characters.

The second version of the IsDigit method can be used to test a single character within a string. In this case, the first argument is the string and the second is the index of the character to be checked. For example:
Console.WriteLine(char.IsDigit("ABC1",3)); // Outputs "True"
NB: All of the methods described in this article include both overloaded versions.
31 October 2009