when I'm trying to do
char c = (char)-1;
I'm getting compiler error stating that Constant value '-1' cannot be converted to a 'char'
which leads me thinking that this is an invalid conversion. But when I do this in runtime im getting back the character '\uffff'.
Out of curiosity what is that character and why does the compiler not like it?
C# uses Unicode UTF-16 to encode strings and chars. ffff in UTF-16 is a "non-character". When you prefix a string with \u it tells C# to treat the following characters as a Unicode code point. So here, your code point is ffff in hexadecimal or 65535 in decimal. char in C# is represented as a ushort under the hood, and there is an implicit conversion between the two. Here -1 exceeds the range of ushort and overflows to ushort.MaxValue which is 65535. (Integer arithmetic in C# does not throw exceptions on overflow by default. To enable this behavior use checked blocks.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With