Is there a way to detect the notnull constraint via reflection on a generic method?

117 Views Asked by At

When trying to get constraints applied to a generic method with reflection, after calling GetGenericArguments on the MethodInfo, if I use GenericParameterAttributes I get None and GetGenericParameterConstraints returns an empty Type[] when there's only a notnull constraint.

I have tried finding differences in the generated IL and (from what I understand) there's only a NullableAttribute (from System.Runtime.ComplierServices) applied to either the generic method, its declaring type or the type parameter that has the notnull constraint depending on the definition of the class nor method.

Since the attribute's location is not always the same and I'm pretty sure there are others ways it can appear I don't think looking for this attribute is a reliable solution.

Is there something more that can tell me a type parameter has the notnull constraint using reflection?

1

There are 1 best solutions below

0
Blindy On

how to make the difference between public void GenericMethod<T>() and public void GenericMethod<T>() where T : notnull (sic)

Finally, a piece of code.

Well a quick look does show the Nullable attribute on generic types in that case, but you have to keep in mind that generic constraints are compile-time features, they have only incidental IL code generated. Work with that if you wish, you already got there.

I will reiterate however that what you're looking for is compile-time data, and you already have a strong foundation for that: source generators. You can easily write a source generator that looks through your types and builds a public static array of whatever meta-data you wish by just parsing the syntax tree and finding your notnull constraints.