Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting property description attribute

Tags:

c#

Existing code (simplified)

I have this function

public static string[] GetFieldNames<T>(IEnumerable<T> items)
  where T : class
{
  var properties = typeof(T).GetProperties().Where(p => SystemTypes.Contains(p.PropertyType)); // Only get System types

  return properties.Select(p => p.Name).ToArray();
}

So if say I have this class

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

  [Description("The value")]
  public int Value { get; set; }
}

I can have code like this

List<MyClass> items = ...; // Populate items somehow
string[] fieldNames = GetFieldNames(items); // This returns ["Name", "Value"]

That works fine.

The problem

I need to get the Description (if it exists), so that GetFieldNames(items) returns ["Name", "The value"]

How do I modify the GetFieldNames() function to read the Description attribute if it exists?
(Please note that this function has been simplified, the real function is much more complex, so please avoid changing the logic)

like image 507
Aximili Avatar asked Oct 14 '14 05:10

Aximili


People also ask

What is description attribute?

Use the description [description] attribute to tell customers about your product. List product features, technical specifications, and visual attributes. A detailed description will help us show your product to the right customers.

What is Description C#?

The Description attribute decoration is used to define a descriptive name for a give property or event. It can be used with either enum elements or with any user defined data type property or event. The description decoration is defined under the System.

How do I add attributes to my property at runtime?

It is not possible to add Attributes in run-time. Attributes are static and cannot be added or removed.

Does Getcustomattribute use reflection?

Use reflection to get information defined with custom attributes in C# by using the GetCustomAttributes method.


3 Answers

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();
like image 123
Diligent Key Presser Avatar answered Oct 16 '22 09:10

Diligent Key Presser


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;
    }
}
like image 4
user3473830 Avatar answered Oct 16 '22 08:10

user3473830


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
like image 3
Shahar Shokrani Avatar answered Oct 16 '22 07:10

Shahar Shokrani