Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sending anonymous type to IronPython from C# throws MissingMemberException

The below code throws a 'MissingMemberException'

ScriptEngine engine = Python.CreateEngine();
ScriptRuntime runtime = engine.Runtime;
ScriptScope scope = runtime.CreateScope();

string code = "emp.Name==\"Bernie\"";

ScriptSource source =
  engine.CreateScriptSourceFromString(code, SourceCodeKind.Expression);

var emp = new {Name = "Bernie"};

scope.SetVariable("emp", emp);

var res = (double)source.Execute(scope);

if I declare a type called 'Employee' and give it a member 'Name', and use this instead:

var emp = new Employee {Name = "Bernie"}

It works just as expected. Does anyone know why it doesn't work on anonymous types and is there a workaround?

like image 325
dferraro Avatar asked Jan 16 '13 22:01

dferraro


1 Answers

Your problem is that anonymous types are internal. When the complier generates an anonymous type, it is approximately this:

internal class <>f__AnonymousType0`1'<'<Name>j__TPar'> //or whatever silly name the compiler uses
{
    public string Name {get;set;}
}

You can replicate the error you are getting with a concrete class by changing it to be internal:

internal class Employee
{
    public string Name { get; set; }
}

OK, so that's why it's happening. How do you fix it? Well, the best approach is to just use a concrete class that is public like you have already found.

like image 187
vcsjones Avatar answered Sep 28 '22 06:09

vcsjones