Arsen Mkrtchyan
Arsen Mkrtchyan

Reputation: 50752

How to get attribute on property in property get or set body

Is it possible to get attribute on property in property get or set body without StackFrame?

for example

[SomeAttribute]
public int SomeProp
{
    get
    {
        //Get of SomeAttribute is set on this property
    }
    set
    {
        //Get of SomeAttribute is set on this property
    }
}

Upvotes: 1

Views: 687

Answers (1)

Jahan Zinedine
Jahan Zinedine

Reputation: 14874

You can write a function like this and get the property name by an expression not by string lliterals

public string Item(this T obj, Expression<Func<T, object>> expression) 
{
    if (expression.Body is MemberExpression)
    {
        return ((MemberExpression)expression.Body).Member.Name;
    }
    if (expression.Body is UnaryExpression)
    {
        return ((MemberExpression)((UnaryExpression)expression.Body).Operand).Member.Name;
    }
    throw new InvalidOperationException();
}

Usage:

public int SomeProp
{
  get 
  { 
     var attribs = 
           this.GetType().GetProperty(this.Item(o => o.SomeProp)).Attributes;
  }
}

Upvotes: 1

Related Questions