In C #, can casting Char in Int32 cause a negative value?

Or is it always guaranteed to be positive for all possible characters?

+5
source share
5 answers

It is guaranteed to be non-negative.

char is a 16-bit unsigned value.

From section 4.1.5 of the C # 4 specification:

The type charis unsigned 16-bit integers with values ​​from 0 to 65535. The set of possible values ​​for the type charcorresponds to the Unicode character set. Although it charhas the same idea as ushort, not all operations allowed for one type are allowed on another.

+10
source

char U + 0000 U + ffff, Int32 .

+2

16- 0x0000 0xFFFF Char.

Char Structure - MSDN

+2
source

See Microsoft documentation

Here you can see that Char is a 16-bit value in the range from U + 0000 to U + ffff. If you pass it Int32, there should not be a negative value.

0
source

charcan be implicitly converted to ushortand ushortrange 0 to 65,535, therefore its always positive

0
source

All Articles