Ralt
Ralt

Reputation: 2206

Is it possible to create instances of all classes in an assembly?

I have an application which creates and exports a .dll which contains custom icons for WPF forms.

I'm trying to create a sort of exploratory test where I can open up an app, and choose a .dll. Once I have chosen the .dll it will look inside of it and create instances of each class in there, and then add these objects to the form.

I want to be able to do this as a quick test to see that all the icons in that .dll display correctly before sending it out to a customer.

I am able to get all of the types inside of the .dll by:

var assembly = Assembly.LoadFrom(fileDialog.FileName);

foreach (var type in assembly.DefinedTypes)
{
   Console.WriteLine(type);
}

I was wondering if it is possible to somehow use this to create the objects.

Upvotes: 2

Views: 404

Answers (2)

xanatos
xanatos

Reputation: 111930

Normally you aren't really interested in creating all the types, you want to create types that implement a certain interface or that subclass a certain class:

Type baseType = typeof(... someting ...);
Assembly assembly = ... your assembly ...;

foreach (Type type in assembly.GetTypes())
{
    // If type implements/subclasses baseType
    if (baseType.IsAssignableFrom(type))
    {
        // If there is a public parameterless constructor
        if (type.GetConstructor(Type.EmptyTypes) != null)
        {
            IMyInterface obj = (IMyInterface)Activator.CreateInstance(type)
        }
    }
}

Upvotes: 0

sszarek
sszarek

Reputation: 424

The simple solution will be using .NET Activator class. It is using reflection but since you want create this object for testing purposes I don't think that overhead will make difference for you.
You can use Activator like this:

Type type = typeof(SomeClass);
object obj = Activator.CreateInstance(type);

If you need to create object which constructor needs some parameter you can call overloaded CreateInstance which accepts arguments:

Type type = typeof(SomeClass);
object obj = Activator.CreateInstace(type, new object[] {"arg1", "arg2"});

CreateInstance method will return object but you can always cast to desired type (if you know it) so you can easily perform some operations on newly created object. Alternatively you can call methods, set properties using reflection.

You can read more about Activator on MSDN.

Upvotes: 2

Related Questions