How to apply at once StringLength attribute to all properties within the class?

168 views Asked by At

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?

1

There are 1 answers

0
Vivek Nuna On

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