Редагувати

Поділитися через


char (C# reference)

The char type keyword is an alias for the .NET System.Char structure type that represents a Unicode UTF-16 character.

Type Range Size .NET type
char U+0000 to U+FFFF 16 bit System.Char

The default value of the char type is \0, that is, U+0000.

The char type supports comparison, equality, increment, and decrement operators. Moreover, for char operands, arithmetic and bitwise logical operators perform an operation on the corresponding character codes and produce the result of the int type.

The string type represents text as a sequence of char values.

Literals

You can specify a char value with:

  • a character literal.
  • a Unicode escape sequence, which is \u followed by the four-symbol hexadecimal representation of a character code.
  • a hexadecimal escape sequence, which is \x followed by the hexadecimal representation of a character code.
var chars = new[]
{
    'j',
    '\u006A',
    '\x006A',
    (char)106,
};
Console.WriteLine(string.Join(" ", chars));  // output: j j j j

As the preceding example shows, you can also cast the value of a character code into the corresponding char value.

Note

In the case of a Unicode escape sequence, you must specify all four hexadecimal digits. That is, \u006A is a valid escape sequence, while \u06A and \u6A are not valid.

In the case of a hexadecimal escape sequence, you can omit the leading zeros. That is, the \x006A, \x06A, and \x6A escape sequences are valid and correspond to the same character.

Conversions

The char type is implicitly convertible to the following integral types: ushort, int, uint, long, and ulong. It's also implicitly convertible to the built-in floating-point numeric types: float, double, and decimal. It's explicitly convertible to sbyte, byte, and short integral types.

There are no implicit conversions from other types to the char type. However, any integral or floating-point numeric type is explicitly convertible to char.

C# language specification

For more information, see the Integral types section of the C# language specification.

See also