Reputation: 2889
char x = (char)-1;
is valid in Java, but shows me the error (Overflow in constant value computation)
Should I use a different datatype in C#?
Upvotes: 2
Views: 1172
Reputation: 3247
Here's the definition of the C# char
type; it's a 16-bit Unicode character, same as in Java. If you are just looking for a 16-byte signed value, then you might want a short
.
For your reference, here is a list of the integral types available to you in C#.
You can also use an unchecked
statement such as unchecked { char x = (char)-1; }
; however, if it were me and I was, for instance, using -1
to represent an error value or some other marker, I would probably just use: char x = (char)0xFFFF;
which gives you the same result, and a way of checking for an invalid value, without needing to circumvent the type check.
Upvotes: 2
Reputation:
The error occurs because C# is smarter about literals ("constant computation"). In C# one could do...
int x = -1;
char c = (char)x;
int y = c;
// y is 0xffff, as per Java
However, do note that 0xFFFF is an invalid Unicode character :)
Happy coding.
Using unchecked
will also "work":
unchecked {
char x = (char)-1;
}
Upvotes: 4