Search code examples
c#genericsdynamicdynamicobject

Get generic type of call to method in dynamic object


I'm starting to work with dynamic objects in .Net and I can't figure out how to do something.

I have a class that inherits from DynamicObject, and I override the TryInvokeMember method.

e.g.

class MyCustomDynamicClass : DynamicObject
{
    public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
    {
        // I want to know here the type of the generic argument
    }
}

And inside that method I want to know the type (if any) of the generic arguments in the invocation.

e.g. If I invoke the following code, I want to get the value of System.Boolean and System.Int32 inside the overrided method of my dynamic object

dynamic myObject = new MyCustomDynamicClass();
myObject.SomeMethod<bool>("arg");
myObject.SomeOtherMethod<int>("arg");

Currently if I place a breakpoint inside the overrided method I can get the name of the method being invoked ("SomeMethod" and "SomeOtherMethod", and also the values of the arguments, but not the generic types).

How can I get these values?

Thanks!


Solution

  • Actually I looked through the hierarchy of the binder and found a property with the needed values in the internal fields of the object.

    The problem is that the property isn't exposed because it uses C#-specific code/classes, therefore the properties must be accessed using Reflection.

    I found the code in this japanese blog: http://neue.cc/category/programming (I don't read any japanese, therefore I'm not sure if the author actually describes this same issue

    Here's the snippet:

    var csharpBinder = binder.GetType().GetInterface("Microsoft.CSharp.RuntimeBinder.ICSharpInvokeOrInvokeMemberBinder");
    var typeArgs = (csharpBinder.GetProperty("TypeArguments").GetValue(binder, null) as IList<Type>);
    

    typeArgs is a list containing the types of the generic arguments used when invoking the method.

    Hope this helps someone else.