9

Is it possible to loop through each class in a namespace and initialize an object for each class?

For instance, I want to loop through all classes in the Test.POS namespace, create an object for each class, and call the runImportProcess method on each object.

I know that I can loop through a namespace like so:

Type[] typelist = GetTypesInNamespace(Assembly.GetExecutingAssembly(), 
                                      "Test.POS");

foreach (Type t in typelist)
{
    Console.WriteLine(t.Name);
}

I'm not sure if it's possible to use this t variable to accomplish what I want. Any insight for a novice?

wonea
  • 4,783
  • 17
  • 86
  • 139

4 Answers4

6

Try Assembly.GetTypes(). Then filter them by the namespace (and ensure they are what you want). To instantiate them, use Activator.CreateInstance(...).

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • Perfect! Now, the real challenge is to call the `runImportProcess()` method on this new object. Since the compiler isn't aware of the class' properties and methods at compile time, is this even possible? Looking at this example, it seems like I have to programmatically define which type the variable would be after I call `Activator.CreateInstance()` - `ObjectType instance = (ObjectType)Activator.CreateInstance(objectType);` –  Dec 11 '13 at 20:06
  • 1
    you can do that - even better - create a shared interface. – Daniel A. White Dec 11 '13 at 20:08
5

Try this:

var types = Assembly
    .GetExecutingAssembly()
    .GetTypes()
    .Where(t => t.Namespace.StartsWith("Test.POS"));

foreach (var t in types)
{
    Console.WriteLine(t.Name);
}
BartoszKP
  • 34,786
  • 15
  • 102
  • 130
3

You can use GetConstructor method

using System;
using System.Reflection;

class Addition
{
    public Addition(int a)
    {
        Console.WriteLine("Constructor called, a={0}", a);
    }
}

class Test
{
    static void Main()
    {
        Type type = typeof(Addition);
        ConstructorInfo ctor = type.GetConstructor(new[] { typeof(int) });
        object instance = ctor.Invoke(new object[] { 10 });
    }
}
BartoszKP
  • 34,786
  • 15
  • 102
  • 130
Mauricio Gracia Gutierrez
  • 10,288
  • 6
  • 68
  • 99
2

You can use reflector to get all the classes from an assembly:

Getting all types in a namespace via reflection

and then use activator to create new instances of the retrieved classes:

Get a new object instance from a Type

Community
  • 1
  • 1
Gang Gao
  • 1,051
  • 8
  • 9