.csproj (.NET SDK Projects) Condition Cheat Sheet

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"/>

which says to reference System.Text.Json for anything not targeting .NET 6.


They are actually complicated, but this may be all you need:

  1. Compare for equality (==) or inequality (!=).
  2. Compare numeric values (<,>, <=, >=). This is used extremely rarely. This also supports System.Version.
  3. Check if a folder exists (Exists(path)).
  4. Check if a string contains forward or backward trailing slash (HasTrailingSlash(str)).
  5. Negate (!).
  6. Logical grouping (And and Or) with brackets to change priority (()).
  7. Really simple If/Else/Then block ($if$ (%expression%), $elseif, $endif).
  8. 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.

Practical Examples

Generate nuget package on build, but only in Release mode

<PropertyGroup Condition="'$(Configuration)' == 'Release'">

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:

    <When Condition="'$(OS)' == 'Windows_NT'">

To contact me, send an email anytime or leave a comment below.