Reputation: 855
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
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