If you know the type of expressions ahead of time, you can compile them as part of the class, and then pull them out of the resulting assembly.
Here is an example that does (with expressions taking a string and returning a bool) and runs the resulting rules.
With the contents of c: \ temp \ rules.txt:
file => file.Length == 0 file => System.IO.Path.GetExtension(file) == ".txt" file => file == null
Then the resulting result is as follows:
Rules found in file: file => file.Length == 0, file => System.IO.Path.GetExtension(file) == ".txt", file => file == null, Checking rule file => (file.Length == 0) against input c:\temp\rules.txt: False Checking rule file => (GetExtension(file) == ".txt") against input c:\temp\rules.txt: True Checking rule file => (file == null) against input c:\temp\rules.txt: False
A source:
using System; using System.Xml.Linq; using System.Linq; using System.IO; using Microsoft.CSharp; using System.CodeDom.Compiler; using System.Reflection; using System.Linq.Expressions; class Program { private const string classTemplate = @" using System; using System.Linq.Expressions; public static class RulesConfiguration {{ private static Expression<Func<string, bool>>[] rules = new Expression<Func<string, bool>>[] {{ {0} }}; public static Expression<Func<string, bool>>[] Rules {{ get {{ return rules; }} }} }} "; static void Main(string[] args) { var filePath = @"c:\temp\rules.txt"; var fileContents = File.ReadAllLines(filePath);
source share