Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a Func<> with Roslyn

Tags:

c#

.net

roslyn

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?

like image 309
gsharp Avatar asked Mar 21 '23 04:03

gsharp


1 Answers

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 :)

like image 110
Jon Skeet Avatar answered Mar 28 '23 12:03

Jon Skeet