2

I am trying to get the properties of a return type of a method using reflection.

I am getting the return type of the method using MethodInfo.ReturnType, which yields my a type of Task<T> since my method is async. Using GetProperties on this type yields me with the properties belonging to Task: Result, Exception, AsyncState. However, I want to get the properties of the underlying type T.

Example for method with signature:

public async Task<MyReturnType> MyMethod()
var myMethodInfo = MyType.GetMethod("MyMethod");
var returnType = myMethodInfo.ReturnType; // Task<MyReturnType>
var myProperties = returnType.GetProperties(); // [Result, Exception, AsyncState]

How can I get the properties of the inner type T in Task in stead of the properties of Task?

Tiamo Idzenga
  • 1,006
  • 11
  • 23
  • Does this answer your question? [C# Get Generic Type Name](https://stackoverflow.com/questions/4185521/c-sharp-get-generic-type-name) – Klamsi Jun 18 '21 at 07:07
  • @Klamsi Not quite, as it seems that will get Task in stead of T. I have now answered my own question, however. – Tiamo Idzenga Jun 18 '21 at 07:08

1 Answers1

4

You can determine if the type is a Task with the method GetGenericTypeDefinition() and get the generic type arguments with the property GenericTypeArguments.

In this case:

var myMethodInfo = MyType.GetMethod("MyMethod");
var returnType = myMethodInfo.ReturnType;

if (returnType.GetGenericTypeDefinition() == typeof(Task<>)) {
    var actualReturnType = returnType.GenericTypeArguments[0]; // MyReturnType
    var myProperties = actualReturnType.GetProperties(); // The properties of MyReturnType!
}
Tiamo Idzenga
  • 1,006
  • 11
  • 23