TargetFramework vs. TargetFrameworks (plural)

18.3k Views Asked by At

In the .csproj file in my .NET Core projects, there are these 3 lines by default:

<PropertyGroup>
  <TargetFramework>netcoreapp2.2</TargetFramework>
</PropertyGroup>

Now if I want to target mulitple frameworks, I can change it to this:

<PropertyGroup>
  <TargetFrameworks>netcoreapp2.2;net4.6</TargetFrameworks>
</PropertyGroup>

The difference is subtle, but it's there. When targeting multiple frameworks, you have to use <TargetFrameworks> (plural) instead of just <TargetFramework> (singular).

But why is it made like this? It seems like it would have been easier to just pick one of the two, and then always use that. Which leads me to the thought, that there might be a more complex reason, for choosing to different (although similar) words, depending on whether or not you target more frameworks. Can anyone enlighten me on the topic?

2

There are 2 best solutions below

2
On

You can use TargetFrameworks configuration when you are building a class library that will runs well in .Net Full Framework and .Net Core Framework. This is the best use case to this configuration

It doesn't make sense use multiple target framework if you are building a website or webapi. In this case, use just one target framework.

4
On

Basically when you want to target a single framework you use <TargetFramework> tag (in the case where you're building an app targeting .net-core), but it's possible also that you may conditionally reference assemblies multiple frameworks by using <TargetFrameworks> (in case you're building an app for both .net standard and .net-core) and then you can conditionally compile against those assemblies by using preprocessor symbols with if-then-else logic

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFrameworks>netstandard1.4;net40;net45</TargetFrameworks>
  </PropertyGroup>

  <!-- Conditionally obtain references for the .NET Framework 4.0 target -->
  <ItemGroup Condition=" '$(TargetFramework)' == 'net40' ">
    <Reference Include="System.Net" />
  </ItemGroup>

  <!-- Conditionally obtain references for the .NET Framework 4.5 target -->
  <ItemGroup Condition=" '$(TargetFramework)' == 'net45' ">
    <Reference Include="System.Net.Http" />
    <Reference Include="System.Threading.Tasks" />
  </ItemGroup>

</Project>

Source : https://learn.microsoft.com/dotnet/standard/frameworks