1

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?

MW_dev
  • 2,146
  • 1
  • 26
  • 40

4 Answers4

1

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

Community
  • 1
  • 1
Fredrik Kalseth
  • 13,934
  • 4
  • 25
  • 17
0

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
  • 26,748
  • 16
  • 78
  • 122
0

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
  • 37,282
  • 14
  • 64
  • 100
0

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

Oliver Friedrich
  • 9,018
  • 9
  • 42
  • 48