Subscribe

RSS Feed (xml)

C# Characters

In C#, characters are not 8-bit quantities like they are in many other computer languages, such as C++. Instead, C# uses a 16-bit character type called Unicode. Unicode defines a character set that is large enough to represent all of the characters found in all human languages. Although many languages, such as English, French, or German, use relatively small alphabets, some languages, such as Chinese, use very large character sets that cannot be represented using just 8 bits. To accommodate the character sets of all languages, 16-bit values are required. Thus, in C#, char is an unsigned 16-bit type having a range of 0 to 65,535. The standard 8-bit ASCII character set is a subset of Unicode and ranges from 0 to 127. Thus, the ASCII characters are still valid C# characters.

A character variable can be assigned a value by enclosing the character inside single quotes. For example, this assigns X to the variable ch:

char ch;
ch = 'X';

You can output a char value using a WriteLine( ) statement. For example, this line outputs the value in ch:

Console.WriteLine("This is ch: " + ch);

Although char is defined by C# as an integer type, it cannot be freely mixed with integers in all cases. This is because there are no automatic type conversions from integer to char. For example, the following fragment is invalid:

char ch;

ch = 10; // error, won't work

The reason the preceding code will not work is that 10 is an integer value, and it won’t automatically convert to a char. If you attempt to compile this code, you will see an error message. To make the assignment legal, you would need to employ a cast, which is described later in this chapter.

No comments:

Post a Comment

LocalsAdda.com-Variety In Web World

Fun Mail - Fun in the Mail