Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve custom attribute parameter values?

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>
like image 342
Rush Frisby Avatar asked Oct 13 '10 16:10

Rush Frisby


2 Answers

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);
            }
        }
    }
}
like image 125
Jon Skeet Avatar answered Oct 16 '22 05:10

Jon Skeet


Jon Skeet's solution is good if you allow multiple attributes of the same type to be declared on a property. (AllowMultiple = true)

ex:

[Table(HeaderText="F. Name 1")]
[Table(HeaderText="F. Name 2")]
[Table(HeaderText="F. Name 3")]
public string FirstName { get; set; }

In your case, I would assume you only want one attribute allowed per property. In which case, you can access the properties of the custom attribute via:

var tableAttribute= propertyInfo.GetCustomAttribute<TableAttribute>();
Console.Write(tableAttribute.HeaderText);
// Outputs "F. Name" when accessing FirstName
// Outputs "L. Name" when accessing LastName
like image 44
ScubaSteve Avatar answered Oct 16 '22 06:10

ScubaSteve