Rules such as "the simulation layer does not use the wall clock" or "the domain layer does not reference the UI" erode over time while they live only in documents. Making them part of the build and the tests surfaces a violation on the first attempt. This article covers shared MSBuild settings, central package versions, Roslyn's banned API analyzer, architecture tests and property-based testing with FsCheck, with examples.
Directory.Build.props and central package versions
MSBuild automatically imports the first Directory.Build.props it finds walking up from the project folder into every project. Shared settings such as the target framework, Nullable, TreatWarningsAsErrors and the version number live in one place. The version can be read from a JSON file with MSBuild property functions, so the application, the packaging script and the website share one source.
Central package management is enabled with ManagePackageVersionsCentrally in Directory.Packages.props, where each package version is declared with a PackageVersion item. Projects write PackageReference without a version; a project that sets one gets error NU1008. This keeps the same package from drifting to different versions in two projects.
<!-- Directory.Build.props: imported by every project below this folder -->
<Project>
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<VersionJson>$([System.IO.File]::ReadAllText('$(MSBuildThisFileDirectory)version.json'))</VersionJson>
<Version>$([System.Text.RegularExpressions.Regex]::Replace($(VersionJson), '(?s).*"version"\s*:\s*"([^"]+)".*', '$1'))</Version>
</PropertyGroup>
<PropertyGroup Condition="$(MSBuildProjectName.EndsWith('.Tests'))">
<IsPackable>false</IsPackable>
</PropertyGroup>
</Project>
<!-- Directory.Packages.props: one version per package for the whole repository -->
<Project>
<PropertyGroup>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="Microsoft.Data.Sqlite" Version="10.0.13" />
<PackageVersion Include="Microsoft.CodeAnalysis.BannedApiAnalyzers" Version="3.3.4" />
<PackageVersion Include="FsCheck.Xunit" Version="3.0.0" />
</ItemGroup>
</Project>Microsoft Learn — Customize the build by folder
Microsoft Learn — Central Package Management
Build channels and conditional settings
To produce different distributions from the same source, such as a demo and a full version or a store build and a standalone build, pass a property on the command line: dotnet build -p:Channel=Demo. Projects add a different ProjectReference or DefineConstants based on that value. Writing the channel name into the assembly with an AssemblyMetadata item makes it readable at runtime and lets crash reports include it.
The .NET SDK turns Optimize on by default only for a configuration named Release. Check the value explicitly for configurations with other names, such as a game engine's export configuration. dotnet msbuild -getProperty:Optimize -p:Configuration=ExportRelease shows the final value of the property without building.
Microsoft Learn — Property functions
A banned API list with BannedApiAnalyzers
The Microsoft.CodeAnalysis.BannedApiAnalyzers package reports uses of the APIs listed in BannedSymbols.txt with diagnostic RS0030. The file is added to the project as AdditionalFiles. Each line holds a symbol in documentation comment ID format, optionally followed by a semicolon and an explanation: T: for types, M: for methods, P: for properties and F: for fields.
A deterministic simulation project can ban DateTime.Now, Guid.NewGuid, the Random constructors and the Parallel class. With TreatWarningsAsErrors on, a violation stops the build. The list is added only to the relevant projects; UI and tool projects keep using these APIs. A truly necessary exception is opened with a local #pragma warning disable RS0030 and a written reason.
BannedSymbols.txt
P:System.DateTime.Now;Use the simulation clock
P:System.DateTime.UtcNow;Use the simulation clock
M:System.Guid.NewGuid;Derive identifiers from the match seed
M:System.Random.#ctor;Use a seeded Xoshiro256StarStar stream
M:System.Random.#ctor(System.Int32);System.Random is not stable across .NET versions
T:System.Threading.Tasks.Parallel;Iteration order must stay deterministic
Simulation.csproj
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.BannedApiAnalyzers" PrivateAssets="all" />
<AdditionalFiles Include="BannedSymbols.txt" />
</ItemGroup>dotnet/roslyn-analyzers — BannedApiAnalyzers
Architecture tests: reading project references
A layering rule such as "the domain layer does not reference the database or the game engine" can be checked with an xUnit test. The test opens the .csproj file with XDocument, reads the Include values of ProjectReference and PackageReference items, and fails with the reference name when a forbidden one is present. The message states clearly which project added which reference.
Assembly.GetReferencedAssemblies is not enough on its own: the compiler does not write a reference that the code never uses into the output assembly. A forbidden reference that was added but is not used yet would slip through. Reading the project file checks intent and inspecting the compiled assembly checks actual use; the two can be combined.
Property-based testing with FsCheck
Example-based tests try a few chosen inputs; property-based tests check a rule against hundreds of random inputs. The Property attribute from the FsCheck.Xunit package generates values for the method's parameters. When an input breaks the rule, FsCheck shrinks it to the simplest example that still fails and prints the seed needed to reproduce it.
Passing that seed to the Replay parameter of the Property attribute regenerates the same input sequence, so debugging no longer depends on chance. MaxTest sets how many inputs are tried. The default suits quick feedback; raise it for critical conversions such as serialization.
using FsCheck.Xunit;
public static class Grid
{
public static int Wrap(int value, int size) => ((value % size) + size) % size;
}
public class GridProperties
{
[Property]
public bool Wrap_stays_in_range(int value)
{
int w = Grid.Wrap(value, 64);
return w >= 0 && w < 64;
}
[Property]
public bool Wrap_is_idempotent(int value) =>
Grid.Wrap(Grid.Wrap(value, 64), 64) == Grid.Wrap(value, 64);
[Property(MaxTest = 500)]
public bool Hex_round_trips(byte[] data) =>
data is null || Convert.FromHexString(Convert.ToHexString(data)).SequenceEqual(data);
}
// After a failure, pin the reported seed: [Property(Replay = "<seed from the output>")]Which properties to write
Good properties usually follow a few patterns: invariants (the result always stays in a range), round trips (serializing and deserializing returns the same value), idempotence (applying twice equals applying once) and comparison with a simple reference implementation. Save formats, wrapping map coordinates and resource calculations fit these patterns well.
Default generators produce values from a type's whole range. Define a custom generator (Arbitrary) for objects that carry domain rules; otherwise most attempts are spent on invalid inputs. Deterministic simulations offer one more valuable property: running the simulation twice with the same seed and the same command sequence must produce the same state hash.