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?
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?
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.
var attribs = (MyAttributeAttribute[]) typeof(MyClass).GetCustomAttributes(
typeof(MyAttributeAttribute),
true);
Console.WriteLine(attribs[0].CustomAttribute); // prints 'Value'
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);