This project is read-only.
Rule Inheritance

This example shows how rules set for a base object will also apply to all its descendants.

    class InheritanceExample
    {
        public abstract class Person
        {
            public string Name { get; set; }
            public string Email { get; set; }
        }
        public class Member : Person
        {
            public int MembershipNumber { get; set; }
        }
        public class Visitor : Person
        {
            public Member InvitedBy { get; set; }
        }
        public class Party
        {
            public List<Person> Attendees { get; set; }
        }

        static void Main(string[] args)
        {
            var engine = new Engine();
            engine.For<Person>()
                    .Setup(m => m.Name)
                        .MustNotBeNullOrEmpty()
                    .Setup(m => m.Email)
                        .MustNotBeNullOrEmpty()
                        .MustMatchRegex(@"^[a-z]+@[a-z]+(\.[a-z]+)*$"); //Matches any e-mail address

            engine.For<Member>() //Member will inherit rules set for a Person.
                    .Setup(m => m.MembershipNumber)
                        .MustBeGreaterThan(0)
                    .Setup(m => m.Email)
                        .MustMatchRegex(@"^[a-z]+@club\.com$"); //Matches specific email address

            engine.For<Visitor>() //Visitor will inherit rules set for a Person.
                    .Setup(m => m.InvitedBy)
                        .MustNotBeNull()
                        .CallValidate(); //Validates the member

            engine.For<Party>()
                    .Setup(m => m.Attendees)
                        .MustNotBeNull()
                        .CallValidateForEachElement();


            var m1 = new Member() { Name = "Janet", Email = "janet@club.com", MembershipNumber = 1 }; //Valid
            var v1 = new Visitor() { Name = "Bill", Email = "bill@mail.com", InvitedBy = m1 }; //Valid
            var v2 = new Visitor() { Name = "Ingrid", Email = "ingrid@yahoo.com", InvitedBy = m1 }; //Valid
            var m2 = new Member() { Name = "", Email = "noname@club.com", MembershipNumber = 2 }; // Invalid - Rule NotNullOrEmpty inherited from Person

            Party party = new Party { Attendees = new List<Person>(new Person[] { m1, v1, v2, m2 }) };
            bool isValid = engine.Validate(party); //Invalid because of m2.
        }
    }

Last edited Sep 26, 2011 at 1:40 PM by athoma13, version 1

Comments

No comments yet.