tags:

views:

114

answers:

2

It's just a service locater type of pattern I am trying to implement, where I'd like to catch an attempt to register an implementation to an interface it doesn't belong to, as in:

public void Add(Type interfaceType, object implementingObject)
{
    // ... check for nulls            

    // NO GOOD
    if(!implementingObject.GetType().IsAssignableFrom(interfaceType)...

    // NO GOOD
    if(!implementingObject.GetType().IsInstanceOf(interfaceType)...

    // FINALLY!
    if(!implementingObject.GetType().BaseType.IsAssignableFrom(interfaceType)...

    // ... ok, add it           
}

Now I finaly figured out to use BaseType.IsInstanceOf by looking inside NUnit's isInstanceOf assertion, but it still seems unituitive.

Can someone explain why this makes sense? Is there some easier way to do this?

+3  A: 

The way to look at it is from left to right, like you would normally when making an assignment in a language.

So in C#, the equivalent of calling assigningTo.IsAssignableFrom(assigningFrom) (or any of the other methods you mention) is to think of it as "will the following code work":

<assigningTo type> variable = <instance of assigningFrom>;

Applying that to your code, you want to use:

interfaceType.IsAssignableFrom(implementingObject.GetType())
interfaceType.IsAssignableFrom(implementingObject.GetType().BaseType)

The logic being you want to see if any of the types on the implementing object can be assigned to the interface type, or, in other words, if the implementing object can be assigned to interfaceType.

casperOne
A: 

I think you want:

interfaceType.IsAssignableFrom(implementingObject.GetType())

Why would a concrete type be assignable from an interface?

Richard Szalay