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

Why is canAssign false?

5 Answers 5

32

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))

18

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.

6

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.

3

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.

1
  • 10
    This one always confuses me. I always forget which way to check (base to child or child to base). Leaving this here: var isSameOrChild = baseType.IsAssignableFrom(otherType)
    – Josh M.
    Jul 28, 2016 at 14:14
3

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.