Search code examples
c#.netcustom-attributescodesmith

Are There Reasons To Not Use CustomAttributes?


This is mostly a request for comments if there is a reason I should not go down this road.

I have a multi-tierd, CodeSmith generated application. At the UI level there need to be some fields that are required, and the required fields will vary depending on field values in the bound entity. What I am thinking of doing is adding a "PropertyRequired" CustomAttribute to each property in the entities that I can set true or false when I load the entity in its manager. Then I will use Reflection to query the property and give visual feedback to the user at the UI level, and I can validate that all the required properties have a valid value in the manager before I save. I've worked this out as a proof of concept with one property in one entity, but before I try to extend it to the rest of the application I'd like to ask if there is someone with more experience to either tell me to go for it, or why I won't like it when I scale up. If this is a bad idea, or if you can suggest a better approach please offer your opinion.


Solution

  • It is a pretty reasonable way to do it (I've done something very similar before) - but there are always downsides:

    • any code needing the entity will need the extra reference (assuming that the attribute and entity are in different assemblies)
    • the values (unless you are clever about it) must be determined at compile-time
    • you can't use it on entities outside of your control

    In most cases the above aren't a problem. If they are an issue, you might want to support an external metadata model - but unless you need it, this would be overkill. Don't do it unless you must (meaning: go ahead and use attributes; they are usually fine).