TExcelTAD
Home › .NET Builds: MSBuild & NuGet › Properties & Evaluation

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.

bash · try it yourself
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:

  1. Properties are expanded when they are defined. Message captured world because Audience was redefined after it. MSBuild reads the file top to bottom.
  2. The last definition wins. By the time the target runs, Audience is builders.
  3. 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
bash · try it yourself
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-env lost against the project's own definition. Answer=7 won, because the project only sets Answer when it's empty. That Condition="'$(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 Release is a global property Configuration=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:

python · try it yourself
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:

bash · try it yourself
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?

  1. y
  2. x
  3. $(A)
  4. empty

The project sets <Flavor>debug</Flavor> and the build runs with -p:Flavor=release. Which value is used?

  1. debug, the project file wins
  2. release: global properties can't be overridden by project files
  3. Both, joined with a semicolon
  4. 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?

  1. MSBuild sorts the file alphabetically
  2. All properties are evaluated in an earlier pass than items
  3. Items are lazy and evaluated during targets only
  4. It can't; that's an error