tags:

views:

116

answers:

4

I am wondering if it is possible to validate parameters to (custom) .net attributes. eg: If I had an attribute that takes a positive integer, could I force a compile time error when a negative value was supplied?

[DonkeyAttribute(1)] //OK

[DonkeyAttribute(-828)] //error

In this example I could use an unsigned integer (but that is non cls compliant I beleive?) Recommendations?

A: 

I don't think it is normally, however this article details a solution using PostSharp. Not sure if it's fit for your purpose, but give it go!

Kieron
+1  A: 

You could enforce this with unit tests; a similar solution to the one I proposed for this question, maybe.

Fredrik Kalseth
A: 

Directly? No. Not without rewriting csc or vbc. Most people would perform said validation at runtime.

However, a bit of Googling came up with this blog entry on PostSharp Aspects. It doesn't technically validate from the compiler, but it does provide checking at compile-time. You can check it out here. Other notes about PostSharp from the same author can be found here.

John Rudy
A: 

You can create a custom attribute by inheriting from System.Attribute. In the custom Constructor you should be able to check the parameters.

BeowulfOF