'Outputting a cast char onto the console in C♯
whenever I try to output a char that is higher than 127 I get a ?:
char erf = (char)144;
Console.WriteLine(erf);
But if I change the encoding to Unicode or UTF-8 It does not print the char at all. I know that char type's range is up to 65535 so It should work. Why does this happen? what type of default encoding does c# use if doing the following changes the output?
Console.OutputEncoding = System.Text.Encoding.Unicode;
Solution 1:[1]
Characters in C# are two-byte unicode. However, the console is not (depends on the OS version). So, your output is correct, the console just doesn't know how to render it. Try writing the characters to a file and viewing the contents in a text editor.
using (var fs = File.Open("c:\\temp\\test.txt",
FileMode.Create,
FileAccess.Write))
{
using (var sr = new StreamWriter(fs))
{
for (var i = 0; i < 255; i++)
{
sr.WriteLine($"{i:000} = {(char)i}");
}
}
}
Then you'll "see" output for all the characters. One of the reasons you don't see anything for characters 127-160 is because they are control characters (keys really), that don't have any output. Visible output resumes at 161.
For an excellent history of Unicode and characters in general, here's an article.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

