Custom Attributes C# with Example



Custom Attributes C# with Example

Find properties with a custom attribute - MyAttribute 
var props = t.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | 
BindingFlags.Instance).Where( 
prop => Attribute.IsDefined(prop, typeof(MyAttribute))); 
Find all custom attributes on a given property 
var attributes = typeof(t).GetProperty("Name").GetCustomAttributes(false); 
Enumerate all classes with custom attribute - MyAttribute 
static IEnumerable GetTypesWithAttribute(Assembly assembly) { 
foreach(Type type in assembly.GetTypes()) { 
if (type.GetCustomAttributes(typeof(MyAttribute), true).Length > 0) { 
yield return type; 
} 
} 
} 
Read value of a custom attribute at runtime 
public static class AttributeExtensions 
{ 
///  
/// Returns the value of a member attribute for any member in a class. 
/// (a member is a Field, Property, Method, etc...) 
///   
/// If there is more than one member of the same name in the class, it will return the first 
one (this applies to overloaded methods) 
///   
///  
/// Read System.ComponentModel Description Attribute from method 'MyMethodName' in class 
'MyClass': 
/// var Attribute = typeof(MyClass).GetAttribute("MyMethodName", (DescriptionAttribute d) 
=> d.Description); 
///  
/// The class that contains the member as a type 
/// Name of the member in the class 
/// Attribute type and property to get (will return first 
instance if there are multiple attributes of the same type) 
/// true to search this member's inheritance chain to find the 
attributes; otherwise, false. This parameter is ignored for properties and events 
///  
public static TValue GetAttribute(this Type type, string MemberName, 
Func valueSelector, bool inherit = false) where TAttribute : Attribute 
{ 
var att = 
type.GetMember(MemberName).FirstOrDefault().GetCustomAttributes(typeof(TAttribute), 
inherit).FirstOrDefault() as TAttribute; 
if (att != null) 
{ 
return valueSelector(att); 
} 
return default(TValue); 
} 
 

} 
Usage 
//Read System.ComponentModel Description Attribute from method  'MyMethodName'  in  class  'MyClass' 
var Attribute = typeof(MyClass).GetAttribute("MyMethodName", (DescriptionAttribute d) => 
d.Description); 

0 Comment's

Comment Form

Submit Comment