Dismissile
Dismissile

Reputation: 33071

Is casting char to int a safe operation in C#?

Given the following code:

string source = "Some Unicode String";
foreach( char value in source ) {

    int y = (int)value;

}

Is it possible that the cast from char to int could fail (and under what circumstances)?

Upvotes: 5

Views: 667

Answers (2)

jorgebg
jorgebg

Reputation: 6600

A conversion from char to int will not fail, with any char value.

From .NET 4.0 reference

The .NET Framework uses the Char structure to represent a Unicode character. The Unicode Standard identifies each Unicode character with a unique 21-bit scalar number called a code point, and defines the UTF-16 encoding form that specifies how a code point is encoded into a sequence of one or more 16-bit values. Each 16-bit value ranges from hexadecimal 0x0000 through 0xFFFF and is stored in a Char structure. The value of a Char object is its 16-bit numeric (ordinal) value.

Upvotes: 8

RB.
RB.

Reputation: 37202

No, it is not possible it could fail. A char ranges from 0x0 to 0xFFFF (65535), while an int ranges from -2,147,483,648 to 2,147,483,647, so all values of char fall inside the range of int.

Upvotes: 8

Related Questions