Home > Mobile >  C# detect nullable reference type from generic argument of method's return type using reflectio
C# detect nullable reference type from generic argument of method's return type using reflectio

Time:03-21

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 custom attributes

CodePudding user response:

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 observe needed attribute you can use methodInfo.ReturnTypeCustomAttributes.GetCustomAttributes(true).

CodePudding user response:

Get the first generic argument of the return type, then see if it is of type Nullabe<>:

if(typeof(IMyInterface).GetMethods()[0].ReturnType
     .GetGenericArguments()[0].GetGenericTypeDefinition() == typeof(Nullable<>))
{
    //....
}
  • Related