Andrew Thomas




Blog Post

Dynamic Execution of Code in C#

Oct 28, 2019 C#

I have had the need to dynamically execute code for specific clients and thought the basics of the code may come in use to others. Its really useful to be able to do this and you need to use the CSharpCodeProvider

string function = "HttpUtility.UrlEncode(\"test / 123\")"; 

//code generator and code provider
ICodeCompiler codeCompiler = new CSharpCodeProvider().CreateCompiler();
CompilerParameters compilerParameters = new CompilerParameters();
compilerParameters.GenerateInMemory = true; 

string code = @"using System;
                using System.Web;
                namespace Ist.Utilities 
                  public class FormulaEvaluationClass 
                    public string DynamicCode() 
                      return Convert.ToString(" + function + @");
CompilerResults compilerResults = codeCompiler.CompileAssemblyFromSource(compilerParameters, code);
if (compilerResults.Errors.HasErrors)
  throw new Exception("Handle errors here"); 

Assembly assembly = compilerResults.CompiledAssembly;
object assemblyClass = assembly.CreateInstance("Ist.Utilities.FormulaEvaluationClass"); 

string result = Convert.ToString(assemblyClass.GetType().InvokeMember("DynamicCode", BindingFlags.InvokeMethod,
  null, assemblyClass, null));

Unfortunately the code is slow if executing a lot of times, so looking at ways to speed that up. Caching the compilation of the assembly certain helps.