Click here to Skip to main content
14,209,090 members
Rate this:
Please Sign up or sign in to vote.
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?
Posted

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

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.
   
Comments
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.
--SA

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



Advertise | Privacy | Cookies | Terms of Service
Web03 | 2.8.190617.2 | Last Updated 25 Jun 2012
Copyright © CodeProject, 1999-2019
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100