kaalus
kaalus

Reputation: 4574

In C# can casting a Char to Int32 produce a negative value?

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

Upvotes: 6

Views: 1709

Answers (5)

Renatas M.
Renatas M.

Reputation: 11820

char can be inplicitly converted to ushort and ushort range is 0 to 65,535 so its always positive

Upvotes: 0

Fischermaen
Fischermaen

Reputation: 12468

See Microsoft's documentation

There you can see, that Char is a 16 bit value in the range of U+0000 to U+ffff. If you cast it to a Int32, there should be no negative value.

Upvotes: 0

Ahmet Kakıcı
Ahmet Kakıcı

Reputation: 6404

Each 16-bit value ranges from hexadecimal 0x0000 through 0xFFFF and is stored in a Char structure.

Char Structure - MSDN

Upvotes: 2

Oded
Oded

Reputation: 499132

Since the range of char is U+0000 to U+ffff, then a cast to an Int32 will always be positive.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1502166

It's guaranteed to be non-negative.

char is an unsigned 16-bit value.

From section 4.1.5 of the C# 4 spec:

The char type represents unsigned 16-bit integers with values between 0 and 65535. The set of possible values for the char type corresponds to the Unicode character set. Although char has the same representation as ushort, not all operations permitted on one type are permitted on the other.

Upvotes: 12

Related Questions