I am trying to use a simple static method to return an object to dynamically evaluate an expression. I have followed the advice outlined in the examples here: http://www.blackwasp.co.uk/RuntimeCompilation_2.aspx
For basic expressions this is working fine, but for ones that involve a .Contains() method I get an exception thrown.
Working Calls:
Console.WriteLine(DynamicCodeUtils.TestExpression("1 == 1 && (2 == 3 || 2 == 2) && 4 == 5");
Output: false
Console.WriteLine(DynamicCodeUtils.TestExpression("Math.Max(100,200)"));
Output: 200
Non-Working Call:
string _ArrayCheck = "\"1,2,3\".Split(',').ToArray().Contains(\"1\")";
Console.WriteLine(DynamicCodeUtils.TestExpression(_ArrayCheck));
Throws an exception - expected output would be "true"
Code:
public static object TestExpression(string Expression)
{
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = false;
parameters.GenerateInMemory = true;
parameters.ReferencedAssemblies.Add("System.dll");
parameters.ReferencedAssemblies.Add("System.Xml.dll");
parameters.ReferencedAssemblies.Add("System.Xml.Linq.dll");
CompilerResults results = provider.CompileAssemblyFromSource(parameters, GetCode(Expression));
var cls = results.CompiledAssembly.GetType("DynamicNS.DynamicCode");
var method = cls.GetMethod("DynamicMethod", BindingFlags.Static | BindingFlags.Public);
return method.Invoke(null, null);
}
public static string[] GetCode(string Expression)
{
return new string[]
{
@"
using System;
using System.Linq;
namespace DynamicNS
{
public static class DynamicCode
{
public static object DynamicMethod()
{
return " + Expression + @";
}
}
}"
};
}
The CompilerResults
type contains the property Errors
. If you look into in, you will find:
error CS0234: The type or namespace name 'Linq' does not exist in the namespace 'System' (are you missing an assembly reference?)
This is because types in the System.Linq
namespace (like Enumerable
) are in the System.Core.dll
assembly. If you add that, then your code will start working:
parameters.ReferencedAssemblies.Add("System.Core.dll");