3

I have this simple interface in .net-6/C#9 with nullable reference types turned on:

public interface IMyInterface
{
    Task<MyModel?> GetMyModel();
}

How do I detect by reflection that the generic argument MyModel of method's return type is in fact declared as nullable reference type MyModel? ?

What i tried...

typeof(IMyInterface).GetMethods()[0].ReturnType...??

I tried using NullabilityInfoContext but the Create method accepts PropertyInfo, ParameterInfo, FieldInfo, EventInfo which does not really help here or I can't figure out how.

The solution from here also accepts only PropertyInfo, FieldInfo and EventInfo

I also tried observing the attributes from method.ReturnType.GenericTypeArguments[0] but there is no difference between methods that return Task<MyModel> and Task<MyModel?>

custom attributes

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
Mirek
  • 4,013
  • 2
  • 32
  • 47

1 Answers1

3

Use MethodInfo.ReturnParameter for NullabilityInfoContext:

Type type = typeof(IMyInterface);
var methodInfo = type.GetMethod(nameof(IMyInterface.GetMyModel));

NullabilityInfoContext context = new();
var nullabilityInfo = context.Create(methodInfo.ReturnParameter); // return type
var genericTypeArguments = nullabilityInfo.GenericTypeArguments;
var myModelNullabilityInfo = genericTypeArguments.First(); // nullability info for generic argument of Task
Console.WriteLine(myModelNullabilityInfo.ReadState);    // Nullable
Console.WriteLine(myModelNullabilityInfo.WriteState);   // Nullable

To analyze nullable attributes methodInfo.ReturnTypeCustomAttributes.GetCustomAttributes(true) can be used.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • What about generic methods with an (unconstrained) type-parameter, but `void` return-type and no method parameters? e.g. `static void Foo() { }` as `Foo()` vs `Foo()`? – Dai Sep 30 '22 at 15:07