Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What use have attributes on generic parameters?

It is valid (ie. it compiles and runs) to put an attribute on the generic parameter for a class or a method:

public class MyClass<[My] T>
{
    private void MyMethod<[My] T>()
    {}
}

public class MyAttribute : Attribute
{}

I've never seen this used, and am struggling to come up with a reason as to why you would want to.

Is it just a quirk/side-effect of the language specification, or is there a valid/useful reason to put an attribute in this position?

like image 389
adrianbanks Avatar asked Jan 31 '11 18:01

adrianbanks


2 Answers

For the same reason attributes are useful on any construct; they supply meta-data that can be used by Reflection or other post-processors to do various things. For instance, you might have an AOP system that uses an attribute on a type argument to apply certain run-time constraints that otherwise could not be expressed. I'm not sure if there are any systems that actually use these attributes to do anything, but there's no reason to disallow them as metadata.

like image 96
Dan Bryant Avatar answered Oct 04 '22 13:10

Dan Bryant


I'm sure some AOP nut will find a valid reason to decorate generic parameters with attributes. I certainly can't think of any. Try this:

typeof(MyClass<>).GetGenericArguments().GetCustomAttributes().OfType<MyAttribute>();

If this Enumerable has any elements, then it is possible to access the attribute you placed on the class's generic parameter. If not, then you can't and thus having data you'd expect to access from any other class in your codebase is pointless. HOWEVER, they can still have code that runs when instantiated, and they're instantiated by the runtime when the generic class comes into scope, allowing you to perform aspect-oriented logic in the attribute itself. Exactly what that would be, and how it would be any different than decorating the generic class or method directly, is left as an exercise to people who worship AOP far more than I do.

like image 29
KeithS Avatar answered Oct 04 '22 15:10

KeithS