Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET : Get property name in attribute

[MyAttribute()]
public string Name { get; set; }

In MyAttribute I need to know the name of associated property, is it possible?

EDIT:

I need to use it in text formatting.

like image 352
Feryt Avatar asked May 09 '10 11:05

Feryt


1 Answers

No, this is not possible. Usually you would use reflection to read attributes applied on a given property, so you already know the property. Example:

var properties = typeof(SomeType).GetProperties();
foreach (var property in properties)
{
    var attributes = property.GetCustomAttributes(typeof(MyAttribute), true);
    if (attributes.Count > 0)
    {
        // look at property.Name here
    }
}
like image 93
Darin Dimitrov Avatar answered Oct 16 '22 06:10

Darin Dimitrov