Validation on an Abstract type(Inheritance related)

Topics: Validation Application Block
May 21, 2007 at 9:19 PM
Hi,

Below is the context of the question.

public class Metric
{
public Metric()
{}

Target target;
}

public abstract Target()
{}

public SimpleTarget:Target()
{}

public TrendTarget:Target()
{}

Metric class can contain as its target either SimpleTarget or TrendTarget. In Metric object, I have object validation for “target” field with object type set up as “Target” (in config file). But if a validation error occurs in SimpleTarget(which is of type Target part of Metric above) the code is unable to catch the error.

The problem is that when I have an object which contains an abstract object as a field in it, the validation is not able to determine in run time the actual type of the abstract object and do the necessary object validation. Is Self validation my only option here? If I need to use Self Validation, how would I make the call (in code) to validate the abstract object.

For e.g. for the below metric instance, if I validate, I dont know the correct way to set up Object Validation for the Target object.

Metric metric = new Metric();
metric.Target = new SimpleTarget();
May 22, 2007 at 2:53 AM
You have a few ways. You can define the validation in the abstract base class and/or override it in the concrete class. Here is an example that can get you started:

namespace Inheritance
{
    class Program
    {
        static void Main(string[] args)
        {
            Metric metric = new Metric();
            metric.Target = new SimpleTarget();
 
            ValidationResults results = Validation.Validate(metric);
        }
    }
 
    public class Metric
    {
        [NotNullValidator]
        public string Name;
 
        [ObjectValidator]
        public Target Target;
    }
 
    abstract public class Target
    {
        [NotNullValidator]
        abstract public string Name { get; set; }
    }
 
    public class SimpleTarget : Target
    {
        private string _name;
        public override string Name
        {
            get
            {
                return _name;
            }
            set
            {
                _name = value;
            }
        }
    }
}

Regards,

Dave

____________________________

David Hayden
Microsoft MVP C#