3

If source generator projects must target netstandard2.0 (C# 7.3), how and why do the examples in the .NET 6 incremental generator documentation use C# 9 syntax like static anonymous functions?

From the doc, formatted for width:

IncrementalValuesProvider<AdditionalText> textFiles =
   context.AdditionalTextsProvider.Where(static file =>
      file.Path.EndsWith(".txt"));
Kevin Krumwiede
  • 9,868
  • 4
  • 34
  • 82
  • You **can** actually use higher C# language versions than 7.3 if you target `netstandard2.0`, it's an artificial restriction in the build-system (grrrrr). It's complicated and so far I've only gotten it to work in multi-targeting projects, e.g. https://www.meziantou.net/how-to-use-nullable-reference-types-in-dotnet-standard-2-0-and-dotnet-.htm (oh, and all of my multi-targeting projects all really slows down VS 2019 for some reason...) – Dai Apr 14 '22 at 23:46
  • @Dai [This blog post](https://andrewlock.net/exploring-dotnet-6-part-9-source-generator-updates-incremental-generators/) also glosses over it. Maybe I'm the only one not hacking my language versions! – Kevin Krumwiede Apr 15 '22 at 00:21

1 Answers1

2

Just change the C# version in the .csproj file to 9, as in <LangVersion>9.0</LangVersion>

yoel halb
  • 12,188
  • 3
  • 57
  • 52
  • It seems suspicious that it should be so simple. If there isn't some reason not to do this, why isn't it the default? – Kevin Krumwiede Jun 19 '22 at 15:42
  • @KevinKrumwiede this is a decision by the C# team to tie by default the language version to the framework version, and the reason is because there are changes to the language that are dependent on specific new framework components and while they usually provide Nuget packages as a polyfil for older versions they don't want to be required to do it – yoel halb Jun 24 '22 at 07:32
  • Maybe this deserves another question, but does that mean that if I change the language version and use those new language features in a library project, I'm creating a dependency on those polyfill packages, at least for some consumers? – Kevin Krumwiede Jun 24 '22 at 18:21
  • @KevinKrumwiede There are language features that require some polyfill but not all of them, some language features should perfectly work out of the box – yoel halb Jan 30 '23 at 01:18
  • So the answer is... maybe? – Kevin Krumwiede Feb 02 '23 at 15:47
  • 1
    @KevinKrumwiede see also https://stackoverflow.com/questions/56651472/does-c-sharp-8-support-the-net-framework – riQQ Feb 22 '23 at 09:04
  • @KevinKrumwiede as long as you don't use a feature that requires a polyfill you are good to go, the mere fact that you changed to a newer C# version is only for the compiler and does not require anything at runtime. However if you are using a feature that requires a polyfill then the compiler will error unless you explicitly add the polyfill dependency. – yoel halb Jul 17 '23 at 17:45