Sealed attributes

Topics: Developer Forum
Dec 20, 2006 at 1:25 PM
It would be great if the Attributes won't be sealed.

If won't be sealed, I could do things like inherit from an attribute and establish a standard message for all occurrences of one attribute, and have a constructor without the message parameter.
Coordinator
Dec 20, 2006 at 2:45 PM
Actually, sealing attributes is a best practice because it provides better performance during reflection. I use FxCop for static code analysis and it raises issues if any attributes aren't sealed. If you need a constructor without a message paramter then we could possibly add that to the EvilBaseAttribute class.
Dec 20, 2006 at 6:43 PM
I understand that the performance won't be so good, but will be more flexible. Only a parameterless constructor wouldn't solution my issue. For a while if found a workaround for my issue overriding the method IsValid. What do you think about? There's a better aproach?

public class A: EvilEntityBase
{
private string _b;

ValidateRequired(null)
public string b
{
get{return _b;}
set{_b=value;}
}

public override bool IsValid()
{
// First clear any existing errors
this.ValidationErrors.Clear();

// Get all properties on the entity and validate
PropertyInfo[] properties = this.Entity.GetType().GetProperties();
ValidateProperties(properties);

if (this.ValidationErrors.Count > 0)
{
return false;
}
// Otherwise
return true;
}

private void ValidateProperties(PropertyInfo[] properties)
{
// Go thru all properties and validate
foreach (PropertyInfo pi in properties)
{
// Get all validation attributes on the property
EvilBaseAttribute[] attributes = (EvilBaseAttribute[])pi.GetCustomAttributes(typeof(EvilBaseAttribute), true);

// Get the value of the property on the current entity
object propValue = null;
if (attributes.Length > 0)
{
propValue = pi.GetValue(this.Entity, null);
}

// Loop thru each attribute on the property and invoke ValidateValue
foreach (EvilBaseAttribute attrib in attributes)
{
// Each attribute type implements its own ValidateValue
if (!attrib.ValidateValue(propValue, this.Entity))
{
/!!!!!!MODIFYING THIS!!!!!!/
if(string.IsNullOrEmpty(attrib.Message))
this.ValidationErrors.Add("MYSTANDARDREQUIRED_MESSAGE");
else
this.ValidationErrors.Add(attrib.Message);
}
}
}
}

}

Coordinator
Dec 20, 2006 at 11:11 PM
I think overriding the IsValid implementation like you have it makes sense for what you want to do.