The Essential .NET Data Types

  • 8/15/2011

The Char Data Type

The Char data type stores a character in Unicode format (more about this topic later in the chapter) using 16 bits, or 2 bytes. Unlike the String type, the Char data type is a value type. The following brief overview gives you more details:

.NET data type: System.Char

Represents: A single character

Range: 0–65.535, so that Unicode characters can be displayed

Type literal: c

Memory requirements: 2 bytes

Delegation to the processor: Yes

CLS-compliant: Yes

Description: Char values are often used in arrays, because in many cases it’s more practical to process individual characters than it is to process strings. Like any other data type, you can define Char arrays with constants (you’ll see an example shortly). The following section on strings contains examples on how to use Char arrays instead of strings for character-by-character processing.

Even if Char is saved internally as an unsigned 16-bit value, and is therefore like a Short, you cannot implicitly convert a Char into a numeric type. In addition to the possibility described in the Online Help, however, you can use not only the functions AscW and ChrW to convert a Char to a numeric data type, and vice versa, but also the Convert class, for example:

'Normal declaration and definition
Dim locChar As Char
locChar = "1"c
Dim locInteger As Integer = Convert.ToInt32(locChar)
Console.WriteLine("The value of '{0}' is {1}", locChar, locInteger)

When you run this example, it displays the following output:

The value of '1' is 49

You can also use the functions Chr and Asc, but they work only for non-Unicode characters (ASCII 0–255). Due to various internal scope checks, they also have an enormous overhead; therefore, they are nowhere near as fast as AscW, ChrW (which are the fastest, because a direct and internal type conversion of Char into Integer, and vice versa, takes place) or the Convert class (which has the advantage of being easily understood by non-Visual Basic developers as well).

Declaration and Sample Assignment (also as Array):

'Normal declaration and definition
Dim locChar As Char
locChar = "K"c

'Define and declare a Char array with constants.
Dim locCharArray() As Char = {"A"c, "B"c, "C"c}

'Convert a Char array into string.
Dim locStringFromCharArray As String = New String(locCharArray)

'Convert a string into a Char array.
'Of course that's also possible with a string variable.
locCharArray = "This is a string".ToCharArray