The default character set under Visual Basic is Unicode. Therefore, when a variable is declared as type Char, Visual Basic creates a two-byte value, since, by default, all characters in the Unicode character set require two bytes. Visual Basic supports the declaration of a character value in three ways. Placing a $c$ following a literal string informs the compiler that the value should be treated as a character, or the Chr and Chrw methods can be used. The following code snippet shows that all three of these options work similarly, with the difference between the Chr and Chrw methods being the range of available valid input values. The Chrw method allows for a broader range of values based on wide character input.
Dim chrLtr_a As Char = "a"c
Dim chrAsc_a As Char = Chr(97)
Dim chrAsc_b as Char = ChrW(98)
To convert characters into a string suitable for an ASCII interface, the runtime library needs to validate each character's value to ensure that it is within a valid range. This could have a performance impact for certain serial arrays. Fortunately, Visual Basic supports the Byte value type. This type contains a value between 0 and 255 that exactly matches the range of the ASCII character set. When interfacing with a system that uses ASCII, it is best to use a Byte array. The runtime knows there is no need to perform a Unicode-to-ASCII conversion for a Byte array, so the interface between the systems operates significantly faster.
In Visual Basic, the Byte value type expects a numeric value. Thus, to assign the letter "a" to a Byte, you must use the appropriate character code. One option to get the numeric value of a letter is to use the Asc method, as shown here:
Dim bytLtrA as Byte = Asc("a")
Was this article helpful?