Exercises in this lecture   Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home   

Exercise solution:
Exploring the type Char


The program given below demonstrates the three static methods IsDigit, IsPunctuation, and IsSeparator. It also shows that the casting (type conversion) of a character to the numeric type short reveals the code position (code point) of a character. You get the same result if you cast to longer numeric integer types.

using System;
using System.Globalization;

class CharDemo{

  public static void Main(){

    Console.WriteLine(Char.IsDigit('.'));
    Console.WriteLine(Char.IsDigit('5'));
    Console.WriteLine(Char.IsDigit(' '));
    Console.WriteLine();

    Console.WriteLine(Char.IsPunctuation('.'));
    Console.WriteLine(Char.IsPunctuation('5'));
    Console.WriteLine(Char.IsPunctuation(' '));
    Console.WriteLine();

    Console.WriteLine(Char.IsSeparator('.'));
    Console.WriteLine(Char.IsSeparator('5'));
    Console.WriteLine(Char.IsSeparator(' '));
    Console.WriteLine();

    Console.WriteLine("ch1: {0}", (short)'A');
    Console.WriteLine("ch1: {0}", (short)'Æ');
  }                  

}

The output of the program is

False
True
False

True
False
False

False
False
True

ch1: 65
ch1: 198

The method GetNumericValue is intended to be used on characters that represent digits in decimal numbers. As an example, Char.GetNumericValue('2') is equal to the number 2 in type double. If applied on non-digit characters, GetNumericValue returns -1.0. Notice that Char.GetNumericValue('a') is -1.0; In contexts where we work with hexadecimal numbers it would have been useful if Char.GetNumericValue('a') returned 10.