Note: This is a follow-up to an answer on a previous question.
I\'m decorating a property\'s setter with an Attribute called TestMaxStringLength
You could consider, as an alternative approach, delaying validation until later, thus removing the need to inspect the stack trace.
This example provides an attribute...
public class MaxStringLengthAttribute : Attribute
{
public int MaxLength { get; set; }
public MaxStringLengthAttribute(int length) { this.MaxLength = length; }
}
... a POCO with the attribute applied to a property...
public class MyObject
{
[MaxStringLength(50)]
public string CompanyName { get; set; }
}
... and a utility class stub that validates the object.
public class PocoValidator
{
public static bool ValidateProperties(TValue value)
{
var type = typeof(TValue);
var props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var prop in props)
{
var atts = prop.GetCustomAttributes(typeof(MaxStringLengthAttribute), true);
var propvalue = prop.GetValue(value, null);
// With the atts in hand, validate the propvalue ...
// Return false if validation fails.
}
return true;
}
}