How to retrieve Data Annotations from code? (programmatically)

asmo picture asmo · Aug 11, 2011 · Viewed 47.1k times · Source

I'm using System.ComponentModel.DataAnnotations to provide validation for my Entity Framework 4.1 project.

For example:

public class Player
{
    [Required]
    [MaxLength(30)]
    [Display(Name = "Player Name")]
    public string PlayerName { get; set; }

    [MaxLength(100)]
    [Display(Name = "Player Description")]
    public string PlayerDescription{ get; set; }
}

I need to retrieve the Display.Name annotation value to show it in a message such as The chosen "Player Name" is Frank.

=================================================================================

Another example of why I could need to retrieve annotations:

var playerNameTextBox = new TextBox();
playerNameTextBox.MaxLength = GetAnnotation(myPlayer.PlayerName, MaxLength);

How can I do that?

Answer

jgauffin picture jgauffin · Aug 11, 2011

Extension method:

public static T GetAttributeFrom<T>(this object instance, string propertyName) where T : Attribute
{
    var attrType = typeof(T);
    var property = instance.GetType().GetProperty(propertyName);
    return (T)property .GetCustomAttributes(attrType, false).First();
}

Code:

var name = player.GetAttributeFrom<DisplayAttribute>(nameof(player.PlayerDescription)).Name;
var maxLength = player.GetAttributeFrom<MaxLengthAttribute>(nameof(player.PlayerName)).Length;