Im constructing metadata about a class. With reflection i iterate over the class properties, and those properties have attributes (name, validation etc). When iterating those attributes, i typecast to some specific attribute-types, and if successful store the relevant attribute information. Im looking to do this in a more elegant way since there is much code repetition at this point. In part the typecast checks (attibute as Attributetype
), and also the check if Validate is null, and then new-ing it up is repetitive (Validate needs to be null if there are no validation attributes). I expect the number of attribute-types to grow
Ideal would be to define what attribute-types im looking for, and if found execute relevant code.
foreach (Attribute attribute in property.GetCustomAttributes(true))
{
//Info attribute
DisplayAttribute display = attribute as DisplayAttribute;
if (display != null)
{
Name =display.Name;
Group = display.GroupName;
Description = display.Description;
}
//Validation attributes
MinLengthAttribute min = attribute as MinLengthAttribute;
if (min != null)
{
if (Validate == null) Validate = new MetaValidate();
Validate.MinLength = min.Length;
}
MaxLengthAttribute max = attribute as MaxLengthAttribute;
if (max != null)
{
if (Validate == null) Validate = new MetaValidate();
Validate.MaxLength = max.Length;
}
RegularExpressionAttribute regex = attribute as RegularExpressionAttribute;
if (regex != null)
{
if (Validate == null) Validate = new MetaValidate();
Validate.Regex = regex.Pattern;
Validate.RegexError = regex.ErrorMessage;
}
}