JDBennett JDBennett - 7 months ago 40
C# Question

Require custom enum attribute if enum type has a different custom attribute

The title sums it up. Say I have a custom attribute IsModule defined. It is used for enum types that I use to load all modules.

I.e assembly.GetCustomAttributes(typeof(IsModule), true)

Once I have all enums that have that attribute, I iterate each enum and read a different custom attribute ModuleData so that I can insert it into the database.

What I want to do is make this future developer proof by requiring the ModuleData attribute over each enum value IF the IsModule attribute is present on the type.


There's no immediate language feature to help. However, three alternate options here:

  1. make a Visual Studio (or ReSharper) add-in that will check for this during editing;
  2. make an FXCop rule that will check when static code analysis is run;
  3. make a unit test that will enumerate all assemblies and make the check.

Note that in case of the unit test (option 3) you need to run it in a way that ensures all assemblies of the program are loaded.