Properties & Evaluation
MSBuild has three building blocks: properties (named strings), items (lists of things, usually files) and targets (steps that run tasks). This lesson is about properties, and about the rule that explains most surprises in MSBuild: a project is evaluated completely before any target runs.
Defining and reading properties
A property is set inside a <PropertyGroup> and read with $(Name). Everything is a string; an undefined property is an empty string, never an error.
mkdir props && cd props
cat > props.proj <<'XML'
<Project>
<PropertyGroup>
<Greeting>Hello</Greeting>
<Audience>world</Audience>
<Message>$(Greeting), $(Audience)!</Message>
<Audience>builders</Audience>
<Missing>[$(NoSuchProperty)]</Missing>
</PropertyGroup>
<Target Name="Show">
<Message Importance="high" Text="Message = $(Message)" />
<Message Importance="high" Text="Audience = $(Audience)" />
<Message Importance="high" Text="Missing = $(Missing)" />
<Message Importance="high" Text="Project = $(MSBuildProjectName) in $(MSBuildProjectDirectory)" />
</Target>
</Project>
XML
dotnet msbuild -nologo -v:m -t:Show Message = Hello, world!
Audience = builders
Missing = []
Project = props in /home/learner/props
This file has no Sdk attribute: it's a plain MSBuild project (.proj is the conventional extension), so it has only what we wrote. Three rules show up already:
- Properties are expanded when they are defined.
MessagecapturedworldbecauseAudiencewas redefined after it. MSBuild reads the file top to bottom. - The last definition wins. By the time the target runs,
Audienceisbuilders. - Undefined means empty.
$(NoSuchProperty)became nothing, without a warning. Typos in property names fail silently, which is why the query commands are so useful.
MSBuildProjectName and MSBuildProjectDirectory are reserved properties that MSBuild sets for every project. Others you'll use: MSBuildThisFileDirectory (the folder of the file being evaluated, which matters in imported .props), MSBuildProjectFullPath and MSBuildBinPath.
Where else properties come from
Properties have four sources, from weakest to strongest:
| Source | Example | Can the project override it? |
|---|---|---|
| Environment variables | Configuration=Release dotnet build |
yes: they act as defaults |
Properties in imported files (Sdk.props, Directory.Build.props) |
<Configuration Condition="'$(Configuration)' == ''">Debug</Configuration> |
yes, if your definition comes later |
| Properties in the project file | <Nullable>enable</Nullable> |
n/a |
| Global properties from the command line | -p:Configuration=Release, -c Release |
no |
mkdir layers && cd layers
cat > layers.proj <<'XML'
<Project>
<PropertyGroup>
<Flavor>from-project</Flavor>
<Answer Condition="'$(Answer)' == ''">42</Answer>
</PropertyGroup>
<Target Name="Show">
<Message Importance="high" Text="Flavor=$(Flavor) Answer=$(Answer) Home=$(HOME)" />
</Target>
</Project>
XML
dotnet msbuild -nologo -v:m -t:Show
Flavor=from-env Answer=7 dotnet msbuild -nologo -v:m -t:Show
dotnet msbuild -nologo -v:m -t:Show -p:Flavor=from-command-line Flavor=from-project Answer=42 Home=/home/learner
Flavor=from-project Answer=7 Home=/home/learner
Flavor=from-command-line Answer=42 Home=/home/learner
$(HOME)is just the environment variable: every environment variable is visible as a property.Flavor=from-envlost against the project's own definition.Answer=7won, because the project only setsAnswerwhen it's empty. ThatCondition="'$(X)' == ''"pattern is how SDK files define overridable defaults.-p:Flavor=…beat the project. Global properties are read-only for the whole build; assignments in project files are silently ignored.dotnet build -c Releaseis a global propertyConfiguration=Release, which is why no file can accidentally flip a release build back to Debug.
Evaluation happens before execution
MSBuild processes a project in two phases. Evaluation reads the project and every import, in passes: first all properties (including imports and conditions), then item definitions, then items. Only then does execution run targets. A consequence: a property set inside a target is invisible to evaluation, and a property defined late in the file is visible to all targets. This model reproduces the order:
project = [
("prop", "Configuration", "Debug", "'$(Configuration)' == ''"),
("item", "Compile", "src/$(Configuration).cs", None),
("prop", "Greeting", "Hi", None),
("prop", "OutDir", "bin/$(Configuration)/", None),
]
global_props = {"Configuration": "Release"}
def expand(text, props):
for name, value in props.items():
text = text.replace(f"$({name})", value)
return text
def holds(cond, props):
if cond is None:
return True
left, right = cond.split(" == ")
return expand(left, props) == expand(right, props)
props = dict(global_props)
print("pass 1: properties")
for kind, name, value, cond in project:
if kind != "prop":
continue
if name in global_props:
print(f" {name}: global property wins, definition ignored")
elif holds(cond, props):
props[name] = expand(value, props)
print(f" {name} = {props[name]}")
else:
print(f" {name}: condition false, skipped")
print("pass 2: items (all properties are final now)")
for kind, name, value, cond in project:
if kind == "item":
print(f" {name} += {expand(value, props)}")pass 1: properties
Configuration: global property wins, definition ignored
Greeting = Hi
OutDir = bin/Release/
pass 2: items (all properties are final now)
Compile += src/Release.cs
The item was declared before OutDir and the other properties in the file, but it saw their final values, because items are evaluated in a later pass. Real MSBuild has more passes (imports are expanded inline, ItemDefinitionGroups come between properties and items, UsingTask comes last), but "all properties first, then items" is the part that explains everyday surprises.
Property functions
Inside $( ) you can call a whitelisted set of .NET methods and MSBuild helpers. They're evaluated at evaluation time like any other property:
mkdir funcs && cd funcs
cat > funcs.proj <<'XML'
<Project>
<PropertyGroup>
<Version>2.7.1-beta.3</Version>
<Major>$(Version.Split('.')[0])</Major>
<IsPrerelease>$(Version.Contains('-'))</IsPrerelease>
<NextMajor>$([MSBuild]::Add($(Major), 1))</NextMajor>
<Upper>$(MSBuildProjectName.ToUpperInvariant())</Upper>
<Tools>$([System.IO.Path]::Combine($(MSBuildProjectDirectory), 'tools'))</Tools>
<Epoch>$([System.Environment]::GetEnvironmentVariable('SOURCE_DATE_EPOCH'))</Epoch>
<Newer>$([MSBuild]::VersionGreaterThan('10.0.2', '10.0.10'))</Newer>
</PropertyGroup>
<Target Name="Show">
<Message Importance="high" Text="Major=$(Major) Prerelease=$(IsPrerelease) NextMajor=$(NextMajor)" />
<Message Importance="high" Text="Upper=$(Upper) Tools=$(Tools)" />
<Message Importance="high" Text="Epoch=$(Epoch) 10.0.2 newer than 10.0.10? $(Newer)" />
</Target>
</Project>
XML
dotnet msbuild -nologo -v:m -t:Show Major=2 Prerelease=True NextMajor=3
Upper=FUNCS Tools=/home/learner/funcs/tools
Epoch=1767225600 10.0.2 newer than 10.0.10? False
String instance methods (Split, Contains, Replace, Trim…) work directly on a property. Static methods use $([Type]::Method(args)), and [MSBuild]:: offers arithmetic, version comparison (note that 10.0.2 is correctly older than 10.0.10, unlike a string comparison), GetPathOfFileAbove, NormalizePath, EnsureTrailingSlash and more. Keep them short: a property function that needs a comment should probably be a task in a target.
Test yourself
A project defines <A>x</A>, then <B>$(A)</B>, then <A>y</A>. What is $(B) when targets run?
- y
- x
- $(A)
- empty
The project sets <Flavor>debug</Flavor> and the build runs with -p:Flavor=release. Which value is used?
- debug, the project file wins
- release: global properties can't be overridden by project files
- Both, joined with a semicolon
- The build fails with a conflict error
Why can an item declared at the top of a project use a property defined at the bottom?
- MSBuild sorts the file alphabetically
- All properties are evaluated in an earlier pass than items
- Items are lazy and evaluated during targets only
- It can't; that's an error