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?
3 Answers
(char)myint;
for example:
Console.WriteLine("(char)122 is {0}", (char)122);
yields:
(char)122 is z
3 Comments
Tom Lint
@nykwil I don't see anything wrong with gimel's answer.
Travis J
@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.Rob
@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.
int i = 65;
char c = Convert.ToChar(i);
1 Comment
Triynko
Convert.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".
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.