1

If I build and publish a NuGet package with a Language Version of 9, can I install and reference the NuGet package in a project using a lower Language version (for example c# 7)?

NuGet Package .csproj:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <LangVersion>9</LangVersion>
  </PropertyGroup>
</Project>

Consuming library .csproj:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <LangVersion>7.3</LangVersion>
  </PropertyGroup>
</Project>
ADyson
  • 57,178
  • 14
  • 51
  • 63
chris31389
  • 8,414
  • 7
  • 55
  • 66
  • 1
    Why don't you try it and see? (P.S. I'd expect so yes because when you build a C# program it's compiled down to IL. So the raw C# never gets anywhere near the target project. AFAIK the C# version only determines what language features you can use when coding and what compiler version you need. What it compiles _to_ depends on the target .NET Framework. Bear in mind, when you install a nuget package (or any reference any other .NET DLL), you don't even know if it was originally written in C# or another language - that's one of the nice things about .NET) – ADyson Nov 23 '20 at 09:40
  • 1
    Officially, the language version is now tied to the target framework version (although you can override this with `LangVersion`, officially you're in unsupported terratory). In practice, so long as you're not using C# features which rely on newer target frameworks (you'd need jump through hoops and use polyfills to do this, such as defining `System.Runtime.CompilerServices.IsExternalInit` to use init-only properties) you'll be fine. – canton7 Nov 23 '20 at 09:44
  • @canton7 even things like init-only accessors gives consideration to older compilers; that's *why* it uses mod-req; the caveat being that you won't be able to use the property at all, *even in* an initializer. Things that don't touch that property should be fine, though. – Marc Gravell Nov 23 '20 at 09:46
  • @MarcGravell Yep, the point I was trying to make is that if you're using polyfills in order to define types/methods using features introduced by newer compilers, don't necessarily expect older compilers to be able to use those types/methods in the same way that newer compilers can. – canton7 Nov 23 '20 at 09:52

1 Answers1

1

This is possible.

So after a suggestion from @ADyson I tried to do this myself locally.

It took me about 30 minutes to build a .netstandard2.0 project with a reference to IAsyncEnumerable with the Microsoft.Bcl.AsyncInterfaces 5.0.0 NuGet package as it doesn't natively get included in .netstardard2.0.

After packing up a NuGet locally, I included it into a Console Application using .netcore2.1 and called a method that used the IAsyncEnumerable. It worked!

chris31389
  • 8,414
  • 7
  • 55
  • 66