In my case I got the error as follows
Message=(1,1): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
Source=Microsoft.CodeAnalysis.Scripting
when I called the following method.
private static async Task TrialUsingRoslynScriptingApi1()
{
var scriptOptions = ScriptOptions.Default;
var assemblies = AppDomain.CurrentDomain.GetAssemblies(); // .SingleOrDefault(assembly => assembly.GetName().Name == "MyAssembly");
foreach (Assembly assembly in assemblies)
scriptOptions = scriptOptions.AddReferences(assembly);
scriptOptions = scriptOptions.AddImports("System");
scriptOptions = scriptOptions.AddImports("System.Collections.Generic");
var codeString = @"iList =>
{
var finalResult = 0;
foreach (var i in iList)
finalResult = finalResult + i;
return finalResult;
};
return arithmeticSum;";
Func<List<int>, int> arithmeticSum = await CSharpScript.EvaluateAsync<Func<List<int>, int>>(codeString, scriptOptions);
var iListOfNumbers = new List<int>() { 1, 2, 3, 4, 5 };
Console.WriteLine(arithmeticSum.Invoke(iListOfNumbers));
Console.WriteLine(arithmeticSum(iListOfNumbers));
}
To mitigate that, I changed the codeString to the following. Note the return statement in the end and the assignment in the begining.
var codeString = @"Func<List<int>, int> arithmeticSum = iList =>
{
var finalResult = 0;
foreach (var i in iList)
finalResult = finalResult + i;
return finalResult;
};
return arithmeticSum;";
Note that this is not a regular use case, I am trying to compile a piece of code using roslyn(.NET Compiler platform) on the fly.
To run this example, do the following.
- create a console app on .net core
- Add Microsoft.CodeAnalysis.CSharp.Scripting nuget package.
- Add some or all of the following using statements as needed.
Using statements
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
- Finally call the method as follows.
Main method in Program.cs file should be as follows.
static async Task Main(string[] args)
{
Console.WriteLine("Hello World! A demo of string to lambda with Roslyn");
await TrialUsingRoslynScriptingApi1();
}