Iterate attributes of property, typecast and store info if found 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;
    }
}
Seems like ive found a great solution, my entire loop can be rewritten as this:

InvokeOnAttr&lt;DisplayAttribute&gt;(property, a =&gt; {
    Name = a.Name;
    Group = a.GroupName;
    Description = a.Description;
});

InvokeOnAttr&lt;MinLengthAttribute&gt;(property, a =&gt; {
    Validate.MinLength = a.Length;
});

InvokeOnAttr&lt;MaxLengthAttribute&gt;(property, a =&gt; {
    Validate.MaxLength = a.Length;
});

InvokeOnAttr&lt;RegularExpressionAttribute&gt;(property, a =&gt; {
    Validate.Regex = a.Pattern;
    Validate.RegexError = a.ErrorMessage;
});


If this method also is availible in the class (it takes a property, finds the attribute (of type TAttr provided), and if found executes the passed in action on it:

public void InvokeOnAttr&lt;TAttr&gt;(PropertyInfo p, Action&lt;TAttr&gt; action) where TAttr : Attribute {
    TAttr attr = p.GetCustomAttribute&lt;TAttr&gt;();
    if (attr is ValidationAttribute)
    {
        if (Validate == null) Validate = new MetaValidate();
    }
    if (attr != null) { 
        action.Invoke(attr);
    }
}