asmo asmo - 1 year ago 109
C# Question

How to retrieve Data Annotations from code? (programmatically)

I'm using

to provide validation for my Entity Framework 4.1 project.

For example:

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

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

I need to retrieve the
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 Source

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();


var name = player.GetAttributeFrom<DisplayAttribute>("PlayerDescription").Name;
var maxLength = player.GetAttributeFrom<MaxLengthAttribute>("PlayerName").Length;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download