Misunderstanding Type.IsAssignableFrom

int i=1; long longOne=i; //assignment works fine //...but bool canAssign=(typeof(long).IsAssignableFrom(typeof(int))); //false 

Why canAssign false?

+7
source share
5 answers

When you assign an int to long , all that happens is an implicit conversion. longOne is the actual long (as if you initialized it as 1L ), not int , masquerading as long if you get a drift.

That is, int (or Int32 ) and long (or Int64 ) are not related to inheritance or implementation; they just become convertible because both are integer types of numbers.

+10
source

Looking at a method in Reflector, it seems that this method is intended to determine inheritance, and not for compatibility.

For example, if you have a class that implements an interface, then the method will return true if you did (typeof(interface).IsAssignableFrom(typeof(class))

+12
source

IsAssignableFrom returns true if the types match or the type implements or inherits it.

A long does not inherit int , so the method returns false.

When you assign an int value to a long value, it is not just an assignment. The compiler also automatically adds code to convert the int value to a long value.

+3
source

Since Type.IsAssignableFrom is a .NET framework tool, and assigning from int to long is C # language. If you look at the generated IL, you will see there a type conversion instruction. There are many places where CLR rules may differ from C # rules, another example is overload resolution in MethodBase.Invoke and one that is executed by the C # compiler.

+3
source

From http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx :

true if c and the current type are the same type, or if the current type is in the c inheritance hierarchy, or if the current type is an interface that c implements, or if c is a parameter of a general type and current Type is one of the restrictions c. false if none of these conditions is true, or if c is null.

Like @BoltClock says this is just an implicit conversion.

+2
source

All Articles