user256034
user256034

Reputation: 4369

How to get a value from attribute?

Let's have a attribute with an int paramter in the ctor

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)]
public class EntityBindingAttribute : Attribute
{
    public int I { get; set; }

    public EntityBindingAttribute(int i)
    {
        I = i;
    }
}

How can I access this value using code ?

Upvotes: 1

Views: 250

Answers (2)

Fung
Fung

Reputation: 7750

// Get all the attributes for the class
Attribute[] _attributes = Attribute.GetCustomAttributes(typeof(NameOfYourClass));

// Get a value from the first attribute of the given type assuming there is one
int _i = _attributes.Where(_a => _a is EntityBindingAttribute).First().I;

Upvotes: 1

Simon Mourier
Simon Mourier

Reputation: 138841

You would use the Attribute.GetCustomAttributes Method, with the overload that matches the object where the attribute has been set.

For example if the attribute is set on a method, something like:

MethodInfo mInfo = myClass.GetMethod("MyMethod");
foreach(Attribute attr in Attribute.GetCustomAttributes(mInfo))
{
   if (attr.GetType() == typeof(EntityBindingAttribute))
   {
     int i = ((EntityBindingAttribute)attr).I);
    }
}

Upvotes: 3

Related Questions