I have an issue where I'm trying to compile code with the Microsoft.CodeAnalysis.CSharp package. I wrote a function that compiles the code into an assembly and returns it. This function was originally written in NET8, but I had to move it into a netstandard2.0 library. I copied the original function from https://stackoverflow.com/a/29417053/23650248 and made minor modifications. Since I moved it it doesn't compile code if it contains the dynamic keyword.
It works as expected when the code doesn't include the dynamic keyword, but when it does I get the following exception:
Line: 13 Col:36 Code:
CS1980 Message: Cannot define a class or member that utilizes 'dynamic' because the compiler required type 'System.Runtime.CompilerServices.DynamicAttribute' cannot be found. Are you missing a reference?
This is the code I was trying to compile:
using System;
using Microsoft.CSharp;
using System.Threading.Tasks;
using System.Runtime.CompilerServices;
using System.Dynamic;
namespace CodeCompiler
{
public class CalculationScripts : ICalculationScriptRunner
{
public async Task CalculateTime(dynamic model)
{
int x = 5;
}
}
}
(there is also an additional using for the interface)
The class library which contains my assembly-generation code is in netstandard 2.0 and and I also have the CSharpParseOptions set to C# 7.3 (also tried changing this to other versions):
var options = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp7_3).WithKind(SourceCodeKind.Regular);
I've already tried to include every using that I found online that could be related to this issue, and also included the required assemblies for the compilation, but none of them solved my problem. If I change the function's parameter's type to another type it works without any issues, but it's important to me that I'm able to use dynamic.
System.Dynamic.RuntimeNuGet package? i.e.<PackageReference Include="System.Dynamic.Runtime" Version="4.3.0" />? Also:async voidis a huge red flag