Click here to Skip to main content
15,169,285 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am writing a custom attribute. I have applied the AttributeUsage attribute to it, restricting its use to properties only. This works fine: trying to use the attribute on a class or method results in a design-time error, which is exactly what I want.

I would like to restrict it further, so it can be used only on properties that return a String. That is to say, it will result in a design-time error if applied to a DateTime or other non-string. Is this kind of precision possible and, if so, how would I do it?

1 solution

Not supported. It doesn't get any more granular than down to a Property. You cannot restrict it to a return type of a property.

There is no way to do this at runtime inside the attribute code either. The attribute doesn't know anything about the item it's been attached to. It only adds metadata to the item.

The only way I know of that can enforce proper usage would be code written in Unit Tests to Refelect the type and make the determination and/or a custom written FxCop rule.
Gregory Gadow 25-Jun-12 13:58pm
That's what I thought, but figured I'd check. Thanks for the answer.
Sergey Alexandrovich Kryukov 25-Jun-12 14:34pm
Correct, a 5. This is not how attributes work. In general, they have many draconian limitations.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900