IsAssignable what? 10
I’ve tweeted it before, Jackson tumblered it in return, but after commenting on a StackOverflow answer where the poster got it wrong, commenting:
I always seem to turn that call around.
I felt that I needed to broaden this grand hack. If you’re like me, and apparently like a lot of coders out there, you tend to always get Type.IsAssignableFrom wrong on the first try, then you need this extension method:
public static bool IsAssignableTo (this Type self, Type type)
{
if (self == null)
throw new ArgumentNullException ("self");
if (type == null)
throw new ArgumentNullException ("type");
return type.IsAssignableFrom (self);
}
Somehow, even if IsAssignableFrom is more «left to rightish», preserving the side of the arguments a real assignment would have, I understand IsAssignableTo faster. For what it’s worth, I’ve used it extensively while writing our .net 3.5 implementation of System.Linq.Expressions, and it served me well.
Have a great friday.
Trackbacks
Use the following link to trackback from your own site:
http://www.evain.net/blog/articles/trackback/779
Whats even funnier than the parameters being seemingly wrong way round… is that the Java clas “Class:” has a method with same wrong way around parameters…I wonder if Microsoft forgot to change this when copying from java ?
The original method is so annoying in his pit of despair design it should really be called IsAssignableFromOrToWhateverFuckThisShitImGoingToSpace()
You’re reinventing the wheel here: just use typeA.IsSubclassOf(typeB)
Omer, not only am I not reinventing the wheel, but I’m also right while you’re wrong. Checking if a type subclasses another is not the same thing as being assignable to a type. Assignability takes interfaces and variance into account for instance.
Geez – you’re right. I’ll have to check all my code where I’ve been using IsSubclassOf throughout the years now. I agree that the original IsAssignableFrom should have been reversed.
why not just use “is”
Because `is` is a runtime check performed on an object instance, and IsAssignableFrom works on a Type instance when working on reflection?
Cool, did you add this to MonoRocks, I mean, Cadenza?
JB is correct that subclassing is not the operation here. IsAssignableTo is actually a subtyping check. IsAssignableTo is a predicate on System.Type corresponding to the “is” operator on instances.
I personally prefer naming the operation after what it actually is, ie. “Subtypes”, and I’ve supported this Subtypes() extension method in my Sasa library for awhile now.
Sandro, I also prefer naming operations after what they actually are, and assignability isn’t semantically the same thing as subtyping. You can query a generic parameter if an interface is assignable to it (that is, if the generic parameter has a generic constraint to this interface), and semantically, if the interface is assignable to the generic parameter, the interface doesn’t subtype the generic parameter.