0

We have an existing custom class that inherits from ValidationAttribute. This class does some basic validation on enum property values on our c# data model classes.

The constructor for the attribute class takes a Type parameter that is intended to match the type of the field that the attribute is applied to.

I would like to get the type of the field that has the attribute on it without having to pass it in as a parameter to the attribute.

Is this something that can be done easily?

GaTechThomas
  • 5,421
  • 5
  • 43
  • 69

2 Answers2

3

Is this something that can be done easily?

No, it's something that can't be done at all, unfortunately. The attribute doesn't have access to the member on which it is applied.

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
1

You can't do this from within the attribute easily. You have to use reflection to get the class, and its properties, which are decorated BY the attribute, and from there you have access to both. From within the attributes code you don't know which object(s) are its target, and so cannot get access to their PropertyInfos

Community
  • 1
  • 1
RyanR
  • 7,728
  • 1
  • 25
  • 39
  • but for that, you need an already existing handle to the type... which you seem to be agreeing isn't possible from inside the attribute. – DrewJordan May 22 '15 at 20:02