Reading an attribute C# with Example



Reading an attribute C# with Example

Method GetCustomAttributes returns an array of custom attributes applied to the member. After retrieving this 
array you can search for one or more specific attributes. 
var attribute = typeof(MyClass).GetCustomAttributes().OfType().Single(); 
Or iterate through them 
foreach(var attribute in typeof(MyClass).GetCustomAttributes()) { 
Console.WriteLine(attribute.GetType()); 
} 
GetCustomAttribute extension method from System.Reflection.CustomAttributeExtensions retrieves a custom 
attribute of a specified type, it can be applied to any MemberInfo. 
var attribute = (MyCustomAttribute) typeof(MyClass).GetCustomAttribute(typeof(MyCustomAttribute)); 
GetCustomAttribute also has generic signature to specify type of attribute to search for. 
var attribute = typeof(MyClass).GetCustomAttribute(); 
Boolean argument inherit can be passed to both of those methods. If this value set to true the ancestors of 
element would be also to inspected. 
 

0 Comment's

Comment Form

Submit Comment