Search code examples
c#csharpcodeprovider

Set Variable Value using CSharpCodeProvider


I was wondering if there is any way to pass a variable value in a code that will be compiled One Time using CSharpCodeProvider .

for example :

string code = @"
using System;

namespace First
{
    public class Program
    {
       public int Value; // pass this value
        public static void Main()
        {
        " +
            "Console.WriteLine(\"Hello + Value\");"
            + @"
        }
    }
}

";

Compile Method :

public void Compile(String Code)
{
    CSharpCodeProvider provider = new CSharpCodeProvider();
    CompilerParameters parameters = new CompilerParameters();

    parameters.ReferencedAssemblies.Add("System.Drawing.dll");
    parameters.GenerateInMemory = true;
    parameters.GenerateExecutable = false;

    CompilerResults results = provider.CompileAssemblyFromSource(parameters, Code);
}

So i want to be able to pass a value of the Value example 2

and what i meant by ONE TIME is like compile time so the compiled code will always in its run-time will display the value : 2 whenever i executed the application .

I hope its clear !


Solution

  • Solved Using Mono.Cecil reference details Documentatin