Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not understanding Type.IsAssignableFrom

Tags:

c#

types

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

Why is canAssign false?

like image 868
spender Avatar asked Jan 24 '11 11:01

spender


5 Answers

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

like image 138
Matthew Steeples Avatar answered Sep 21 '22 19:09

Matthew Steeples


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.

like image 24
BoltClock Avatar answered Sep 24 '22 19:09

BoltClock


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.

like image 41
Guffa Avatar answered Sep 20 '22 19:09

Guffa


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.

like image 21
veggerby Avatar answered Sep 20 '22 19:09

veggerby


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.

like image 29
Konstantin Oznobihin Avatar answered Sep 24 '22 19:09

Konstantin Oznobihin