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?
Turns out, the information I initially left out of the question, deeming it not important, was so after all.
The
MyCompositionPluginandCompositionPluginare both defined in different assemblies, that the executing program loads dynamically at runtime.The .NET-Runtime now consideres a type loaded from a different assembly another than the one referenced by the executing assembly, rendering the
MyCompositionPlugin-Type in theProgramto be considered unequal to theMyCompositionPluginloaded from another assembly, even if they are actually the same.The solution to comparing the two for equality (in that they are the same “Class” in the common sense) is to break it down to a string-equality of the defining assemblies, which is arguably dirty, but does the trick.
Cudos to Paolo Falabella who pointed to this question