I’m writing an attribute (it’s a ValidatorAttribute) that currently has
[AttributeUsage(AttributeTargets.Property)]
which restricts the type of construct on which the attribute can be placed. It can be applied to any Property that might exist.
I’m wondering if there’s an attribute that will restrict the Type of the Property to which the attribute can be applied. I want to restrict it to be used on DateTime properties.
I can see a couple of options, but they aren’t ideal:
- I can ignore the instance of the attribute by checking the type inside the attribute, but there’s no indication to the developer that the attribute isn’t doing anything
- I can throw an exception if the
Typeis incorrect, but for obvious reasons this is just a bad idea.
Ideally I’d get a compile time error, similar to if I put this attribute on anything other than a Property:
Attribute is not valid on this
declaration type. It is only valid on
‘property, indexer’ declarations.
I don’t expect that there is such an attribute, but I’m happy to be wrong. Alternatively has anyone written such an attribute (is it even possible?), or any suggested alternatives?
The only way to enforce this is to write a post-build tool that enumerate all the types in an assembly and verifies if yours were applied to the correct ones. Not much point in doing so, the attribute simply won’t have any effect if it was applied wrong, you just cannot find it back.