Search code examples
c#reflectiondynamic-typing

Detecting dynamic parameters and return types


I've looked all over stack overflow but haven't been able to find a solution to this yet. How can I use reflection to distinguish between dynamic and object parameters and return types?

For example, suppose I have a number of methods in a class like this:

public void Foo(dynamic d) { }
public void Bar(object o) { }

public dynamic Foo() { return "foo"; }
public object Bar() { return "bar"; }

How can I get only the Foo's and not Bar's?


Solution

  • The C# compiler emits a DynamicAttribute on any dynamic parameters, return types, or members, which you can detect via GetCustomAttributes. For the sake of brevity, you can define a helper method like this:

    static bool IsDynamic(ParameterInfo pi) {
        return pi.GetCustomAttributes(typeof(DynamicAttribute), true).Length > 0;
    }
    

    Or if using .NET 4.5 or later, you can extension methods from the extremely helpful CustomAttributeExtensions class:

    static bool IsDynamic(ParameterInfo pi) {
        return pi.IsDefined(typeof(DynamicAttribute));
    }
    

    Then you get the just those methods that either select or return a dynamic type like this:

    dynamicMethods = myType.GetMethods()
        .Where(mi => IsDynamic(mi.ReturnParameter) || mi.GetParameters().Any(IsDynamic));
    

    Note that the C# compiler will throw an error if you try to use the DynamicAttribute directly, but other CIL compilers may not.