Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does IsAssignableFrom() not work for int and double?

Tags:

c#

.net

types

This is false: typeof(double).IsAssignableFrom(typeof(int))

This is false: typeof(int).IsAssignableFrom(typeof(double))

But this works:

double a = 1.0;
int b = 1;

a = b;

Clearly a double is assignable from an int but the framework IsAssignableFrom() gets it wrong.

Why? Or is this a bug in .NET caused by the special nature of int and double which have no inheritance relationship but are assignable (in one direction)?

like image 882
Ian Mercer Avatar asked Jun 08 '11 07:06

Ian Mercer


1 Answers

C# is providing the implicit conversion from int to double. That's a language decision, not something which .NET will do for you... so from the .NET point of view, double isn't assignable from int.

(As an example of why this is language-specific, F# doesn't perform implicit conversions for you like this - you'd need to explicitly specify the conversion.)

It's worth looking at the documentation for Type.IsAssignableFrom (edited very slightly for readability):

Returns 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. Returns false if none of these conditions are true, or if c is null.

Now apply that to double and int and you'll see it should return false.

like image 93
Jon Skeet Avatar answered Oct 19 '22 02:10

Jon Skeet