I'm trying to search a specific namespace and return instances of all classes that implement the specified interface and have the specified base class.
Here is the code
private List<T> GetInstancesWithInterface<T, T2>(string @namespace) { var tList = Assembly.GetExecutingAssembly() .GetTypes() .Where(t => t.Namespace == @namespace) .Where(t => t.BaseType == (typeof (T)) && t.GetInterfaces().Contains(typeof(T2))) .Select(t => (T)Activator.CreateInstance(typeof(T), this)) .ToList(); return tList; } And here is the calling code
var examples = GetInstancesWithInterface<DrawableGameComponent, IResettable>("GamePhysics.Physics"); foreach (var example in examples) { Debug.Assert(example is IResettable); var r = example as IResettable; _examples.Add(r); Components.Add(example); if (Components.Count == 0) continue; example.Enabled = false; example.Visible = false; } The problem I am having is the Assert fails because I get back a list of DrawableGameComponent which cannot be treated as IResettable so the code var r = example as IResettable always returns null.
Additional info
I should have also mentioned that DrawableGameComponent does not implement the IResettable interface. My three example classes that I'm trying to fetch all have DrawableGameComponent as the base class and they also implement IResettable.
Additional thoughts
I was thinking that perhaps I should create a new abstract class called Example which implements DrawableGameComponent and IResettable and then my concrete example classes can just implement the Example base class. I suppose this might be better design but I am also interested to know if I can get it working as it is.
isoperator should deal with such a situation just fine. Have you stepped through it with a debugger and looked at each object returned?DrawableGameComponentdoes not implement the IResettable interface. My three example classes that I'm trying to fetch all have DrawableGameComponent as the base class and they also implement IResettable. I'll update the question with this extra info too.(typeof (T)).IsAssignableFrom(t.BaseType)(and vice versa) rather thant.BaseType == (typeof (T))? If you're looking forT's child classes, then==most likely won't work.IsAssignableFromSelecttoSelect(t => (T)Activator.CreateInstance(t, this)). The way it's currently set up will create instances ofTwhenever you find a child class, rather than creating instances of the child classes.