Bagzli
Bagzli

Reputation: 6579

Search classes in an assembly and call a method

I am trying to find all classes in an assembly that impelement certain interface and then basically get a property of that object in my view. Here is what I have tried:

List<IManager> Managers = new List<IManager>();
const string @namespace = "MyProject.Models.Manager";
var managerClasses = from t in Assembly.GetExecutingAssembly().GetTypes()
        where t.IsClass && t.Namespace == @namespace
        select t;

foreach (var managerClass in managerClasses.Where(t => typeof(IManager).IsAssignableFrom(t)))
{
    var r = (IManager) managerClass;
    Managers.Add(r);
}

My code crashes on var r = (IManager) managerClass; and I don't understand how to cast that object to be of type IManager.

EDIT: I have fixed the above code with appropriate variable names to remove confusion.

Upvotes: 0

Views: 78

Answers (1)

Reddog
Reddog

Reputation: 15579

At the place where you're doing the var r = (IManager) report the report is still a Type object. You will need to instantiate that type. You can do this using Activator.CreateInstance() but you might also want to make some assertions about the constructor for that type first (e.g. require a parameterless constructor) and also check that it's a concrete class type (i.e. not abstract).

Upvotes: 2

Related Questions