Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type equality check in C#

Tags:

c#

types

equality

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?

like image 738
F.P Avatar asked Dec 04 '22 15:12

F.P


1 Answers

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.

like image 105
vcsjones Avatar answered Dec 10 '22 10:12

vcsjones