Really often in more complicated SDK style projects you need to specify conditions. For instance, when targeting specific version of a .NET Framework, you might want to add extra reference and so on.
It goes similar to this:
<ItemGroup Condition="'$(TargetFramework)' != 'net6.0'"> <PackageReference Include="System.Text.Json" Version="6.0.5"/> </ItemGroup>
which says to reference
System.Text.Json for anything not targeting
They are actually complicated, but this may be all you need:
- Compare for equality (
==) or inequality (
- Compare numeric values (
>=). This is used extremely rarely. This also supports
- Check if a folder exists (
- Check if a string contains forward or backward trailing slash (
- Negate (
- Logical grouping (
Or) with brackets to change priority (
- Really simple If/Else/Then block (
- As strings in those conditions are actually an instance of .NET’s
System.String, you can use any string method from it.
To build condition, you’ll compare something to something, and there’s a whole lot of built-in properties.
Generate nuget package on build, but only in Release mode
<PropertyGroup Condition="'$(Configuration)' == 'Release'"> <GeneratePackageOnBuild>true</GeneratePackageOnBuild> </PropertyGroup>
Target different frameworks when building on Windows
Let’s say we are targeting
.NET 6 in general, but when building on Windows we also want to target
.NET 4.6.1, because it’s not available elsewhere. We can use the Choose Element to make things simpler:
<Choose> <When Condition="'$(OS)' == 'Windows_NT'"> <PropertyGroup> <TargetFrameworks>net6.0;net461</TargetFrameworks> </PropertyGroup> </When> <Otherwise> <PropertyGroup> <TargetFrameworks>net6.0</TargetFrameworks> </PropertyGroup> </Otherwise> </Choose>
To contact me, send an email anytime or leave a comment below.