-2

I have multiple classes, all residing in a distinct namespace. All classes derive from the same base class, all have the same function, accepting the same parameters. I would like to be able to iterate through the classes, calling said function.

I know I can get a list of the classes using the following:

var validationClasses = Assembly.GetExecutingAssembly().GetTypes()
.Where(t => t.Namespace == "Panther.Business.Shipping.Validate")
.ToList();

And, of course, I can iterate through each class in validationClasses.

But I can’t figure out how to instantiate an instance of each class, and call that function.

Any direction greatly appreciated.

  • see [this answer](https://stackoverflow.com/questions/752/how-to-create-a-new-object-instance-from-a-type) – sm_ Dec 21 '20 at 05:13
  • `validationClasses` is a collection of types. You need to use `Acticator.CreateInstance` to create instance of types in that collection. https://stackoverflow.com/questions/752/how-to-create-a-new-object-instance-from-a-type – Chetan Dec 21 '20 at 05:14
  • You're trying to do what any DI-container does out-of-box. While it could be useful for education purposes, consider using DI. At least this will be more realistic scenario. – Dennis Dec 21 '20 at 06:01

1 Answers1

1

Assuming a base class ValidationBase, you could do something like:

Type baseType = typeof(ValidationBase);
MethodInfo method = baseType.GetMethod("MethodName");

var validationClasses = Assembly.GetExecutingAssembly()
                                .GetTypes()
                                .Where(t => t.IsSubclassOf(baseType));

foreach(Type t in validationClasses)
{
  var instance = Activator.CreateInstance(t);
  method.Invoke(instance, null); // Replace `null` with array of arguments if necessary
}
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206