John Kline Kurtz
John Kline Kurtz

Reputation: 855

Get class and instance DescriptionAttribute values

How do you retrieve the DescriptionAttribute of an instance of a class and of the class itself?

[Description("The Help class description")]
public class Help
{
    //...
}

public class General
{
    [Description("The Help instance description")]
    public Help ThisHelp {get; set;} = new Help();
}

public static class Program
{
    static void Main()
    {
        General MyGeneral = new General();
        var Atts = MyGeneral.ThisHelp.GetType().GetCustomAttributes(typeof(DescriptionAttribute), true);
        Console.WriteLine(string.Join(Environment.NewLine, Atts.OfType<DescriptionAttribute>().Select(a => a.Description)));
        //Only writes "The Help class description" ... But not the instance
    }
}

I get the class version only.

Upvotes: 0

Views: 733

Answers (1)

41686d6564
41686d6564

Reputation: 19661

It's not the attribute of the instance, per se, since instances don't have attributes. It's the attribute of the property. So, you need to have a MemberInfo of the target property in order to get its attributes, not just the attributes of the Help type.

Try something like this:

var propertyAtts = MyGeneral.GetType().GetProperty("ThisHelp")
                        .GetCustomAttributes(typeof(DescriptionAttribute), true);

You could also use typeof(General) instead of MyGeneral.GetType() in case you don't have an instance of General. Similarly, for the class attributes, you may use typeof(Help) instead of MyGeneral.ThisHelp.GetType().

Upvotes: 1

Related Questions