5

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?

Colonel Panic
  • 132,665
  • 89
  • 401
  • 465

2 Answers2

13

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Also see [How to tell if Type A is implicitly convertible to Type B](http://stackoverflow.com/questions/2224266/how-to-tell-if-type-a-is-implicitly-convertible-to-type-b) – Justin Mar 06 '13 at 17:18
  • Thanks. The method is much more complicated than the name suggested. – Colonel Panic Mar 06 '13 at 19:04
1

The questions you are asking are slightly different. The set of assignable values in C# are generally more permissive than the set of assignable types in the CLR.

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454