Query Constraints

Aug 30, 2011 at 6:47 AM

Is there a way to query Constraints on a type?


e.g. how can I get the fact that T must be a struct from this:

public class A<T> where T : struct {} 

Aug 30, 2011 at 10:14 PM

Fasterflect doesn't currently provide anything for this, but you could write something along these lines:

bool hasStructConstraint = type.HasGenericParameters() && type.GetGenericParameters().ToList()

.Where(t =>(t.GenericParameterAttributes & GenericParameterAttributes.NotNullableValueTypeConstraint) == GenericParameterAttributes.NotNullableValueTypeConstraint)

.Count() > 0;

See MSDN for more info :o)