Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# attribute usage: only allow attributes on a property with specific data type [duplicate]

I've created a few attributes for properties. now I want to limit these attributes to properties with a certain data type? the idea is, a compiler error will be thrown if it is assign to a different type. is this possible?

if not, then I guess i'll have to check it on runtime.

like image 923
Mel Avatar asked Dec 20 '11 10:12

Mel


2 Answers

You could write a custom FxCop/ Code Analysis rule to check for this.

FxCop is integrated in VS 2010 under the name "Code Analyis", you can change the ruleset in the project properties.

like image 146
BrokenGlass Avatar answered Oct 14 '22 05:10

BrokenGlass


No, this is not possible.

A good workaround is to build a unit test which will traverse all classes, their properties and check for this additional applicability criteria. It's not that comfortable as a compile-time error message, but will serve the purpose. In case you have some kind of build automation infrastructure, the quality assurance level will be the same in practice.

like image 41
Ondrej Tucny Avatar answered Oct 14 '22 05:10

Ondrej Tucny