L.Le
L.Le

Reputation: 65

c# how to dynamically call method on existing object

I am calling an API and want to dynamically call methods from that object. Using ASP.Net reflections, it seems that it allows you to get the type of that object, then invoke. But that seems to call the method from an empty instance of that class. In my case I have that object with data/information in an existing instance of that class, so is it possible to call a method dynamically from it?

For example:

I have ServiceReference "ThirdPartyRef".

ThirdPartyRef.ThirdPartyRefApiClient api = new ThirdPartyRef.ThirdPartyRefApiClient();
ThirdPartyRef.ApiObjectCollection collection = new ThirdPartyRef.ApiObjectCollection();

ThirdPartyRef.GetOrderUpdatesCollections orderUpdates = new ThirdPartyRef.GetOrderUpdatesCollections();

collection = (ThirdPartyRef.ApiObjectCollection)api.get(orderUpdates);

foreach (ThirdPartyRef.Order orderUpdate in collection.Items)
{

    MethodInfo[] mi = orderUpdate.GetType().GetMethods();
    foreach (MethodInfo orderUpdateMethInfo in mi)
    {
        string methodName = orderUpdateMethInfo.Name.Replace("get_", ""); // for example get_LastModifiedDate and set_LastModifiedDate is available
        var meth = orderUpdate.GetType().GetMethod(methodName);
        string result = string.Empty;
        result = meth.Invoke(orderUpdateMethInfo, null).ToString();
        Console.WriteLine("result: " + result.ToString());
    }

}

I changed the actual name of the third party company for this example, hopefully I didn't make mistakes by re-typing the code.

When I run the code above, I just get empty outputs. So that made me believe that line that has "meth.Invoke" is being executed on an empty instance or a "type" of that object, not on the actual instance that has data.

When I directly call the method on that object, I'm able to see data.

Console.WriteLine("LastModified:" + orderUpdate.LastModified.ToString());

Output - LastModified:8/3/2015 5:43:18 PM

Is there a way to dynamically call method on existing object? Or am I going about this all the wrong way? The reason I want to do it dynamically is because there are 40+ methods where I want to get that into a database. If I can just layout the database table to match, then it'll be easier in the long run if the third party company were to ever change their API.

Upvotes: 1

Views: 2648

Answers (1)

Steve Danner
Steve Danner

Reputation: 22158

Change this line:

result = meth.Invoke(orderUpdateMethInfo, null).ToString();

to this:

result = meth.Invoke(orderUpdate, null).ToString();

The first parameter of Invoke is the object upon which you are acting, which should be your orderUpdate object as your show in the static code sample where you call LastModified directly.

Upvotes: 3

Related Questions