Starting with .NET 6, dotnet new console
will create a project with a "top level program" and implicit using
s. If you're like me and want or need to frequently test projects using different target frameworks, it's no longer possible to change the <TargetFramework>
version. While it's possible to use dotnet new console -f net5.0
to get the older .NET 5 new console app template, I really like top level projects and implicit usings for quick test programs.
How to change the .NET 6 project template
Here's a diff of the .NET 6 dotnet new console
project file, and the changes that I apply:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
- <TargetFramework>net6.0</TargetFramework>
+ <TargetFrameworks>net6.0;net48</TargetFrameworks>
+ <LangVersion>10</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
+ <ItemGroup Condition=" '$(TargetFrameworkIdentifier)' == '.NETFramework' ">
+ <Reference Include="System.Net.Http" />
+ </ItemGroup>
+
</Project>
You might have seen MSBuild conditions like '$(TargetFramework)' == 'net48'
before, but the problem with this is if you change which version of the .NET Framework you target, or if you target multiple, then you have to manage that list in multiple places. By using TargetFrameworkIdentifier
instead, it will automatically work for all .NET Framework versions. Well, except that System.Net.Http
only existed from 4.5, so if you target 4.0 or earlier the implicit using System.Net.Http
will fail. But .NET Framework 4.5 came out in 2012, so I'm going to pretend that nobody has a valid reason to target such old versions any longer.
TL;DR
Here's another copy of the project file, but not in diff format, so you can copy-paste into your csproj
:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworks>net6.0;net48</TargetFrameworks>
<LangVersion>10</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup Condition=" '$(TargetFrameworkIdentifier)' == '.NETFramework' ">
<Reference Include="System.Net.Http" />
</ItemGroup>
</Project>
The .NET team have a docs page on how to create your own template package. Following it, you can create your own new project template, and if you call it something short and quick to type like c
, then you'll be able to use dotnet new c
to get your preferred project template.