Nico Schertler
Nico Schertler

Reputation: 32637

Specify language version for Roslyn SyntaxFactory

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?

Upvotes: 3

Views: 1126

Answers (2)

dkokkinos
dkokkinos

Reputation: 411

In case you want to spesify tha LanguageVersion in a syntax tree that you create with code, you can use the following:

var options = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp10);
var syntaxTree = CSharpSyntaxTree.ParseText(code, options);

Upvotes: 0

shingo
shingo

Reputation: 27404

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

Upvotes: 3

Related Questions