With
public abstract class CompositionPlugin { ... }
and
public class MyCompositionPlugin : CompositionPlugin { ... }
I want to check if an object's type is equal to a given type:
public class Framework {
public IList<CompositionPlugin> CompositionPlugins = new List<CompositionPlugin>();
public CompositionPlugin GetCompositionPlugin(Type ofType)
{
foreach (CompositionPlugin plugin in CompositionPlugins)
{
if (plugin.GetType().Equals(ofType))
return plugin;
}
throw new ArgumentException("A composition plugin of type " + ofType.FullName + " could not be found");
}
}
Where the method is called like this:
Framework framework = new Framework();
// Adding the plugin to the framework is done by loading an assembly and
// checking if it contains plugin-compatible classes (i.e. subclasses
// of <CompositionPlugin>)
framework.RegisterAssembly("E:\\Projects\\Framework\\MyPlugin\\bin\\Debug\\MyPlugin.dll");
CompositionPlugin plugin = framework.GetCompositionPlugin(typeof(MyCompositionPlugin));
Yet, when testing, this check always fails, even though I most definitely have that type of object in the list that I request.
In my understanding, it should return the first instance of MyCompositionPlugin
that is found inside the CompositionPlugins
-List.
Is my type check wrong? Why? How is it done correctly?
You want to use IsAssignableFrom
on your Type:
if (ofType.IsAssignableFrom(plugin.GetType())
Equals
only handles cases where types are exactly the same. IsAssignableFrom
also handles the case where ofType
may be a type that your plugin inherits from, or an interface that is implemented.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With