I got all the classes that implement my interface. I want to call a method when the instance of the object is created
var types =AppDomain.CurrentDomain.GetAssemblies().ToList()
.SelectMany(s => s.GetTypes())
.Where(t => typeof(IManagerReport).IsAssignableFrom(t));
Console.WriteLine("Processing manager reports..");
foreach(var TheType in types)
{
//error here
var temptype = Activator.CreateInstance(TheType) as IManagerReport;
temptype.Load();
temptype.Save();
Console.WriteLine("Saved to: " + temptype.SavePath);
}
The error that is produced is here:
Cannot create an instance of an interface
Make sure you exclude IManagerReport from the selection of types you’re fetching.
The problem is, in your types enumerable, you’ve got not only the derived types of IManagerReport, but also the IManagerReport itself. You can’t create an instance of an interface, only a class. Use the code I posted to exclude most trouble items, but I would still add a try/catch on the Activator.CreateInstance. You may have derived types that have no parameterless public constructor. These would also fail.
Wrap the call in a try/catch and continue. I would say you should account for all possibilities here, but there’s just simply too many of them. Account for a few, then also account for the possibility that the creation simply won’t work for another reason.