how to force which types custom attribute can be used with?

P

Pawe³

Hi!
I want to create my own custom attribute. And want it to be used only to
attribute class that inherrits from System.Windows.Forms.Control. Is it
possible to specify such constraint?.. If it is not possible in
compile-time, maybe I can check it in run-time, but I do not know how to
access atrributed type from Attribute constructor (and maybe throw some
exception).

Grtx
Paul
 
D

Daniel O'Connell [C# MVP]

Pawe3 said:
Hi!
I want to create my own custom attribute. And want it to be used only to
attribute class that inherrits from System.Windows.Forms.Control. Is it
possible to specify such constraint?.. If it is not possible in
compile-time, maybe I can check it in run-time, but I do not know how to
access atrributed type from Attribute constructor (and maybe throw some
exception).

No, its not possible to constrain an attribute to a given type. I also do
not think it is possible to check the applied type at runtime.

You could write an fxcop rule to achieve such, however, and integrate fxcop
into your build process.
 
S

Steven Cheng[MSFT]

Hi Paul,

Thank you for your posting. Regarding on the issue, I am
finding proper resource to assist you and we will update as soon as posible.

Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security(This posting is provided "AS IS",
with no warranties, and confers no rights.)
 
K

Kevin Yu [MSFT]

Thanks for Daniel's quick response!

Hi Paul,

First of all, I would like to confirm my understanding of your issue. From
your description, I understand that you need to create your own attribute
and apply it to certain classes. And you need the attribute cannot be
applied to classes other than those inherited from
System.Windows.Form.Control. If there is any misunderstanding, please feel
free to let me know.

I agree with Daniel's suggestion that we cannot check this constraint in
.NET framework. attributes can be applied to any class definitions. So I
think using fxcop might be the best workaround. FxCop can be downloaded
from the following link:

http://www.gotdotnet.com/team/fxcop/

HTH.

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top