More C# Attribute annoyances


And on the subject of the deficiencies of attributes, there are a few more things I’d like to accomplish, but cant.  First on the list, generic attributes:

// Boo C# compiler, boo!!!
public class GenericAttribute<T> : Attribute

So many times I’d like to have some kind of generic attribute, whether for validation, for action filters, the list goes on and on:

error CS0698: A generic type cannot derive from 'Attribute' because it is an attribute class

Well that’s helpful!  It gets worse.  Let’s try a more interesting attribute value for an attribute that takes a value in its constructor:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class FineThenAttribute : Attribute
{
    public FineThenAttribute(int value)

Most of the time, I’ll put a hard-coded value into the constructor.  Sometimes, I’d like for that value to come from…somewhere else:

public class PrettyPlease
{
    public const int Five = 5;
    public static int Four = 4;

    [FineThen(6)]
    [FineThen(Five)]
    [FineThen(Four)]
    public void Method()

The first two compile just fine, as the values passed in are constant values.  The third attribute does NOT compile, however.  I get yet another roadblock:

error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

One time I tried to get extra fancy with attribute decorators.  Silly me!  This attribute definition compiles just fine:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class DelegateTypeAttribute : Attribute
{
    public DelegateTypeAttribute(Action jackson)

But it’s impossible to use!  None of these attribute declarations compile:

public class WithACherryOnTop
{
    [DelegateType(() => { })]
    [DelegateType(MatchesAction)]
    [DelegateType(new Action(MatchesAction))]
    public void Method()
    {
    }

    private static void MatchesAction()

Blech.  Every time I try and do something mildly interesting with attributes, blocked by the CLR!

Attributes are lousy decorators