Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to access the Description attribute on either a property or a const in C#?
    primarykey
    data
    text
    <p>How do you access the Description property on either a const or a property, i.e.,</p> <pre><code>public static class Group { [Description( "Specified parent-child relationship already exists." )] public const int ParentChildRelationshipExists = 1; [Description( "User is already a member of the group." )] public const int UserExistsInGroup = 2; } </code></pre> <p>or</p> <pre><code>public static class Group { [Description( "Specified parent-child relationship already exists." )] public static int ParentChildRelationshipExists { get { return 1; } } [Description( "User is already a member of the group." )] public static int UserExistsInGroup { get { return 2; } } } </code></pre> <p>In the calling class I'd like to access the Description property, i.e.,</p> <pre><code>int x = Group.UserExistsInGroup; string description = Group.UserExistsInGroup.GetDescription(); // or similar </code></pre> <p>I'm open to ideas to other methodologies as well.</p> <p><strong>EDIT:</strong> I should have mentioned that I've seen an example provided here: <a href="https://stackoverflow.com/questions/464889/does-auto-implemented-properties-support-attributes">Do auto-implemented properties support attributes?</a></p> <p>However, I'm looking for a method to access the description attribute without having to enter a string literal into the property type, i.e., I'd rather not do this:</p> <pre><code>typeof(Group).GetProperty("UserExistsInGroup"); </code></pre> <p>Something along the lines of an Extension Method; similar to the following method that will return the Description attribute on an Enum via an Extension Method:</p> <pre><code>public static String GetEnumDescription( this Enum obj ) { try { System.Reflection.FieldInfo fieldInfo = obj.GetType().GetField( obj.ToString() ); object[] attribArray = fieldInfo.GetCustomAttributes( false ); if (attribArray.Length &gt; 0) { var attrib = attribArray[0] as DescriptionAttribute; if( attrib != null ) return attrib.Description; } return obj.ToString(); } catch( NullReferenceException ex ) { return "Unknown"; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload