Sara.B
Sara.B

Reputation: 11

How to pass an object to dynamic code in C#

im using System.CodeDom.Compiler to generate a dynamic code , i need to pass some objects to the functions in code , but when i pass objects they refer to my current name space ...

string code = @"
            using System;
            using " + type + @";
            namespace First
            {
                public class Program
                {
                    static " + type + ".Class1 " + type.ToLower() + " = (" + type + ".Class1)"+o + @";                   
                    public static bool check () {
                        if( " + exp
                        +
                        @")
                            return true;
                        else 
                            return false;
                    }
                    public static void Main()
                    {
                    " +
                       "    Console.WriteLine(\"Hello, world!\");"
                      + @"
                    }
                }
            }
        ";

and i get this error : The name 'MineRuleEngine'(my current name space) does not exist in the current context

Upvotes: 0

Views: 472

Answers (2)

Sara.B
Sara.B

Reputation: 11

i pass the object directly to the method and invoke that by reflection

public static bool check (Object o) {

and put the parameter "o" inside string , and remove static modifier

type + " " + type.ToLower() + " = " + "(" + type + ")o ;"

Upvotes: 0

netaholic
netaholic

Reputation: 1385

my problem is that object "o" is refer to MineRuleEngine.person for example . and my dynamic code doesn't know "MineRuleEngine" namespace

The reason your code doesn't know about this object is because you have to explictly take care of using "external" resources (i.e. classes)

You have to specify using MyNamespace; in code and you have to add a reference to an assembly containing the namespace.

For example:

 CSharpCodeProvider provider = new CSharpCodeProvider();
 CompilerParameters param = new CompilerParameters(new string[] { "System.dll", "Scripting.dll" });

Also take a look at this question Referencing current assembly with CompilerParameters

Upvotes: 1

Related Questions