Here’s my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;
namespace ConsoleApplication1
{
class Program
{
public int xx = 1; // variable I want to access from the runtime code
static void Main(string[] args)
{
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateInMemory = true;
parameters.ReferencedAssemblies.Add("System.dll");
CompilerResults results = provider.CompileAssemblyFromSource(parameters, GetCode());
var cls = results.CompiledAssembly.GetType("ConsoleApplication1.Program");
var method = cls.GetMethod("DynamicMethod", BindingFlags.Static | BindingFlags.Public);
method.Invoke(null, null);
int a = int.Parse(Console.ReadLine()); // pause console
}
static string[] GetCode()
{
return new string[]
{
@"using System;
namespace ConsoleApplication1
{
class Program
{
public static void DynamicMethod()
{
Console.WriteLine(""Hello, world!"");
}
}
}"
};
}
}
}
I would like to know if It’s possible to access variable int xx from the runetime code (eg. putting xx = 2; line after “hello world”. That would be awesome
Thanks 🙂
Yes, you can make that available, but you need to:
xx(I’m calling this assemblyStaticAssembly, for convenience – so it is probablyStaticAssembly.exe, the console exe that is running)PrograminStaticAssemblyapublictype so that it is accessiblexxinto astaticfield, or instantiate an instance ofProgramand pass it to the dynamic code somehowThe following works, for example (I’m using the “instantiate an instance and pass it” approach, so I’ve added a parameter to
DynamicMethod):