Reputation: 18068
I have a class with ~400 string properties(it's auto-generated) I would like to apply [StringLength(50)]
to all properties within the class. Is that is possible without copy-pasting the attribute 400 times?
Upvotes: 0
Views: 218
Reputation: 1
There is a way to do it using reflection, but this approach will apply the attributes at runtime, not at compile time.
public static void AddStringLengthAttribute(Type type, int maxLength)
{
var properties = type.GetProperties();
foreach (var property in properties)
{
var attribute = new StringLengthAttribute(maxLength);
property.SetCustomAttribute(attribute);
}
}
Then you can call AddStringLengthAttribute(typeof(YourClass), 50);
Upvotes: 1