Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all properties with values reflection

I wrote custom property attribute and set it on couple of properties in my class. Now I would like during runtime get only properties which has this attribute, be able to get value of the property as well as values of attribute fields. Could You please help me with this task ? thanks for help

like image 538
gruber Avatar asked Jan 19 '11 15:01

gruber


1 Answers

Here's an example:

void Main()
{
    var myC = new C { Abc = "Hello!" };
    var t = typeof(C);
    foreach (var prop in t.GetProperties())
    {
        var attr = prop.GetCustomAttributes(typeof(StringLengthAttribute), true).Cast<StringLengthAttribute>().FirstOrDefault();
        if (attr != null)
        {
            var attrValue = attr.MaximumLength; // 100
            var propertyValue = prop.GetValue(myC, null); // "Hello!"
        }
    }
}
class C
{
    [StringLength(100)]
    public string Abc {get;set;}
}
like image 173
Tim S. Avatar answered Sep 28 '22 15:09

Tim S.