Msbuild Antipatterns
.NET (Microsoft)OfficialPublished by .NET (Microsoft)
- Skill
- Review and audit
- Software development
- MIT
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
The MSBuild Anti-Pattern Catalog provides a structured reference for identifying common mistakes in MSBuild project files. It focuses on maintainability, correctness, and build performance by highlighting smells, explaining their negative impacts, and providing concrete fixes. This skill is designed for auditing existing MSBuild configurations to ensure they follow best practices, such as leveraging built-in tasks, maintaining incremental build integrity, and properly structuring properties and imports. It is intended for analysis and review purposes rather than automated migration.
What it does
- Identifies common MSBuild anti-patterns like hardcoded paths and redundant SDK properties.
- Provides clear 'Smell', 'Why it's bad', and 'Fix' guidance for each pattern.
- Offers rules for auditing project files for maintainability and correctness.
- Distinguishes between style preferences and actual functional defects.
- Includes guidance on incremental build optimization using Inputs and Outputs.
- Provides instructions for handling cross-platform pathing and conditional imports.
When to use it
- When performing a broad audit or linting of MSBuild project files.
- When investigating build performance issues related to non-incremental targets.
- When checking for cross-platform compatibility risks in build logic.
- When reviewing project files for maintainability and adherence to modern MSBuild standards.
- When troubleshooting build errors caused by incorrect property evaluation or import order.
Advantages
- Reduces build maintenance burden by promoting centralized property management.
- Improves build performance by enabling effective incremental builds.
- Enhances cross-platform reliability by identifying shell-dependent or OS-specific logic.
- Provides actionable, prioritized findings for project file improvements.
- Helps prevent common pitfalls like version drift and redundant file listing.
Usage examples
- “Review this project file for common MSBuild anti-patterns and suggest improvements.”
- The agent will scan the file, identify specific anti-patterns (e.g., hardcoded paths, missing incremental build attributes), and provide a prioritized list of findings with recommendations.
- “Why is my build running every time even when nothing changed?”
- The agent will audit the custom targets in the project file, identify missing 'Inputs' and 'Outputs' attributes, and explain how to implement incremental build logic.
- “Are these backslashes in my .targets file going to break the build on Linux?”
- The agent will analyze the usage of backslashes to determine if they are passed to MSBuild's evaluator (safe) or to a raw shell command (unsafe), providing a clear verdict.
- “Audit my project file for redundant properties that are already covered by the .NET SDK.”
- The agent will compare the project's properties against standard SDK defaults and identify which ones can be safely removed to reduce noise.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/dotnet/msbuild-antipatterns/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip msbuild-antipatterns.zip -d .agents/skills
Documentation by .NET (Microsoft)
MSBuild Anti-Pattern Catalog
A numbered catalog of common MSBuild anti-patterns. Each entry follows the format:
Smell: What to look for
Why it's bad: Impact on builds, maintainability, or correctness
Fix: Concrete transformation
Use this catalog when scanning project files for improvements.
Review output contract
For review, audit, maintainability, or correctness-risk requests:
Do not edit files unless the user explicitly asks for fixes.
Return prioritized findings grounded in the supplied file, with impact and a targeted recommendation.
Separate confirmed defects from conditional risks and already-correct patterns.
Keep the final answer as the review; do not replace it with a terse summary of changes.
AP-01: <Exec> for Operations That Have Built-in Tasks
Smell: <Exec Command="mkdir ..." />, <Exec Command="copy ..." />, <Exec Command="del ..." />
Why it's bad: Built-in tasks are cross-platform, support incremental build, emit structured logging, and handle errors consistently. <Exec> is opaque to MSBuild.
<!-- BAD -->
<Target Name="PrepareOutput">
<Exec Command="mkdir $(OutputPath)logs" />
<Exec Command="copy config.json $(OutputPath)" />
<Exec Command="del $(IntermediateOutputPath)*.tmp" />
</Target>
<!-- GOOD -->
<Target Name="PrepareOutput">
<MakeDir Directories="$(OutputPath)logs" />
<Copy SourceFiles="config.json" DestinationFolder="$(OutputPath)" />
<Delete Files="@(TempFiles)" />
</Target>Built-in task alternatives:
| Shell Command | MSBuild Task |
|---|---|
mkdir | <MakeDir> |
copy / cp | <Copy> |
del / rm | <Delete> |
move / mv | <Move> |
echo text > file | <WriteLinesToFile> |
touch | <Touch> |
xcopy /s | <Copy> with item globs |
AP-02: Unquoted Condition Expressions
Smell: Condition="$(Foo) == Bar" — either side of a comparison is unquoted.
Why it's bad: If the property is empty or contains spaces/special characters, the condition evaluates incorrectly or throws a parse error. MSBuild requires single-quoted strings for reliable comparisons.
<!-- BAD -->
<PropertyGroup Condition="$(Configuration) == Release">
<Optimize>true</Optimize>
</PropertyGroup>
<!-- GOOD -->
<PropertyGroup Condition="'$(Configuration)' == 'Release'">
<Optimize>true</Optimize>
</PropertyGroup>Rule: Always quote both sides of == and != comparisons with single quotes.
AP-03: Hardcoded Absolute Paths
Smell: Paths like C:\tools\, D:\packages\, /usr/local/bin/ in project files.
Why it's bad: Breaks on other machines, CI environments, and other operating systems. Not relocatable.
<!-- BAD -->
<PropertyGroup>
<ToolPath>C:\tools\mytool\mytool.exe</ToolPath>
</PropertyGroup>
<Import Project="C:\repos\shared\common.props" />
<!-- GOOD -->
<PropertyGroup>
<ToolPath>$(MSBuildThisFileDirectory)tools\mytool\mytool.exe</ToolPath>
</PropertyGroup>
<Import Project="$(RepoRoot)eng\common.props" />Preferred path properties:
| Property | Meaning |
|---|---|
$(MSBuildThisFileDirectory) | Directory of the current .props/.targets file |
$(MSBuildProjectDirectory) | Directory of the .csproj |
$([MSBuild]::GetDirectoryNameOfFileAbove(...)) | Walk up to find a marker file |
$([MSBuild]::NormalizePath(...)) | Combine and normalize path segments |
AP-04: Restating SDK Defaults
Smell: Properties set to values that the .NET SDK already provides by default.
Why it's bad: Adds noise, hides intentional overrides, and makes it harder to identify what's actually customized. When defaults change in newer SDKs, the redundant properties may silently pin old behavior.
<!-- BAD: All of these are already the default -->
<PropertyGroup>
<OutputType>Library</OutputType>
<EnableDefaultItems>true</EnableDefaultItems>
<EnableDefaultCompileItems>true</EnableDefaultCompileItems>
<RootNamespace>MyLib</RootNamespace> <!-- matches project name -->
<AssemblyName>MyLib</AssemblyName> <!-- matches project name -->
<AppendTargetFrameworkToOutputPath>true</AppendTargetFrameworkToOutputPath>
</PropertyGroup>
<!-- GOOD: Only non-default values -->
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
</PropertyGroup>AP-05: Manual File Listing in SDK-Style Projects
Smell: <Compile Include="File1.cs" />, <Compile Include="File2.cs" /> in SDK-style projects.
Why it's bad: SDK-style projects automatically glob **/*.cs (and other file types). Explicit listing is redundant, creates merge conflicts, and new files may be accidentally missed if not added to the list.
<!-- BAD -->
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Services\MyService.cs" />
<Compile Include="Models\User.cs" />
</ItemGroup>
<!-- GOOD: Remove entirely — SDK includes all .cs files by default.
Only use Remove/Exclude when you need to opt out: -->
<ItemGroup>
<Compile Remove="LegacyCode\**" />
</ItemGroup>Exception: Non-SDK-style (legacy) projects require explicit file includes. If migrating, see msbuild-modernization skill.
Exception (F# / .fsproj): F# compilation is order-dependent — the compiler processes <Compile Include> items sequentially and a file can only reference types/modules declared in files listed above it. .fsproj files must therefore list every source file explicitly, in dependency order (utility/leaf modules at the top, the entry point such as Program.fs at the bottom). If a .fsi signature file is used, it must appear immediately before its companion .fs implementation file.
AP-06: Using <Reference> with HintPath for NuGet Packages
Smell: <Reference Include="..." HintPath="..\packages\SomePackage\lib\..." />
Why it's bad: This is the legacy packages.config pattern. It doesn't support transitive dependencies, version conflict resolution, or automatic restore. The packages/ folder must be committed or restored separately.
<!-- BAD -->
<ItemGroup>
<Reference Include="Newtonsoft.Json">
<HintPath>..\packages\Newtonsoft.Json.13.0.3\lib\netstandard2.0\Newtonsoft.Json.dll</HintPath>
</Reference>
</ItemGroup>
<!-- GOOD -->
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>Note: <Reference> without HintPath is still valid for .NET Framework GAC assemblies like WindowsBase, PresentationCore, etc.
AP-07: Missing PrivateAssets="all" on Analyzer/Tool Packages
Smell: <PackageReference Include="StyleCop.Analyzers" Version="..." /> without PrivateAssets="all".
Why it's bad: Without PrivateAssets="all", analyzer and build-tool packages flow as transitive dependencies to consumers of your library. Consumers get unwanted analyzers or build-time tools they didn't ask for.
See references/private-assets.md for BAD/GOOD examples and the full list of packages that need this.
AP-08: Copy-Pasted Properties Across Multiple .csproj Files
Smell: The same <PropertyGroup> block appears in 3+ project files.
Why it's bad: Maintenance burden — a change must be made in every file. Inconsistencies creep in over time.
<!-- BAD: Repeated in every .csproj -->
<!-- ProjectA.csproj, ProjectB.csproj, ProjectC.csproj all have: -->
<PropertyGroup>
<Nullable>enable</Nullable>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<!-- GOOD: Define once in Directory.Build.props at the repo/src root -->
<!-- Directory.Build.props -->
<Project>
<PropertyGroup>
<Nullable>enable</Nullable>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
</Project>See directory-build-organization skill for full guidance on structuring Directory.Build.props / Directory.Build.targets.
AP-09: Scattered Package Versions Without Central Package Management
Smell: <PackageReference Include="X" Version="1.2.3" /> with different versions of the same package across projects.
Why it's bad: Version drift — different projects use different versions of the same package, leading to runtime mismatches, unexpected behavior, or diamond dependency conflicts.
<!-- BAD: Version specified in each project, can drift -->
<!-- ProjectA.csproj -->
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<!-- ProjectB.csproj -->
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />Fix: Use Central Package Management. See https://learn.microsoft.com/en-us/nuget/consume-packages/central-package-management for details.
AP-10: Monolithic Targets (Too Much in One Target)
Smell: A single <Target> with 50+ lines doing multiple unrelated things.
Why it's bad: Can't skip individual steps via incremental build, hard to debug, hard to extend, and the target name becomes meaningless.
<!-- BAD -->
<Target Name="PrepareRelease" BeforeTargets="Build">
<WriteLinesToFile File="version.txt" Lines="$(Version)" Overwrite="true" />
<Copy SourceFiles="LICENSE" DestinationFolder="$(OutputPath)" />
<Exec Command="signtool sign /f cert.pfx $(OutputPath)*.dll" />
<MakeDir Directories="$(OutputPath)docs" />
<Copy SourceFiles="@(DocFiles)" DestinationFolder="$(OutputPath)docs" />
<!-- ... 30 more lines ... -->
</Target>
<!-- GOOD: Single-responsibility targets -->
<Target Name="WriteVersionFile" BeforeTargets="CoreCompile"
Inputs="$(MSBuildProjectFile)" Outputs="$(IntermediateOutputPath)version.txt">
<WriteLinesToFile File="$(IntermediateOutputPath)version.txt" Lines="$(Version)" Overwrite="true" />
</Target>
<Target Name="CopyLicense" AfterTargets="Build">
<Copy SourceFiles="LICENSE" DestinationFolder="$(OutputPath)" SkipUnchangedFiles="true" />
</Target>
<Target Name="SignAssemblies" AfterTargets="Build" DependsOnTargets="CopyLicense"
Condition="'$(SignAssemblies)' == 'true'">
<Exec Command="signtool sign /f cert.pfx %(AssemblyFiles.Identity)" />
</Target>AP-11: Custom Targets Missing Inputs and Outputs
Smell: <Target Name="MyTarget" BeforeTargets="Build"> with no Inputs / Outputs attributes.
Why it's bad: The target runs on every build, even when nothing changed. This defeats incremental build and slows down no-op builds.
See references/incremental-build-inputs-outputs.md for BAD/GOOD examples and the full pattern including FileWrites registration.
See incremental-build skill for deep guidance on Inputs/Outputs, FileWrites, and up-to-date checks.
AP-12: Setting Defaults in .targets Instead of .props
Smell: <PropertyGroup> with default values inside a .targets file.
Why it's bad: .targets files are imported late (after project files). By the time they set defaults, other .targets files may have already used the empty/undefined value. .props files are imported early and are the correct place for defaults.
<!-- BAD: custom.targets -->
<PropertyGroup>
<MyToolVersion>2.0</MyToolVersion>
</PropertyGroup>
<Target Name="RunMyTool">
<Exec Command="mytool --version $(MyToolVersion)" />
</Target>
<!-- GOOD: Split into .props (defaults) + .targets (logic) -->
<!-- custom.props (imported early) -->
<PropertyGroup>
<MyToolVersion Condition="'$(MyToolVersion)' == ''">2.0</MyToolVersion>
</PropertyGroup>
<!-- custom.targets (imported late) -->
<Target Name="RunMyTool">
<Exec Command="mytool --version $(MyToolVersion)" />
</Target>Rule: .props = defaults and settings (evaluated early). .targets = build logic and targets (evaluated late).
AP-13: Import Without Exists() Guard
Smell: <Import Project="some-file.props" /> without a Condition="Exists('...')" check.
Why it's bad: If the file doesn't exist (not yet created, wrong path, deleted), the build fails with a confusing error. Optional imports should always be guarded.
<!-- BAD -->
<Import Project="$(RepoRoot)eng\custom.props" />
<!-- GOOD: Guard optional imports -->
<Import Project="$(RepoRoot)eng\custom.props" Condition="Exists('$(RepoRoot)eng\custom.props')" />
<!-- ALSO GOOD: Sdk attribute imports don't need guards (they're required by design) -->
<Project Sdk="Microsoft.NET.Sdk">Exception — required imports: Imports that are required for the build to work correctly should fail fast — don't guard those. Guard imports that are optional or environment-specific (e.g., local developer overrides, CI-specific settings).
Exception — NuGet package forwarders: .props/.targets files inside a NuGet package's per-TFM build/ or buildTransitive/ folder routinely import a sibling file under buildTransitive/<tfm>/… without an Exists() guard. These are a package contract: the target file is guaranteed to be present in the restored package, even if it doesn't appear in the source tree at that relative path. The package layout is typically produced by:
A custom
.nuspecwith per-TFM<file>entries — e.g.<file src="buildTransitive\common\MyAdapter.props" target="buildTransitive\net8.0\MyAdapter.props" />— that copy files from a single source folder (such asbuildTransitive/common/) into per-TFM subfolders at pack time, or<None Update="...">/<Content Include="...">items in the.csprojwith a per-TFM<PackagePath>(e.g.<PackagePath>buildTransitive/net8.0/</PackagePath>), declared once per target TFM, orSDK conventions (e.g.
IncludeBuildOutput,BuildOutputTargetFolder) that place built outputs underbuild/<tfm>/.
Before flagging an unguarded <Import> inside a build/ or buildTransitive/ folder, resolve it against the packed layout — read every *.nuspec in the project directory and its immediate parent directory (shared nuspecs are common in mono-repos; do not walk further up), and any <PackagePath> metadata on <None>/<Content> items in the .csproj. Only flag if the target path is missing from both the source tree and the projected package layout. The dotnet-msbuild/extension-points skill — Source tree vs packed layout — documents the full cross-check procedure.
Forwarding buildTransitive/ → build/: forward through the sibling build/*.props / build/*.targets file (not directly to buildMultiTargeting/); when build/ is per-TFM (build/<tfm>/), include the TFM segment derived from the file's own folder (not $(TargetFramework)), or transitive consumers hit MSB4019. See the extension-points skill — Forwarding chain — for the rule and derivation expression.
AP-14: Backslashes in Paths — Where It Matters
Smell: Backslash path separators in .props/.targets files meant to run cross-platform.
Where this is a real bug (🔴 Error) — paths that MSBuild does not route through its path normalizer:
Raw shell strings inside
<Exec Command="...\tools\foo.exe ..." />— passed verbatim tobash/shon Unix, which treats\as an escape.Backslash-delimited paths inside CDATA blocks, embedded in source files written by
<WriteLinesToFile>, or constructed for non-MSBuild consumers (custom scripts, response files, environment variables).Paths handed to custom tasks that call OS file APIs directly without going through MSBuild path utilities.
Where this is only a style preference (🔵 Style) — paths that go through MSBuild's evaluator (<Import Project="...">, file-path properties consumed by built-in tasks like <Copy>/<MakeDir>/<Delete>, item Include=/Exclude= globs):
MSBuild's evaluator normalizes \ → / on Unix-like systems before resolving the path. See FileUtilities.MaybeAdjustFilePath and ConvertToUnixSlashes in microsoft/msbuild src/Framework/FileUtilities.cs. So <Import Project="$(MSBuildThisFileDirectory)..\..\build\common.props" /> resolves correctly on Linux/macOS today. Forward slashes are still preferred for consistency, but the import will not break and existing backslash-style imports should not be flagged as 🔴 Error.
<!-- 🔴 Error: \ in raw shell string breaks on Linux/macOS -->
<Exec Command="$(MSBuildThisFileDirectory)tools\release\sign.exe $(OutputPath)" />
<!-- 🔵 Style: \ in Import is normalized on Unix, but / is nicer -->
<Import Project="$(MSBuildThisFileDirectory)..\..\build\common.props" />
<!-- ✅ Recommended in new code -->
<Import Project="$(MSBuildThisFileDirectory)../../build/common.props" />Verification rule: Before flagging a backslash path as 🔴 Error, ask "does this string flow through MSBuild's evaluator, or is it handed verbatim to a non-MSBuild consumer?" Only the second case is a correctness defect.
Note: $(MSBuildThisFileDirectory) already ends with a platform-appropriate separator, so $(MSBuildThisFileDirectory)tools/mytool works on both platforms.
AP-15: Unconditional Property Override in Multiple Scopes
Smell: A property set unconditionally in both Directory.Build.props and a .csproj — last write wins silently.
Why it's bad: Hard to trace which value is actually used. Makes the build fragile and confusing for anyone reading the project files.
<!-- BAD: Directory.Build.props sets it, csproj silently overrides -->
<!-- Directory.Build.props -->
<PropertyGroup>
<OutputPath>bin\custom\</OutputPath>
</PropertyGroup>
<!-- MyProject.csproj -->
<PropertyGroup>
<OutputPath>bin\other\</OutputPath>
</PropertyGroup>
<!-- GOOD: Use a condition so overrides are intentional -->
<!-- Directory.Build.props -->
<PropertyGroup>
<OutputPath Condition="'$(OutputPath)' == ''">bin\custom\</OutputPath>
</PropertyGroup>
<!-- MyProject.csproj can now intentionally override or leave the default -->For additional anti-patterns (AP-16 through AP-23) and a quick-reference checklist, see additional-antipatterns.md.
Files
- ATTRIBUTION.mdAdded by AutoGineer854 B
- LICENSELicence file added by AutoGineer1.1 KiB
- SKILL.md18.9 KiB
- references/additional-antipatterns.md18.8 KiB
- references/incremental-build-inputs-outputs.md1.5 KiB
- references/private-assets.md1.0 KiB
references/additional-antipatterns.md
AP-16: Using <Exec> for String/Path Operations
Smell: <Exec Command="echo $(Var) | sed ..." /> or <Exec Command="powershell -c ..." /> for simple string manipulation.
Why it's bad: Shell-dependent, not cross-platform, slower than property functions, and the result is hard to capture back into MSBuild properties.
<!-- BAD -->
<Target Name="GetCleanVersion">
<Exec Command="echo $(Version) | sed 's/-preview//'" ConsoleToMSBuildProperty="CleanVersion" />
</Target>
<!-- GOOD: Property function -->
<PropertyGroup>
<CleanVersion>$(Version.Replace('-preview', ''))</CleanVersion>
<HasPrerelease>$(Version.Contains('-'))</HasPrerelease>
<LowerName>$(AssemblyName.ToLowerInvariant())</LowerName>
</PropertyGroup>
<!-- GOOD: Path operations -->
<PropertyGroup>
<NormalizedOutput>$([MSBuild]::NormalizeDirectory($(OutputPath)))</NormalizedOutput>
<ToolPath>$([System.IO.Path]::Combine($(MSBuildThisFileDirectory), 'tools', 'mytool.exe'))</ToolPath>
</PropertyGroup>AP-17: Mixing Include and Update for the Same Item Type in One ItemGroup
Smell: Same <ItemGroup> has both <Compile Include="..."> and <Compile Update="...">.
Why it's bad: Update acts on items already in the set. If Include hasn't been processed yet (evaluation order), Update may not find the item. Separating them avoids subtle ordering bugs.
<!-- BAD -->
<ItemGroup>
<Compile Include="Generated\Extra.cs" />
<Compile Update="Generated\Extra.cs" CopyToOutputDirectory="Always" />
</ItemGroup>
<!-- GOOD -->
<ItemGroup>
<Compile Include="Generated\Extra.cs" />
</ItemGroup>
<ItemGroup>
<Compile Update="Generated\Extra.cs" CopyToOutputDirectory="Always" />
</ItemGroup>AP-18: Redundant <ProjectReference> to Transitively-Referenced Projects
Smell: A project references both Core and Utils, but Core already depends on Utils.
Why it's bad: Adds unnecessary coupling, makes the dependency graph harder to understand, and can cause ordering issues in large builds. MSBuild resolves transitive references automatically.
<!-- BAD -->
<ItemGroup>
<ProjectReference Include="..\Core\Core.csproj" />
<ProjectReference Include="..\Utils\Utils.csproj" /> <!-- Core already references Utils -->
</ItemGroup>
<!-- GOOD: Only direct dependencies -->
<ItemGroup>
<ProjectReference Include="..\Core\Core.csproj" />
</ItemGroup>Caveat: If you need to use types from Utils directly (not just transitively), the explicit reference is appropriate. But verify whether the direct dependency is actually needed.
AP-19: Side Effects During Property Evaluation
Smell: Property functions that write files, make network calls, or modify state during <PropertyGroup> evaluation.
Why it's bad: Property evaluation happens during the evaluation phase, which can run multiple times (e.g., during design-time builds in Visual Studio). Side effects are unpredictable and can corrupt state.
<!-- BAD: File write during evaluation -->
<PropertyGroup>
<Timestamp>$([System.IO.File]::WriteAllText('stamp.txt', 'built'))</Timestamp>
</PropertyGroup>
<!-- GOOD: Side effects belong in targets -->
<Target Name="WriteTimestamp" BeforeTargets="Build">
<WriteLinesToFile File="stamp.txt" Lines="built" Overwrite="true" />
</Target>AP-20: Platform-Specific Exec Without OS Condition
Smell: <Exec Command="chmod +x ..." /> or <Exec Command="cmd /c ..." /> without an OS condition.
Why it's bad: Fails on the wrong platform. If the project is cross-platform, guard platform-specific commands.
<!-- BAD: Fails on Windows -->
<Target Name="MakeExecutable" AfterTargets="Build">
<Exec Command="chmod +x $(OutputPath)mytool" />
</Target>
<!-- GOOD: OS-guarded -->
<Target Name="MakeExecutable" AfterTargets="Build"
Condition="!$([MSBuild]::IsOSPlatform('Windows'))">
<Exec Command="chmod +x $(OutputPath)mytool" />
</Target>AP-21: Property Conditioned on TargetFramework in .props Files
Smell: <PropertyGroup Condition="'$(TargetFramework)' == '...'"> or <Property Condition="'$(TargetFramework)' == '...'"> in Directory.Build.props or any .props file imported before the project body.
Why it's bad: $(TargetFramework) is NOT reliably available in Directory.Build.props or any .props file imported before the project body. It is only set that early for multi-targeting projects, which receive TargetFramework as a global property from the outer build. Single-targeting projects (using singular <TargetFramework>) set it in the project body, which is evaluated after .props. This means property conditions on $(TargetFramework) in .props files silently fail for single-targeting projects — the condition never matches because the property is empty. This applies to both <PropertyGroup Condition="..."> and individual <Property Condition="..."> elements.
For a detailed explanation of MSBuild's evaluation and execution phases, see Build process overview.
<!-- BAD: In Directory.Build.props — TargetFramework may be empty here -->
<PropertyGroup Condition="'$(TargetFramework)' == 'net8.0'">
<DefineConstants>$(DefineConstants);MY_FEATURE</DefineConstants>
</PropertyGroup>
<!-- ALSO BAD: Condition on the property itself has the same problem -->
<PropertyGroup>
<DefineConstants Condition="'$(TargetFramework)' == 'net8.0'">$(DefineConstants);MY_FEATURE</DefineConstants>
</PropertyGroup>
<!-- GOOD: In Directory.Build.targets — TargetFramework is always available -->
<PropertyGroup Condition="'$(TargetFramework)' == 'net8.0'">
<DefineConstants>$(DefineConstants);MY_FEATURE</DefineConstants>
</PropertyGroup>
<!-- ALSO GOOD: In the project file itself -->
<!-- MyProject.csproj -->
<PropertyGroup Condition="'$(TargetFramework)' == 'net8.0'">
<DefineConstants>$(DefineConstants);MY_FEATURE</DefineConstants>
</PropertyGroup>⚠️ Item and Target conditions are NOT affected. This restriction applies ONLY to property conditions (<PropertyGroup Condition="..."> and <Property Condition="...">). Item conditions (<ItemGroup Condition="...">) and Target conditions in .props files are SAFE because items and targets evaluate after all properties (including those set in the project body) have been evaluated. This includes PackageVersion items in Directory.Packages.props, PackageReference items in Directory.Build.props, and any other item types.
Do NOT flag the following patterns — they are correct:
<!-- OK in Directory.Build.props — ItemGroup conditions evaluate late -->
<ItemGroup Condition="'$(TargetFramework)' == 'net472'">
<PackageReference Include="System.Memory" />
</ItemGroup>
<!-- OK in Directory.Packages.props — PackageVersion items evaluate late -->
<ItemGroup Condition="'$(TargetFramework)' == 'net8.0'">
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="8.0.11" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net9.0'">
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="9.0.0" />
</ItemGroup>
<!-- OK — Individual item conditions also evaluate late -->
<ItemGroup>
<PackageReference Include="System.Memory" Condition="'$(TargetFramework)' == 'net472'" />
</ItemGroup>AP-22: Forking a Project Instance via <MSBuild> with Path-Neutral Global Properties
Smell: A target uses the <MSBuild> task to build or publish a project, passing extra Properties that don't change that project's output path. Two common shapes:
<!-- (a) the SAME project re-invokes itself (publish-on-build) -->
<MSBuild Projects="$(MSBuildProjectFullPath)" Targets="Publish" Properties="_IsPublishing=true" />
<!-- (b) project A invokes Build/Publish on ANOTHER project B it consumes
(e.g. a test or layout project publishing a tool) -->
<MSBuild Projects="..\tool\tool.csproj" Targets="Publish" Properties="_IsPublishing=true" />Why it's bad: An MSBuild project instance is identified by its path plus its global properties. Passing an extra global property creates a distinct instance of the target project — (project, {_IsPublishing=true}) — that still resolves to the same OutputPath/IntermediateOutputPath as the instance the solution/graph already builds, (project, {}). That project is then built twice, and in a parallel/graph build the two instances can write the same files concurrently (PDBs, *.sourcelink and other NativeAOT intermediates, project.assets.json), producing The process cannot access the file because it is being used by another process or intermittent file-lock failures. This applies whether the offending <MSBuild> call is in the target project itself or in some other project in the same build. Use the check-bin-obj-clash skill to confirm two evaluations of that project differ only by a path-neutral property while sharing an output path.
<!-- BAD (a): forks a second instance (path + {_IsPublishing=true}) that shares this project's bin/obj -->
<Target Name="PublishOnBuild" AfterTargets="Build">
<MSBuild Projects="$(MSBuildProjectFullPath)" Targets="Publish" Properties="_IsPublishing=true" />
</Target><!-- GOOD (a): set the flag as a normal (non-global) property and run the target in the SAME instance -->
<PropertyGroup>
<!-- Capture whether the entry point already invoked publish (it sets _IsPublishing as a global prop). -->
<_PublishWasInvokedDirectly Condition="'$(_IsPublishing)' == 'true'">true</_PublishWasInvokedDirectly>
<_IsPublishing>true</_IsPublishing>
</PropertyGroup>
<Target Name="PublishOnBuild"
AfterTargets="Build"
DependsOnTargets="Publish"
Condition="'$(_PublishWasInvokedDirectly)' != 'true'" />For (a), the static property keeps everything in one instance (one output path, nothing to race); running Publish via DependsOnTargets (or CallTarget) reuses that instance instead of forking. The _PublishWasInvokedDirectly guard breaks the target cycle when publish is the entry point (e.g. dotnet publish, which sets _IsPublishing=true as a global property and would otherwise re-trigger PublishOnBuild).
<!-- BAD (b): A forks a publish instance of B that races B's own build in the graph -->
<MSBuild Projects="..\tool\tool.csproj" Targets="Publish" Properties="_IsPublishing=true" />
<!-- GOOD (b): make B publish as part of its OWN build (the (a) fix in tool.csproj), then have A
just sequence B and consume B's already-produced publish output — never re-publish it. -->
<ItemGroup>
<ProjectReference Include="..\tool\tool.csproj" ReferenceOutputAssembly="false" />
</ItemGroup>
<!-- A then reads tool's publish dir; it does not invoke Publish on tool. -->For (b), the consumer must not fork the producer with path-neutral global properties. Let the producer publish itself (one instance), reference it only to sequence the build, and read its output.
When extra global properties ARE fine: only when the output path encodes the discriminator (RuntimeIdentifier, TargetFramework, Configuration, Platform) so each instance writes to a distinct directory. If you must invoke a project with a path-neutral property, give that build its own BaseIntermediateOutputPath/output path so it can't collide.
AP-23: SetTargetFramework Metadata on a ProjectReference to a Non-Multi-Targeting Project
Smell: A <ProjectReference> carries SetTargetFramework="TargetFramework=net8.0" (or similar) metadata, the referenced project is single-targeting (uses singular <TargetFramework>, not <TargetFrameworks>), and the injected TFM equals the TFM the project already targets.
<!-- BAD: Tool.csproj single-targets net8.0 and we inject that SAME net8.0 — redundant AND harmful -->
<ItemGroup>
<ProjectReference Include="..\Tool\Tool.csproj" SetTargetFramework="TargetFramework=net8.0" />
</ItemGroup>Why it's bad: SetTargetFramework injects TargetFramework as a global property on the referenced project's build. That mechanism exists so a consumer can pick one specific TFM of a multi-targeting project — different TFM values produce different output paths, so each build is distinct and safe.
For a single-targeting project, injecting the TFM it already targets is path-neutral: the project already resolves to bin\<config>\net8.0\ and obj\<config>\net8.0\ on its own, so the extra global property doesn't change the output path — it only creates a distinct MSBuild project instance (project, {TargetFramework=net8.0}). Meanwhile the solution/graph builds that same project as (project, {}) with no global properties. Both instances resolve to the same OutputPath/IntermediateOutputPath, so the project is built twice and the two instances write the same files (assemblies, PDBs, project.assets.json, etc.). Under a parallel build this is a classic bin/obj clash — The process cannot access the file because it is being used by another process or intermittent, retry-flaky failures. (Injecting a different TFM changes the output path and is a legitimate override — see below.)
Note the healthy contrast: the P2P protocol itself does not inject TargetFramework when it sees a non-multi-targeting reference — it correctly omits the global property. SetTargetFramework overrides that safe default and is what reintroduces the clash. Use the check-bin-obj-clash skill to confirm two evaluations of the referenced project differ only by a path-neutral TargetFramework global property while sharing an output path.
<!-- GOOD: single-targeting reference needs no SetTargetFramework — just reference it -->
<ItemGroup>
<ProjectReference Include="..\Tool\Tool.csproj" />
</ItemGroup>When SetTargetFramework IS appropriate:
Multi-targeting reference — the referenced project is multi-targeting (
<TargetFrameworks>) and you deliberately need to consume a specific TFM. Each TFM has its own output path, so the forked instance doesn't collide.Deliberately overriding a single-targeting project's TFM to a different value — you can use
SetTargetFrameworkon a single-targeting reference to build it under a TFM other than the one it declares. This is only valid when the passed-in TFM differs from what the project single-targets: because the injectedTargetFrameworkthen changes the output path (obj\<config>\<different-tfm>\), the instance no longer collides with the(project, {})build. It is only the redundant case — passing the same TFM the project already targets (path-neutral) — that causes the clash.
Related: referencing a framework-incompatible project. Independently of the clash above, whenever the referencing and referenced projects target incompatible frameworks (e.g. a .NETFramework project referencing a .NETCoreApp project, or vice-versa) — regardless of whether either side is single- or multi-targeting — you must set both:
SkipGetTargetFrameworkProperties="true"— bypass the P2PGetTargetFrameworkPropertiesnegotiation, which would otherwise fail because the frameworks aren't compatible, andReferenceOutputAssembly="false"— because an assembly built for an incompatible framework can't be consumed as a reference; you only want to trigger/sequence the build, not reference its output.
<!-- OK: .NETFramework project builds an incompatible .NETCoreApp tool without referencing its assembly -->
<ProjectReference Include="..\Tool\Tool.csproj"
SkipGetTargetFrameworkProperties="true"
ReferenceOutputAssembly="false" />⚠️ Prevent the referencing project's TargetFramework from leaking. When SkipGetTargetFrameworkProperties="true" bypasses the negotiation, nothing stops the referencing project's own TargetFramework global property (present whenever the referencing project is being built for a specific TFM — e.g. it is multi-targeting) from flowing down into the referenced project. If it flows into a single-targeting referenced project, that project builds under the wrong TFM (and to a different, wrong output path). Guard against it one of two ways:
set
SetTargetFramework="TargetFramework=<tfm>"to explicitly pin the referenced build's TFM (also required for multi-targeting references), orfor a single-targeting referenced project you want to build as-declared, set
UndefineProperties="TargetFramework"to strip the inherited global property so the project uses its own<TargetFramework>.
<!-- OK: strip the referencing project's TargetFramework so the single-targeting tool builds as it declares -->
<ProjectReference Include="..\Tool\Tool.csproj"
SkipGetTargetFrameworkProperties="true"
UndefineProperties="TargetFramework"
ReferenceOutputAssembly="false" />Add SetTargetFramework on top of these only if you also need to pin the referenced build to a specific TFM (a multi-targeting project, or a single-targeting project you're overriding to a different TFM per case 2 above). Use SetTargetFramework or UndefineProperties="TargetFramework", not both — the former sets the property, the latter removes it.
Quick-Reference Checklist
When reviewing an MSBuild file, scan for these in order:
| # | Check | Severity |
|---|---|---|
| AP-02 | Unquoted conditions | 🔴 Error-prone |
| AP-19 | Side effects in evaluation | 🔴 Dangerous |
| AP-21 | Property conditioned on TargetFramework in .props | 🔴 Silent failure |
| AP-22 | Forking a project instance via <MSBuild> with path-neutral global properties (self or cross-project) | 🔴 Race/duplicate build |
| AP-23 | SetTargetFramework re-injecting a single-targeting project's own TFM on a ProjectReference | 🔴 Race/duplicate build |
| AP-03 | Hardcoded absolute paths | 🔴 Broken on other machines |
| AP-06 | <Reference> with HintPath for NuGet | 🟡 Legacy |
| AP-07 | Missing PrivateAssets="all" on tools | 🟡 Leaks to consumers |
| AP-11 | Missing Inputs/Outputs on targets | 🟡 Perf regression |
| AP-13 | Import without Exists guard | 🟡 Fragile |
| AP-05 | Manual file listing in SDK-style | 🔵 Noise |
| AP-04 | Restating SDK defaults | 🔵 Noise |
| AP-08 | Copy-paste across csproj files | 🔵 Maintainability |
| AP-09 | Scattered package versions | 🔵 Version drift |
| AP-01 | <Exec> for built-in tasks | 🔵 Cross-platform |
| AP-14 | Backslashes in cross-platform paths | 🔵 Cross-platform |
| AP-10 | Monolithic targets | 🔵 Maintainability |
| AP-12 | Defaults in .targets instead of .props | 🔵 Ordering issue |
| AP-15 | Unconditional property override | 🔵 Confusing |
| AP-16 | <Exec> for string operations | 🔵 Preference |
| AP-17 | Mixed Include/Update in one ItemGroup | 🔵 Subtle bugs |
| AP-18 | Redundant transitive ProjectReferences | 🔵 Graph noise |
| AP-20 | Platform-specific Exec without guard | 🔵 Cross-platform |
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- .NET (Microsoft)
- Publisher
- .NET (Microsoft) (Official)
- Source
- dotnet/skills · plugins/dotnet-msbuild/skills/msbuild-antipatterns · commit 96c3d68
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by .NET (Microsoft) or .NET (Microsoft).
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download msbuild-antipatterns.zip