There was an interesting discussion on a mailing list I'm on recently, where a fellow asked: "Given a Type object representing a given class, how do you determine if that class implements a specific interface?"
To be clear, he's not asking how to do:
(C#)
if (myType is IWhateverable) { ... }
He has an object of type System.Type and he wants to see if that type is IWhateverable. He could do this:
(VB)
If myType.GetInterface("MyClass.IWhateverable") IsNot Nothing Then
But he feels, perhaps rightfully so, that the string literal stuck in there is distasteful.
One fellow said, why not run through the interfances with a helper function:
(VB)
Function IsImplemented(objectType As Type, intefaceType As Type) As Boolean
For Each thisInterface As Type in objectType.GetInterfaces
If thisInterface Is interfacetype Then
Return True
Next
Next
End Function
The next said, why not:
(C#)
if (typeof(IWhateverable).IsAssignableFrom(myType)) { ... }
Which isn't bad, but the semantics of IsAssignableFrom are a little more "inclusive" than you might want. From MSDN:
"Returns true if the c parameter 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 supports."
I suggested this, which is his original idea with the string literal coming from elsewhere:
(C#)
if (myType.GetInterface(typeof(IWhateverable).FullName) { ... }
However, it's a shame there isn't a built in:
(C#)
if (myFooInstance.IsImplementationOf(typeof(IWhateverable))) { ... }
Which, arguably, would just do what the IsImplemented definition at the top of this post would do internally! :)
UPDATE: Wesner says I'm using IsAssignableFrom wrong. Yes, I think I reversed the semantics there. Fixed. It's still up in the air if it's more correct or faster as he implies it may be. Check the comments for the ongoing thread.
Hosting By