int i=1;
long longOne=i; //assignment works fine
//...but
bool canAssign=(typeof(long).IsAssignableFrom(typeof(int))); //false
Why is canAssign false?
Looking at the method in Reflector it would appear that this method is meant to be used for determining inheritance rather than compatibility.
For example if you have a class that implements an interface then the method would return true if you did
(typeof(interface).IsAssignableFrom(typeof(class))
When you assign an int to a long, all that happens is implicit conversion. longOne is an actual long (as if you initialized it to be 1L), and not an int masquerading as a long, if you get the drift.
That is, int (or Int32) and long (or Int64) aren't related in terms of inheritance or implementation; they just happen to be convertible because both are integral number types.
The IsAssignableFrom returns true if the types are the same, or if the type implements or inherits it.
A long doesn't inherit int, so the method returns false.
When you assign an int value to a long, it's not just an assignment. The compiler also automatically adds code to convert the int value into a long value.
From http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx:
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. false if none of these conditions are true, or if c is null.
As @BoltClock says it is just implicit conversion.
Because Type.IsAssignableFrom is a .NET framework facility, while assigning from int to long is a C# language one. If you take a look at the generated IL you'll see type conversion instruction there. There are lots of places where CLR rules might differ from C# ones, one more example is overload resolution in MethodBase.Invoke and the one performed by C# compiler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With