Search code examples
c#async-awaitreflectionaopcastle-dynamicproxy

Reflect the returnType of an async method


Below is the code for an interceptor i wish to use for implementing a cacheprovider. I need to determine the return type of the method that will be invoked. This is pretty straight forward when the method invoked is synchronous. However most of the methods i'm encountering are async, they are returning a Task.

How can I use reflection to figure out the return type of the async methods?

public void Intercept(IInvocation invocation)
{
    try
    {
        if (invocation.Method.Name.StartsWith("Retrieve"))
        {
            var returnType = invocation.Method.ReturnType;
            if (returnType.IsGenericType &&
                returnType.GetGenericTypeDefinition() == typeof (Task<>))
            {
                var returnTypeOfTheTask = returnType.NeedSomeHelpHere();
            }
        }
        _circuitBreaker.Execute(invocation);
    }
    // ...
}

Solution

  • You can use either

    var returnTypeOfTheTask = returnType.GetGenericArguments()[0];
    

    or

    var returnTypeOfTheTask = returnType.GenericTypeArguments[0];
    

    Which one you will use depends mostly on the platforms that you need to support (e.g. the first option exists since .NET 2.0 but is not supported in Modern UI, while the second option does not exist in .NET 4.0). I would recommend using the second method if both would work for your needs.