131

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 3

198
(char)myint;

for example:

Console.WriteLine("(char)122 is {0}", (char)122);

yields:

(char)122 is z

Sign up to request clarification or add additional context in comments.

3 Comments

@nykwil I don't see anything wrong with gimel's answer.
@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.
@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.
78
int i = 65;
char c = Convert.ToChar(i);

1 Comment

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".
22

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.