Question

Inspired by this and this article, I'm trying to create a dynamic function with Roslyn.

However the mentioned sources are outdated or not complete and I'm not able to create a functional sample. My work so far:

var code = @"Func<int, int> doStuffToInt = i =>
{
   var result = i;
   for (var y = i; y <= i * 2; y++)
   {
      result += y;
   }
   return result;
};";


var se = new ScriptEngine();
var session = se.CreateSession();
session.AddReference(typeof(Program).Assembly);
session.AddReference(typeof(Expression).Assembly);

session.ImportNamespace("System");
session.ImportNamespace("System.Linq");
session.ImportNamespace("System.Linq.Expressions");

var submission = session.CompileSubmission<Func<int, int>>(code);

Func<int, int> myFunc =  submission.Execute();

However myFunc is always null and I'm not able to identify where the problem is. Can someone help me out to make this sample run?

Was it helpful?

Solution

Disclaimer: I haven't actually used Roslyn in anger much at all.

Currently your code declares a variable, but doesn't do anything with it afterwards. Based on this random blog post, it looks like you possibly just need an extra expression after the declaration:

var code = @"Func<int, int> doStuffToInt = i =>
{
   var result = i;
   for (var y = i; y <= i * 2; y++)
   {
      result += y;
   }
   return result;
};
doStuffToInt"; // This is effectively the return statement for the script...

I don't guarantee it'll work, but give it a try :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top