Click here to Skip to main content
15,893,401 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a method which compiles a 'module', a 'module' contains a string of valid C# read from a .cs file. I am wondering whether it's possible to pass an object from the class that contains the method to compile the module, to the assembly that is created allowing for the code initially in the .cs file to use that object.

Here is the code I use to compile the modules
C#
public void CompileModule(string strModuleName)
{
    CompilerParameters objCompilerParameters = new CompilerParameters();
    objCompilerParameters.GenerateExecutable = false;
    objCompilerParameters.GenerateInMemory = true;
    objCompilerParameters.IncludeDebugInformation = false;
    CodeDomProvider objCompiler = CSharpCodeProvider.CreateProvider("CSharp");
    CompilerResults objCompilerResults = objCompiler.CompileAssemblyFromSource(objCompilerParameters, Modules[strModuleName].Source);
    if (objCompilerResults.Errors.HasErrors)
    {
        throw new InvalidOperationException("Syntax error.");
    }
    Assembly objCompiledAssembly = objCompilerResults.CompiledAssembly;
    MethodInfo objMethod = objCompiledAssembly.GetType(Modules[strModuleName].ClassName).GetMethod(Modules[strModuleName].CallMethod);
    Console.WriteLine((string)objMethod.Invoke(null, null));
}


Modules is just a dictionary of dictionary<string,>, Module being the name of the class that contains the contents of the .cs file.

If the module source is
C#
public static class Echo
{
    public static string strTest = "Testing";
    public static string EchoTestString()
    {
        return strTest;
    }
}


How would I be able to pass an instantiated object (of type Fruit) to the assembly, so I could use the Fruit object however I wanted inside of the Echo class? So the .cs file could essentially just be

C#
public static class Echo
{
    public static string EchoFruitName()
    {
        return Fruit.Name;
    }
}


Fruit being defined in my compiler class and passed across to the compiled Echo class of course.

Any ideas?
Thanks in advance. :)
Posted
Comments
Hariharan Arunachalam 28-Mar-13 5:43am    
Wouldn't Fruit throw an exception while compiling in the compile method?
Ian A Davidson 28-Mar-13 6:02am    
Why on earth would you even want to do this?

1 solution

Yes, its possible.
Add this line
C#
objCompilerParameters.CompilerOptions = "/reference:MyCurrentAssemblyWithTheFruitClass.exe";


MyCurrentAssemblyWithTheFruitClass.exe (or .dll) which is the file containing the assembly with the fruit class. My test project was a console application, so I used the .exe.
Hope this is what you wanted.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900