Reputation: 101
Getting casting error when trying to cast Derived1 and Derived2 to a TemplateControl type object so that I can add them to a list of TemplateClass objects. Using typeof(TemplateClass).IsAssignableFrom(t) does not match the type, even though it shows the basetype of t as TemplateClass.
class abstract TemplateClass : UserControl {}
class Derived1 : TemplateClass {}
class Derived2 : TemplateClass {}
Type[] types = plugin.GetTypes(); //returning types for Derived1 and Derived2 correctly
foreach (Type t in types)
{
if (typeof(UserControl).IsAssignableFrom(t))
{
var control = (TemplateClass)Activator.CreateInstance(t); // casting error here
controls.Add(control);
}
}
EDIT:
The information i did not include above is that the object plugin is an Assemblly loaded from a dll. The dll is ModelControls. So TemplateClass is really ModelControls.TemplateClass and Derived1 and Derived2 are preceded with the same namespace. When i use Model.TemplateClass in the typeof().IsAssignable(t) it does not find any matching types, even though creating a new Type Array like the one below works fine.
Type[] types = { typeof(ModelControls.Derived1), typeof(ModelControls.Derived2) };
Upvotes: 1
Views: 90
Reputation: 29846
You are failing since you are checking typeof(UserControl)
and automatically casting to TemplateClass
.
What happens if t
is a UserControl
? You will get an invalid cast exception.
Here's a working example checking typeof(TemplateClass)
:
Type[] types = { typeof(Derived1), typeof(Derived2) };
foreach (Type t in types)
{
if (typeof(TemplateClass).IsAssignableFrom(t)) // not typeof(UserControl)
{
var templateClass = (TemplateClass)Activator.CreateInstance(t);
}
}
Upvotes: 2