0

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

user2332607
  • 99
  • 1
  • 3
  • 10
  • 10
    http://stackoverflow.com/questions/6637679/reflection-get-attribute-name-and-value-on-property – Nathan Cooper Feb 10 '16 at 12:23
  • With that syntax no, it isn't possible. With other syntaxes it is possible (as shown for example in the linked question) – xanatos Feb 10 '16 at 12:25

2 Answers2

3

The .LastName returns a string, so you can't do much from there. Ultimately, you need the PropertyInfo for this. There are two ways of getting that:

  • via an Expression (perhaps SomeMethod<Person>(p => p.LastName))
  • from a string (perhaps via nameof)

For example, you could do something like:

var desc = Helper.GetDescription<Person>(nameof(Person.LastName));

or

var desc = Helper.GetDescription(typeof(Person), nameof(Person.LastName));

with something like:

var attrib = (DescriptionAttribute)Attribute.GetCustomAttribute(
    type.GetProperty(propertyName), typeof(DescriptionAttribute));
return attrib?.Description;
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
0

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.

xanatos
  • 109,618
  • 12
  • 197
  • 280