What is the best way to convert an Int value to the corresponding Char in Utf16, given that the Int is in the range of valid values?
Asked
Active
Viewed 3.6e+01k times
4 Answers
187
(char)myint;
for example:
Console.WriteLine("(char)122 is {0}", (char)122);
yields:
(char)122 is z

gimel
- 83,368
- 10
- 76
- 104
-
13@nykwil I don't see anything wrong with gimel's answer. – Tom Lint Apr 02 '15 at 07:47
-
17@nykwil - That is misinformation. `Console.WriteLine((char)49 == '1');` Will give **True**. As will `char c = (char)49; string s = "1two3"; Console.WriteLine(c == s[0]);` Using this cast is perfectly fine. Your explanation does not provide a valid example of it not working. Furthermore, `Console.WriteLine((char)49 == 1);` is *false* which essentially makes your comment baseless. – Travis J Aug 11 '15 at 18:03
-
@nykwil and future readers, in C#, '1' would be a literal char whereas just 1 would be a literal int, i.e. they are two different types. When a cast, like (char)49, is used, the result is a char, which 1 is not, but '1' is. – Rob Feb 12 '23 at 16:11
77
int i = 65;
char c = Convert.ToChar(i);

Corey Trager
- 22,649
- 18
- 83
- 121
-
51Convert.ToChar eventually performs an explicit conversion as "(char)value", where "value" is your int value. Before doing so, it checks to ensure "value" is in the range 0 to 0xffff, and throws an OverflowException if it is not. The extra method call, value/boundary checks, and OverflowException may be useful, but if not, the performance will be better if you just use "(char)value". – Triynko Apr 14 '11 at 17:52
19
Although not exactly answering the question as formulated, but if you need or can take the end result as string you can also use
string s = Char.ConvertFromUtf32(56);
which will give you surrogate UTF-16 pairs if needed, protecting you if you are out side of the BMP.

Humberto Gomes
- 139
- 1
- 10

Boaz
- 25,331
- 21
- 69
- 77
1
gimel's answer in PowerShell seems to be:
> [char]65
A
> [char]48
0
> [char]97
a

JohnL4
- 1,086
- 9
- 18