tags:

views:

44

answers:

3

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?

+3  A: 

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.

Adam
+1  A: 
var attribs = (MyAttributeAttribute[]) typeof(MyClass).GetCustomAttributes(
    typeof(MyAttributeAttribute), 
    true);

Console.WriteLine(attribs[0].CustomAttribute); // prints 'Value'
Tim Robinson
+2  A: 

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);
Jamiec
"Can't understand what you mean by "without using foreach"" ->I find some bad examples that use foreach to read all attributes value
shandu
Yes, but the bad examples are just that - examples - you should take the knowledge they give and use it how you see fit.
Jamiec