Reputation: 29779
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
Upvotes: 5
Views: 19967
Reputation: 56566
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;}
}
Upvotes: 16