One obvious solution is to use reflection.
Here we will show a solution which uses Expression trees tocompile the rules into fast executable delegates. We can then evaluate the rules as if they were normal boolean functions.

Now we can implement the rule validation by compling the rules and then simply invoking them:

var rule = newRule ("Age", "GreaterThan", "20");

Func<User, bool> compiledRule = CompileRule<User>(rule);

// true if someUser.Age > 20

bool isMatch = compiledRule(someUser);

Of course we compile all the rules just once and then use the compiled delegates:

// Compile all the rules once.

var compiledRules = rules.Select(r => CompileRule<User>(r)).ToList();

// Returns true if user satisfies all rules.

publicbool MatchesAllRules(User user)

{

return compiledRules.All(rule => rule(user));

}

Note that the “compiler” is so simple because we are using 'GreaterThan' in the rule definition, and 'GreaterThan' is a known .NET name for the operator, so the string can be directly parsed. The same goes for 'Contains' – it is a method of List. If we need custom names we can build a very simple dictionary that just translates all operators before compiling the rules:

Dictionary<string, string> nameMap = newDictionary<string, string> {

{ "greater_than", "GreaterThan" },

{ "hasAtLeastOne", "Contains" }

};

That’s it. As an improvement we could add error messages to the rule definitions and print the error messages for the unsatisfied rules.