Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get property name inside the attribute that declared on it

I have an attribute declared on property. How can I get the property name inside the attribute?

like image 976
Fitzchak Yitzchaki Avatar asked Mar 25 '10 17:03

Fitzchak Yitzchaki


2 Answers

This is backwards. The only possible way you can get the attribute value is through PropertyInfo.GetCustomAttributes(). That requires knowing the property name first so you can get the PropertyInfo object from Type.GetProperty().

like image 33
Hans Passant Avatar answered Sep 20 '22 12:09

Hans Passant


Sorry to say it but you can't. The attribute has no meaning of knowing to what property/class it is applied.

In general attributes alone are useless (they are just metadata decorating your classes), there must be something reading them at runtime and in order to read an attribute you already have a reference to the property this attribute is applied to, so you already know the property name.

like image 164
Darin Dimitrov Avatar answered Sep 19 '22 12:09

Darin Dimitrov