In Visual Studio, is it possible to target a .NET 4.x CLR but a 2.0 class library API?

Viewed 65

When you select the target framework of a C# project in Visual Studio, you actually select three different things at once (as far as I understand).

Selecting .NET 4.7.2 will select:

  • the language version (e.g. C# 7.2)
  • the CRL (common language runtime) version (e.g. 4.5)
  • and the BCL (base class library) version (e.g. 4.7.2)

Now, is it possible to somehow configure these things independently? I understand there are dependencies, but targeting a lower BCL API should work, right?

The reason is this: my project is a C# class library that is used inside a Unity3D application. Unity has a 4.x (compatible) CLR, but let's you chose between a .NET Standard 2.0 API and a 4.x. It generally makes sense to target 2.0 because it is smaller and 4.x does not work on all platforms that Unity supports.

It would be great if I could replicate this configuration in Visual Studio. Otherwise I might accidentally make an invalid (i.e. > 2.0) API call in my dll code and will only find out when the code crashes with a 'class/function not found' in Unity.

1 Answers

The language version can be set completely independently via <LangVersion> in the csproj, i.e.

<LangVersion>8.0</LangVersion>

The CLR and BCL versions are ... complex. You're really targeting a TFM here. It sounds like you want (again, in the csproj)

<TargetFramework>netstandard2.0</TargetFramework>

The actual CLR (runtime) is determined by whatever runs it, not the library. But you can multi-target, if that becomes useful, i.e.

<TargetFrameworks>netstandard2.0;net472</TargetFrameworks>

and configure different dependencies and #if etc for different platforms, to make the most of each. Whether unity can properly consume a multi-targeted package is another question, that I can't answer.

You can edit the csproj at any point; you aren't tied to what is generated from the template.

Related