In .NET application is possible save C# code in text file or database as string and run dynamically on the fly. This method is useful in many case such as business rule engine or user defined calculation engine and etc. Here is a nice example:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
class Program
{
static void Main(string[] args)
{
var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });
var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, "foo.exe", true);
parameters.GenerateExecutable = true;
CompilerResults results = csc.CompileAssemblyFromSource(parameters,
@"using System.Linq;
class Program {
public static void Main(string[] args) {
var q = from i in Enumerable.Range(1,100)
where i % 2 == 0
select i;
}
}");
results.Errors.Cast<CompilerError>().ToList().ForEach(error => Console.WriteLine(error.ErrorText));
}
}
The class of primary importance here is the CSharpCodeProvider which utilises the compiler to compile code on the fly.
As you know Python is a widely used general-purpose, high-level programming language. Its design philosophy emphasizes code readability, but C# is difficult that python. So it's better use python for dynamic code fragments instead C#.
How to execute python dynamically in C# application?
class Program
{
static void Main(string[] args)
{
var pythonCode = @"
a=1
b=2
c=a+b
return c";
//how to execute python code in c# .net
}
}