0

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.

3
  • 2
    are you looking for the System.Dynamic.Runtime NuGet package? i.e. <PackageReference Include="System.Dynamic.Runtime" Version="4.3.0" /> ? Also: async void is a huge red flag Commented Mar 18, 2024 at 14:18
  • Are you sure you set framework version to netstandard2.0 ? I just tried your code in a new project and it raises the error only with netstandard1.6 or lower. Commented Mar 18, 2024 at 14:22
  • System.Dynamic.Runtime.dll is included, yes. The async void was only for example purposes, I'll change it. Commented Mar 18, 2024 at 14:28

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.