How to read class attribute at runtime?

I am trying to create a generic method that will read a class attribute and return this value at runtime. How should I do it?

Note. The DomainName attribute belongs to the DomainNameAttribute class.

[DomainName("MyTable")] Public class MyClass : DomainBase {} 

What I'm trying to create:

 //This should return "MyTable" String DomainNameValue = GetDomainName<MyClass>(); 
+91
generics c # custom-attributes
Apr 16 '10 at 21:25
source share
8 answers
 public string GetDomainName<T>() { var dnAttribute = typeof(T).GetCustomAttributes( typeof(DomainNameAttribute), true ).FirstOrDefault() as DomainNameAttribute; if (dnAttribute != null) { return dnAttribute.Name; } return null; } 



UPDATE:

This method can be further generalized to work with any attribute:

 public static class AttributeExtensions { public static TValue GetAttributeValue<TAttribute, TValue>( this Type type, Func<TAttribute, TValue> valueSelector) where TAttribute : Attribute { var att = type.GetCustomAttributes( typeof(TAttribute), true ).FirstOrDefault() as TAttribute; if (att != null) { return valueSelector(att); } return default(TValue); } } 

and use like this:

 string name = typeof(MyClass) .GetAttributeValue((DomainNameAttribute dna) => dna.Name); 
+205
Apr 16 '10 at 21:30
source share

An extension already exists for this.

 namespace System.Reflection { // Summary: // Contains static methods for retrieving custom attributes. public static class CustomAttributeExtensions { public static T GetCustomAttribute<T>(this MemberInfo element, bool inherit) where T : Attribute; } } 

So:

 var attr = typeof(MyClass).GetCustomAttribute<DomainNameAttribute>(false); return attr != null ? attr.DomainName : ""; 
+35
Apr 15 '15 at 1:31 on
source share
 System.Reflection.MemberInfo info = typeof(MyClass); object[] attributes = info.GetCustomAttributes(true); for (int i = 0; i < attributes.Length; i++) { if (attributes[i] is DomainNameAttribute) { System.Console.WriteLine(((DomainNameAttribute) attributes[i]).Name); } } 
+13
Apr 16 2018-10-16T00:
source share

I used Darin Dimitrova to create a general extension to get member attributes for any member in the class (instead of attributes for the class). I post it here because others may find this useful:

 public static class AttributeExtensions { /// <summary> /// Returns the value of a member attribute for any member in a class. /// (a member is a Field, Property, Method, etc...) /// <remarks> /// 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) /// </remarks> /// <example> /// Read System.ComponentModel Description Attribute from method 'MyMethodName' in class 'MyClass': /// var Attribute = typeof(MyClass).GetAttribute("MyMethodName", (DescriptionAttribute d) => d.Description); /// </example> /// <param name="type">The class that contains the member as a type</param> /// <param name="MemberName">Name of the member in the class</param> /// <param name="valueSelector">Attribute type and property to get (will return first instance if there are multiple attributes of the same type)</param> /// <param name="inherit">true to search this member inheritance chain to find the attributes; otherwise, false. This parameter is ignored for properties and events</param> /// </summary> public static TValue GetAttribute<TAttribute, TValue>(this Type type, string MemberName, Func<TAttribute, TValue> 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 example:

 //Read System.ComponentModel Description Attribute from method 'MyMethodName' in class 'MyClass' var Attribute = typeof(MyClass).GetAttribute("MyMethodName", (DescriptionAttribute d) => d.Description); 
+4
Nov 26 '13 at 12:00
source share

Here is a good tutorial if you have not seen it before http://msdn.microsoft.com/en-us/library/aa288454(VS.71).aspx

In particular, you are interested in a section called Accessing the Attribute http://msdn.microsoft.com/en-us/library/aa288454(VS.71).aspx#vcwlkattributestutorialanchor3

+2
Apr 16 '10 at 21:27
source share

A simplified version of the decision of Darin Dimitrova:

 public string GetDomainName<T>() { var dnAttribute = typeof(T).GetCustomAttribute<DomainNameAttribute>(true); if (dnAttribute != null) { return dnAttribute.Name; } return null; } 
+2
Mar 26 '15 at 0:26
source share
 ' Simplified Generic version. Shared Function GetAttribute(Of TAttribute)(info As MemberInfo) As TAttribute Return info.GetCustomAttributes(GetType(TAttribute), _ False).FirstOrDefault() End Function ' Example usage over PropertyInfo Dim fieldAttr = GetAttribute(Of DataObjectFieldAttribute)(pInfo) If fieldAttr IsNot Nothing AndAlso fieldAttr.PrimaryKey Then keys.Add(pInfo.Name) End If 

It's probably just as easy to use the body of a generic inline function. It makes no sense to me to make a function common to a MyClass type.

 string DomainName = GetAttribute<DomainNameAttribute>(typeof(MyClass)).Name // null reference exception if MyClass doesn't have the attribute. 
0
Apr 14 '15 at
source share

In case someone needs a nullable result and it will work in Enums, PropertyInfo and classes, this is how I solved it. This is a modification of the updated solution Darina Dimitrova.

 public static object GetAttributeValue<TAttribute, TValue>(this object val, Func<TAttribute, TValue> valueSelector) where TAttribute : Attribute { try { Type t = val.GetType(); TAttribute attr; if (t.IsEnum && t.GetField(val.ToString()).GetCustomAttributes(typeof(TAttribute), true).FirstOrDefault() is TAttribute att) { // Applies to Enum values attr = att; } else if (val is PropertyInfo pi && pi.GetCustomAttributes(typeof(TAttribute), true).FirstOrDefault() is TAttribute piAtt) { // Applies to Properties in a Class attr = piAtt; } else { // Applies to classes attr = (TAttribute)t.GetCustomAttributes(typeof(TAttribute), false).FirstOrDefault(); } return valueSelector(attr); } catch { return null; } } 

Examples of using:

 // Class SettingsEnum.SettingGroup settingGroup = (SettingsEnum.SettingGroup)(this.GetAttributeValue((SettingGroupAttribute attr) => attr.Value) as SettingsEnum.SettingGroup?); // Enum DescriptionAttribute desc = settingGroup.GetAttributeValue((DescriptionAttribute attr) => attr) as DescriptionAttribute; // PropertyInfo foreach (PropertyInfo pi in this.GetType().GetProperties()) { string setting = ((SettingsEnum.SettingName)(pi.GetAttributeValue((SettingNameAttribute attr) => attr.Value) as SettingsEnum.SettingName?)).ToString(); } 
0
Jun 14 '19 at 19:45
source share



All Articles