2

I want to iterate through types in an assembly and if a type is a subclass of a specified interface, I want to create an object of the type and add it to a list like so:

var tasks = new List<IScheduledTask>();

foreach (Type t in Assembly.GetExecutingAssembly().GetTypes())
{
    if (t.IsSubclassOf(typeof(IScheduledTask)))
    {
        tasks.Add(new t());
    }
}

Obviously this above does not work. How can you achieve what I am seeking?

Abe Miessler
  • 82,532
  • 99
  • 305
  • 486
jcvandan
  • 14,124
  • 18
  • 66
  • 103

4 Answers4

4

Activator.CreateInstance is what you're after.

var tasks = new List<IScheduledTask>();
foreach (Type t in Assembly.GetExecutingAssembly().GetTypes())
{
    if (t.IsSubclassOf(typeof(IScheduledTask)))
    {
        tasks.Add((IScheduledTask)Activator.CreateInstance(t));
    }
} 
George Duckett
  • 31,770
  • 9
  • 95
  • 162
  • This will create a list of objects of type `Object` will it not? – Abe Miessler Jun 15 '11 at 16:01
  • No, the object will be of type T, you just need to cast it. – Ray Jun 15 '11 at 16:12
  • @abe-miessler to cast it: `tasks.Add((IScheduledTask)Activator.CreateInstance(t));` – jbtule Jun 15 '11 at 16:23
  • Ahh, I was thinking he wanted to create an instance of the class that inherits from the interface. If he wanted to do that, would it be possible? – Abe Miessler Jun 15 '11 at 16:24
  • @Abe-Miessler, that is what `CreateInstance` is doing here. The type given to it is the implementing type, not the interface-type itself. You cast to `IScheduledTask` because you have to in order to put it on your list. – Paul Phillips Jun 15 '11 at 17:00
  • But doesn't CreateInstance return an object of type `Object`? – Abe Miessler Jun 15 '11 at 17:32
  • @abe-miessler that's the signature of the method but it's "really" returning an instance of the type it is given. Remember that everything inherits from `Object`. – Paul Phillips Jun 15 '11 at 19:15
2

Look at using the Activator.CreateInstance method:

ObjectType instance = (ObjectType)Activator.CreateInstance(objectType);
Abe Miessler
  • 82,532
  • 99
  • 305
  • 486
1

This previous question may help Instantiate an object with a runtime-determined type

It uses Activator.CreateInstance

Community
  • 1
  • 1
Dean
  • 5,896
  • 12
  • 58
  • 95
1
Activator.CreateInstance(t);

will do the trick.

Be careful though, the class you want to instanciate must have a public constructor with no argument for it to work.

Falanwe
  • 4,636
  • 22
  • 37