Working with the Char Type
Char is a value type that contains a single Unicode character. While chars have a numeric
value from hexadecimal 0x0000 through 0xFFFF, they are not directly numerically usable
without explicit type casting.
Literal values are assigned to char variables using single quotes. The literal can be a
simple, single letter, or an escape sequence (for more on escape sequences, see the next
section). Here are two examples:
char chr = 'P'; // contains capital P
char pi = '\u03A0’; // contains capital Pi
The char data type is related to the string data type: A string can be constructed from
and converted into an array of characters—but string and char are two distinct types.
Suppose you have a string defined like this:
string str = "rotfl";
You can retrieve a character of the string using the string’s indexer. For example,
the following statement
char chr = str[1];
stores the character ‘o’ in the variable chr. But you cannot set a character in the
string with a statement like
str[1] = 'a';
because the indexer property of the String class is read-only. (Actually, one would expect this in any
case, because the string instance is immutable.)
If you use the Object Browser to have a look at the String class, you’ll see that its indexer property,
declared as this[int], has a get accessor, but no set accessor.
|