0

I have a class Person that has custom attributes (Header).

[AttributeUsage(AttributeTargets.Property)]
public class Header : Attribute
{
    public string Name { get; set; }


}
public class Person
{
    [Header(Name = "First Name")]
    public string FirstName { get; set; }

    [Header(Name = "Last Name")]
    public string LastName { get; set; }
    public Person(string first, string last)
    {
       FirstName = first;
       LastName = last;
    }

}

I want to create a method that can return all attributes of an object in a list

Person person = new Person("first", "last");
//List<string> attributes = GetAttributes(person);
// output:
//     - "First Name", "Last Name"
tuai
  • 11
  • 1
  • https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/reflection –  Nov 06 '22 at 09:57
  • 1
    Does this answer your question? [How do I read an attribute on a class at runtime?](https://stackoverflow.com/questions/2656189/how-do-i-read-an-attribute-on-a-class-at-runtime) – Vivek Nuna Nov 06 '22 at 09:58
  • @viveknuna this doesn't work in my example could it be because i use my attribute with a property and the other with a class? – tuai Nov 06 '22 at 10:12
  • @tuai You might want to look at https://stackoverflow.com/questions/6637679/reflection-get-attribute-name-and-value-on-property – Progman Nov 06 '22 at 10:27
  • Or just inline it: `var attrNames = typeof(Person).GetProperties().OfType().SelectMany(p => p.CustomAttributes.SelectMany(a => a.NamedArguments).Select(na => na.TypedValue.Value).ToList()).ToList();` -- or `person.GetType()` – Jimi Nov 06 '22 at 10:37

0 Answers0