netmatrix01
netmatrix01

Reputation: 640

Error Checking using Func Delegate

So i recently learned this new trick of using Func Delegate and Lambda expression to avoid multiple validation if statements in my code.

So the code looks like something like

 public static void SetParameters(Dictionary<string,object> param)
        {
            Func<Dictionary<string, object>, bool>[] eval = 
            {
                e => e != null ,
                e => e.Count ==2 ,
                e  => e.ContainsKey("Star"),
                e  => e.ContainsKey("Wars")
            };

            var isValid = eval.All(rule => rule(param));

            Console.WriteLine(isValid.ToString());
        }

but my next step is i would like to do some error checking as well. So for e.g. if the count !=2 in my previous example i would like to write build some error collection for more clear exception further down.

So i been Wondering how can i achieve that using similar Func and Lamdba notation ?.

I did come up with my rules checker class

public class RuleChecker
    {
        public Dictionary<string, object> DictParam
        {
            get;
            set;
        }

        public string ErrorMessage
        {
            get;
            set;
        }
    } 

Can someone help as how can i achieve this?

Upvotes: 3

Views: 337

Answers (1)

Preet Sangha
Preet Sangha

Reputation: 65506

you can do this:

        List<string> errors = new List<string>();
        Func<Dictionary<string, object>, bool>[] eval = 
        {
            e => { bool ret = e != null; if (!ret) errors.Add("Null"); return ret; },

However a more elegant solution would be to

        List<string> errors = new List<string>();
        Func<bool, string, List<string>, bool> EvaluateWithError = (test, message, collection) =>
        {
            if (!test) collection.Add(message); return test;
        };

        Func<Dictionary<string, object>, bool>[] eval = 
        {
            e => EvaluateWithError(e != null, "Null", errors),

Upvotes: 2

Related Questions