Retrieve custom attribute parameter values?

Rush Frisby picture Rush Frisby · Oct 13, 2010 · Viewed 16.6k times · Source

if i have created an attribute:

public class TableAttribute : Attribute {
    public string HeaderText { get; set; }
}

which i apply to a few of my properties in a class

public class Person {
    [Table(HeaderText="F. Name")]
    public string FirstName { get; set; }
}

in my view i have a list of people which i am displaying in a table.. how can i retrieve the value of HeaderText to use as my column headers? Something like...

<th><%:HeaderText%></th>

Answer

Jon Skeet picture Jon Skeet · Oct 13, 2010

In this case, you'd first retrieve the relevant PropertyInfo, then call MemberInfo.GetCustomAttributes (passing in your attribute type). Cast the result to an array of your attribute type, then get at the HeaderText property as normal. Sample code:

using System;
using System.Reflection;

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

public class Person
{
    [Table(HeaderText="F. Name")]
    public string FirstName { get; set; }

    [Table(HeaderText="L. Name")]
    public string LastName { get; set; }
}

public class Test 
{
    public static void Main()
    {
        foreach (var prop in typeof(Person).GetProperties())
        {
            var attrs = (TableAttribute[]) prop.GetCustomAttributes
                (typeof(TableAttribute), false);
            foreach (var attr in attrs)
            {
                Console.WriteLine("{0}: {1}", prop.Name, attr.HeaderText);
            }
        }
    }
}