Nerdy tidbits from my life as a software engineer

Friday, April 24, 2009

Attributes Can’t Be Generic

This is a bit of a bummer.  Attributes can’t have generic arguments.  IE,

public class InputAttribute<T> : Attribute
{
}
is not legal, and fails to compile with the message, “A generic type cannot derive from 'Attribute' because it is an attribute class.”  What stinks about this is that it means there is no way to add generic type requirements to a generic attribute, such as where T : ISomeInterface.  And that’s a bummer, because I’d like to be able to strongly type a type argument of a generic, instead of leaving it up the consumer to do the right thing.  In other words, change this:
public class InputAttribute : Attribute
{
public InputAttribute(Type inputType)
{
...
}
}
…into this…
public class InputAttribute<T> : Attribute where T : ISomeInterface
{
}
But alas, this is not possible.  Back to the drawing board I guess…there must be a better way.

0 comments: