Validate bool methods (constraints) in list

c#, constraints, list, validation

Solution

Try this

List<Func<bool>> constraints = new List<Func<bool>> ();

// add your functions
constraints.Add(check1);
constraints.Add(check2);

// and then determine if all of them return true
bool allTrue = constraints.All (c => c());

// or maybe if any are true
bool anyTrue = constraints.Any(c => c());

Problem

I'm wondering if this is possible: I would like to have a list where I can add bool methods to and validate those methods and when they are all true, return true. When at least one is false, return false. Problem is, when I do something like: ``` private int _value1, _value2, _value3, _value4; private bool check2() { return _value2 + _value3 > _value4; } private bool check2() { return _value2 + _value3 > _value4; } List<bool> constraints = new List<bool>(); constrains.Add(check1()); constrains.Add(check2()); ``` the bools added are of course the result of the validation when added to the list. I get that ;-) How can I make a list with methods, that are actually re-validated? Kind regards, Matthijs This is what I wanted. With the help of the answers below. I made this. Might be useful for others looking for the same thing. ``` public class TestClass { private int _value1, _value2, _value3, _value4; private void button1_Click(object sender, EventArgs e) { ConstraintsList cl = new ConstraintsList(); cl.Add(check1); cl.Add(check2); bool test1 = cl.AllTrue; bool test2 = cl.AnyTrue; _value4 = -5; bool test3 = cl.AllTrue; bool test4 = cl.AnyTrue; _value4 = 5; cl.Remove(check2); bool test5 = cl.AllTrue; bool test6 = cl.AnyTrue; } private bool check1() { return _value1 + _value2 == _value3; } private bool check2() { return _value2 + _value3 > _value4; } } ``` using: ``` public class ConstraintsList { private HashSet<Func<bool>> constraints = new HashSet<Func<bool>>(); public void Add(Func<bool> item) { try { constraints.Add(item); } catch(Exception) { throw; } } public bool AllTrue { get { return constraints.All(c => c()); } } public bool AnyTrue { get { return constraints.Any(c => c()); } } public void Remove(Func<bool> item) { try { constraints.Remove(item); } catch(Exception) { throw; } } } ```

Original source