Force usage of custom attribute

No, there is no way to have the compiler require an attribute in C#. You do have some other options available to you. You could write a unit test that reflects on all types in the assembly and checks for the attribute. But unfortunately there is no way to have the compiler force the usage of an attribute.


No longer relevant to the original poster I imagine, but here's something for anyone who's curious like I was if this was doable.

The following works, but sadly it's not a compile-time check and as such I can't honestly recommend it used. You're better off with interfaces, virtuals and abstracts for most things.

The required attribute:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class RequiredRandomThingAttribute : Attribute { /* ... */ }

Parent class that requires it for derived classes:

public class ParentRequiringAttribute
{
    public ParentRequiringAttribute()
    {
        if (this.GetType().GetCustomAttributes(typeof(RequiredRandomThingAttribute), false).Length == 0)
            throw new NotImplementedException(this.GetType().ToString());
    }
}

And to confirm it all works:

[RequiredRandomThing()]
public class CompleteSubclass : ParentRequiringAttribute { /* ... */ }

public class IncompleteSubclass : ParentRequiringAttribute { /* ... */ }

static public int Main(string[] args)
{
    var test1 = new CompleteSubclass();
    var test2 = new IncompleteSubclass(); // throws
}

It should be fairly easy to improve the validation, but my own investigation stopped here.

Tags:

C#

Attributes