Author : MD TAREQ HASSAN | Updated : 2021/03/22
Char in CSharp
- The char type keyword is an alias for the ` System.Char` structure type that represents a Unicode UTF-16 character
- The default value of the char type is
\0
, (that isU+0000
) - The
string
type represents text as a sequence of char values
Char variable
char ch = 'x';
var ch = 'j'; // char literal
var ch = '\u006A'; // 'j', unicode escape sequence, which is \u followed by the four-symbol hexadecimal representation of a character code
var ch = '\x006A'; // 'j', a hexadecimal escape sequence, which is \x followed by the hexadecimal representation of a character code.
var ch = (char)106; // 'j', from int value
Char Struct
About Char Conversion
- Char is implicitly convertible to 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
Char to String
// interpolation
char ch = 'x';
string str = $"{ch}";
// string constructor
string str = new string(new char[] { 'x' });
// ToString()
char ch = 'x';
var str = ch.ToString();
// when char is int val
var val = 120;
string str = Char.ConvertFromUtf32(val); // x
String to Char
string str = "Hello";
char[] characters = str.ToCharArray();
// readonly indexer of string
var str = "hovermind";
var firstChar = str[0]; // h
Chat to int
var ch = 'x';
var val = (int)ch;
Console.WriteLine(val); // 120
Int to Char
int val = 120;
char ch = Convert.ToChar(val);
Console.WriteLine(ch); // x