Note that there are two different things in C#. A class specification, which describes a class, is contained in a Type
object. A class instance, which describes a particular object, is an object
or any derived class.
There are some additional issues with your code, but I think you can solve them yourself once you get how types and instances work.
In this case, GetTypesInNamespace
returns a list of Type
objects, thus class specifications. You can put them in a dictionary if you want.
Dictionary<string, Type> dictionary = new Dictionary<string, Type>();
Then, if you want to make the class specification into an instance, you have to call the class constructor. You can use reflection on the Type
for that.
// Get the type.
Type someType = dictionary["ClassA"];
// Create an instance.
object myInstance = Activator.CreateInstance(someType);
Note that the above example works for classes that have a default parameterless constructor. If your classes have constructors with parameters, look at the Activator.CreateInstance
method's documentation to find out how to pass those parameters.
Now you want to call MethodB
on the instance. There are three ways to do this.
You know the type of the instance, and you cast the instance to the correct type.
ClassA myClassA = (ClassA)myInstance;
myClassA.MethodB(5);
You don't know the type of the instance, but you know it has a method MethodB
, and you're using .NET 4 or newer.
dynamic myDynamicInstance = (dynamic)myInstance;
myInstance.MethodB(5);
When the instance' class doesn't have a MethodB
, you'll get an exception.
Using reflection. This is a bit more complicated. Search around if you need it. I think dynamic
is the way to go for you here.