Search code examples
c#reflectiondynamic-class-creation

CSharp: How do I dynamically call a class(with constructor) and it's methods?


I've been reading examples of Reflection for two days and I can't quite seem to piece together everything to fit what I need. In fact I thought I was using reflection, until I noticed my "using System.Reflection" was grayed out. :-)

I have an xml file that contains my class names and the methods contained within. The order of the methods or even the names can change. Once I read them in I want to be able to execute them. Seems simple enough.

I have the following test code:

    // myClassName = "namespace.TransactionServices"
    Type tb = Type.GetType(myClassName);

    // Classes will always have the same constructor
    object classInstance = Activator.CreateInstance (
        tb, 
        new object[] 
        {
            authorization.apiKey, 
            authorization.userName, 
            testData.servicesEndPoint
        });

    //Grab the method I want

    //myMethodName = "GetVersion"
    MethodInfo mymethod = tb.GetMethod(myMethodName);
    // no parameters for this method call
    object result = mymethod.Invoke(classInstance, null);

tb is null. I was just going to work away at trying to get the correct API for creating the class, but I don't even know if the rest of what I have is valid.

Any suggestions?

Thanks

Edit: Added namespace. Activator.CreateInstance is returning error that constructor is not found.. It is there.


Solution

  • Are you sure you specified the complete class name including namespace? without the namespace, the result will be null.