Search code examples
c#reflectioncustom-properties

Custom Attribute on property in C#


I have a class Person with two properties

public sealed class Person
{
[Description("This is the first name")]
public string FirstName { get; set; }
[Description("This is the last name")]
public string LastName { get; set; }
}

In my console application code I'd like to get for each property of each instance the value of the Description Attribute.....

something similar to

Person myPerson = new Person();
myPerson.LastName.GetDescription() // method to retrieve the value of the attribute

Is it possible to do this task? Can someone suggest me a way? Best regards Fab


Solution

  • With exactly that syntax it isn't possible. It is possible by using Expression Trees... For example:

    public static class DescripionExtractor 
    {
        public static string GetDescription<TValue>(Expression<Func<TValue>> exp) 
        {
            var body = exp.Body as MemberExpression;
    
            if (body == null) 
            {
                throw new ArgumentException("exp");
            }
    
            var attrs = (DescriptionAttribute[])body.Member.GetCustomAttributes(typeof(DescriptionAttribute), true);
    
            if (attrs.Length == 0) 
            {
                return null;
            }
    
            return attrs[0].Description;
        }
    }
    

    and then:

    Person person = null;
    string desc = DescripionExtractor.GetDescription(() => person.FirstName);
    

    Note that the value of person is irrelevant. It can be null and everything will work correctly, because person isn't really accessed. Only its type is important.