Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is int assignable from char?

I note that

int number = 'a';

Is a sound C# statement

But that the expression

typeof(int).IsAssignableFrom(typeof(char))

Returns false. Isn't this a contradiction?

like image 849
Colonel Panic Avatar asked Mar 06 '13 17:03

Colonel Panic


People also ask

Can an integer be assigned to char?

Because, char are data types which hold 1 byte (8 bits) of data. So in char you can store integer values that can be represented by eight bits. That is 0-255 in normal case.

Is it legal to assign an int to a char variable?

The character is only a representation of an integer value. For example, '0' can be written as 0x30 or 48 , 'a' is an alternative for 0x61 or 97 , etc. So the assignment is perfectly valid.

Can an int be stored as a char?

We can convert int to char in java using typecasting. To convert higher data type into lower, we need to perform typecasting. Here, the ASCII character of integer value will be stored in the char variable. To get the actual value in char variable, you can add '0' with int variable.

Can you assign an int to a char in c?

A char in C is already a number (the character's ASCII code), no conversion required. If you want to convert a digit to the corresponding character, you can simply add '0': c = i +'0'; The '0' is a character in the ASCll table.


1 Answers

Isn't this a contradiction?

Nope. C# provides an implicit conversion from char to int, but if you look at the documentation for Type.IsAssignableFrom it states for the return value:

true if c and the current Type represent the same type, or if the current Type is in the inheritance hierarchy of c, or if the current Type is an interface that c implements, or if c is a generic type parameter and the current Type represents one of the constraints of c, or if c represents a value type and the current Type represents Nullable<c>. false if none of these conditions are true, or if c is null.

None of those conditions is true, so it returns false.

like image 179
Jon Skeet Avatar answered Sep 26 '22 13:09

Jon Skeet