Monday, January 30, 2006

A Wish - Validators for Properties in C#

While writing a validation framework for a whole bunch of business objects this weekend, I wish I would have had the following in C#/.NET

public double Notional
{
get
{
return this._notional;
}
set
{
this._notional = value;
}
validate
{
if (this._notional <>
{
this.AddBrokenRule("A Buyer's notional cannot be negative");
return false;
}
return true;
}
}

If I called businessObject.IsValid, then all properties of the businessObject that implemented validate would be tested. Each object would automatically contain an IList of all broken business rules.

There would be support for this in the Visual Studio designer, so that I could created a resource-based string for each error message.


©2006 Marc Adler - All Rights Reserved

1 comment:

Anonymous said...

You can easily write this with some custom attributes (for the error message) and some reflection looking for naming conventions. This is how a lot of the System.ComponentModel namespace works -- e.g. change notification, resetting property values, etc.