🔧 C#: Fix a Generic Attribute Losing Its Type Argument at Runtime
C# 11’s generic attributes let you write [Validates<Foo>], but reflecting on them at runtime means the applied attribute’s actual type is the closed generic ValidatesAttribute<Foo>, not the open generic definition — calling a non-generic lookup method looking for the open definition finds nothing at all, returning null even though the attribute is clearly visible in source and IntelliSense, because the lookup was never looking for the right closed type to begin with.
🔎 The Problem
public class ValidatesAttribute<T> : Attribute { }
[Validates<CustomerDto>]
public class CustomerValidator { }
var attr = typeof(CustomerValidator)
.GetCustomAttribute<ValidatesAttribute>(); // wrong: no type argument
// attr is null - ValidatesAttribute (open) never matches
// ValidatesAttribute<CustomerDto> (the actual applied, closed type)
✅ Fix: Match on the Open Generic Definition, or the Exact Closed Type
- When the type argument isn’t known ahead of time, use
GetCustomAttributes(inherit: true)and filter by checkingattr.GetType().IsGenericType && attr.GetType().GetGenericTypeDefinition() == typeof(ValidatesAttribute<>), rather than calling a generic method with an unknown type argument. - If the specific closed type is known at the call site, use
GetCustomAttribute<ValidatesAttribute<CustomerDto>>()with the exact same type argument used at the application site — the open generic definition will never match a closed instance. - Consider having the generic attribute implement a shared non-generic marker interface, or expose its type argument as a
Typeproperty, specifically so reflection code that doesn’t know it ahead of time has a non-generic way to find and inspect it.
🚨 Why This Is Dangerous
- Validation, serialization, or DI registration logic that silently finds “no attribute” because of a reflection lookup mismatch doesn’t throw — it just skips whatever behavior the attribute was supposed to trigger, which can look like the feature was never implemented rather than a lookup bug.
[Validates<Foo>] is not an instance of ValidatesAttribute at runtime — it’s an instance of ValidatesAttribute<Foo>, and reflection only finds what you actually ask for.




