Getting property description attribute

This should work for you:

return properties.Select(p => 
    Attribute.IsDefined(p, typeof(DescriptionAttribute)) ? 
        (Attribute.GetCustomAttribute(p, typeof(DescriptionAttribute)) as DescriptionAttribute).Description:
        p.Name
    ).ToArray();

NOTE: just add using System.Reflection as GetCustomAttribute is an extension method in .Net 4.5

public static Tuple<string,string>[] GetFieldNames<T>(IEnumerable<T> items) where T : class
{
    var result =
        typeof (T).GetProperties()
            .Where(p => SystemTypes.Contains(p.PropertyType) &&p.GetCustomAttribute<DescriptionAttribute>() != null)
            .Select(
                p =>
                    new Tuple<string, string>(p.Name,
                        p.GetCustomAttribute<DescriptionAttribute>().Description));

    return result.ToArray();
}

for earlier version of .Net framework we can use this extension method:

public static class Extension
{
    public static T GetCustomAttribute<T>(this System.Reflection.MemberInfo mi) where T : Attribute
    {
        return mi.GetCustomAttributes(typeof (T),true).FirstOrDefault() as T;
    }
}

This is a generic function you can make use of, if the fieldName has description tag attribute it return the value otherwise it return null.

public string GetDescription<T>(string fieldName)
{
    string result;
    FieldInfo fi = typeof(T).GetField(fieldName.ToString());
    if (fi != null)
    {
        try
        {
            object[] descriptionAttrs = fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
            DescriptionAttribute description = (DescriptionAttribute)descriptionAttrs[0];
            result = (description.Description);
        }
        catch
        {
            result = null;
        }
    }
    else
    {
        result = null;
    }

    return result;
}

Example:

class MyClass {
  public string Name { get; set; }

  [Description("The age description")]
  public int Age { get; set; }
}

string ageDescription = GetDescription<MyClass>(nameof(Age));
console.log(ageDescription) // OUTPUT: The age description

Tags:

C#