user396716
user396716

Reputation:

How to get attributes value

I have this code:

[MyAttribute(CustomAttribute="Value")]
class MyClass
{
    // some code
}


Main()
{
    MyClass a = new MyClass();
}

How to get value of CustomAttribute for instance a?

Upvotes: 7

Views: 321

Answers (3)

Jamiec
Jamiec

Reputation: 136174

Along the lines of:

MyAttribute [] myAttributes 
  = (MyAttribute [])a.GetType().GetCustomAttributes(typeof(MyAttribute),true);

Can't understand what you mean by "without using foreach", except that GetCustomAttributes always returns an array of them (to account for having multiple attributes). If you know there can only be one, then just use the first one.

MyAttribute theAttrib = myAttributes[0];
Console.WriteLine(theAttrib.CustomAttribute);

Upvotes: 3

Tim Robinson
Tim Robinson

Reputation: 54764

var attribs = (MyAttributeAttribute[]) typeof(MyClass).GetCustomAttributes(
    typeof(MyAttributeAttribute), 
    true);

Console.WriteLine(attribs[0].CustomAttribute); // prints 'Value'

Upvotes: 1

Adam Houldsworth
Adam Houldsworth

Reputation: 64527

There is a good sample here:

http://msdn.microsoft.com/en-us/library/z919e8tw.aspx

To do this without a foreach you would have to assume there are no other attributes being applied to the type, and index the first attribute directly.

Upvotes: 3

Related Questions