Specify language version for Roslyn SyntaxFactory

Viewed 199

I am currently building a C# source generator with Roslyn in a netstandard2.0 library. In the .csproj, I have referenced the following Roslyn packages:

<ItemGroup>
    <PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.0.1" />
    <PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.3" />
</ItemGroup>

The source generator uses Roslyn's SyntaxFactory to create additional code. It then uses context.Compilation.AddSyntaxTrees() to add the generated code to the compilation (context is the GeneratorExecutionContext passed to the generator's Execute method).

The problem is that I get the following exception upon calling AddSyntaxTrees():

System.ArgumentException: Inconsistent language versions. Parameter name: syntaxTrees

I understand the reason for the exception. The syntax trees created by the SyntaxFactory have their language versions set to CSharp10. But the language version of the compilation context is set to CSharp8.

Is there a way to tell the SyntaxFactory the language version it should produce?

I understand that I could also use version 3.7 of Microsoft.CodeAnalysis.Analyzers (according to this table). But would this not also prevent me from using the latest Roslyn features (not sure what that might be, though). Furthermore, how can I be sure that the target libraries that use the source generator will ever only be compiled with the same language version? Or do I need different versions for the source generator for different language versions? Also - might this differ in different IDEs?

1 Answers

When you create a SyntaxTree you can set its language version with the ParseOptions argument.

var options = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8);
var syntaxTree = SyntaxFactory.SyntaxTree(root, options);

SyntaxFactory.SyntaxTree

Related