Author : MD TAREQ HASSAN | Updated : 2021/03/22

Char in CSharp

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 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