Convert int to a char in C#
This post will discuss how to convert an int to a char in C#.
1. Explicit conversion (casts)
C# doesn’t support implicit conversion from type ‘int’ to ‘char’ since the conversion is type-unsafe and risks potential data loss. However, we can do an explicit conversion using the cast operator (). A cast informs the compiler that the conversion is intentional.
The following program casts the value of an integer to a Char value.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; public class Example { public static void Main() { int val = 65; char ch = (char)val; Console.WriteLine("{0} converts to '{1}'", val, ch); } } /* Output: 65 converts to 'A' */ |
2. Using Convert.ToChar() method
We can use the Convert.ToChar() method to convert an integer to its equivalent Unicode character. The following example converts the value of an integer to a char value. The program throws an OverflowException if it is outside the range of the char data type (0-65535).
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
using System; public class Example { public static void Main() { int val = 65; try { char ch = Convert.ToChar(val); Console.WriteLine("{0} converts to '{1}'", val, ch); } catch (OverflowException) { Console.WriteLine("{0} is outside the range of the char datatype", val); } } } /* Output: 65 converts to 'A' */ |
3. Using Char.ConvertFromUtf32() method
We can use the Char.ConvertFromUtf32() method to convert the specified Unicode code point into a UTF-16 encoded string.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; public class Example { public static void Main() { int val = 65; char ch = Char.ConvertFromUtf32(val)[0]; Console.WriteLine("{0} converts to '{1}'", val, ch); } } /* Output: 65 converts to 'A' */ |
That’s all about converting int to a char in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)