I compile code dynamically from code:
string code = @"
namespace CodeInjection
{
public static class DynConcatenateString
{
public static string Concatenate(string s1, string s2){
return s1 + "" ! "" + s2;
}
}
}";
// http://stackoverflow.com/questions/604501/generating-dll-assembly-dynamically-at-run-time
Console.WriteLine("Now doing some injection...");
Console.WriteLine("Creating injected code in memory");
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
ICodeCompiler icc = codeProvider.CreateCompiler();
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = false;
parameters.GenerateInMemory = true;
//parameters.OutputAssembly = "DynamicCode.dll"; // if specified creates the DLL
CompilerResults results = icc.CompileAssemblyFromSource(parameters, code);
Then I can invoke the method with reflection:
Console.WriteLine("Input two strings, and I will concate them with reflection:");
var s1 = Console.ReadLine();
var s2 = Console.ReadLine();
var result = (string)results.CompiledAssembly.GetType("CodeInjection.DynConcatenateString").GetMethod("Concatenate").Invoke(null, new object[] { s1, s2 });
Console.WriteLine();
Console.WriteLine("Result:");
Console.WriteLine(result);
But I would like to invoke something like this:
Console.WriteLine("Input two strings, and I will concate them with dynamic type:");
var s1 = Console.ReadLine();
var s2 = Console.ReadLine();
dynamic type = results.CompiledAssembly.GetType("CodeInjection.DynConcatenateString");
var resultA = (string)type.Concatenate(s1, s2); // runtime error
// OR
var resultB = (string)CodeInjection.DynConcatenateString.Concatenate(s1, s2); // compile error (cannot find assembly)
Console.WriteLine();
Console.WriteLine("Result:");
Console.WriteLine(resultA);
Console.WriteLine(resultB);
The resultB would be better. Any ideas how to do it? I need strictly .NET 4.0, we have not updated to 4.5 yet (because the half of the team uses VS 2010). (I can invoke with reflection, I know, I am just looking for another way, because we need to test dyn. code)