Share via

MSBuild conditional constructs

MSBuild provides a mechanism for either/or processing with the Choose, When, and Otherwise elements.

Use the Choose element

The Choose element contains a series of When elements with Condition attributes that are tested in order from top to bottom until one evaluates to true. If more than one When element evaluates to true, only the first one is used. An Otherwise element, if present, will be evaluated if no condition on a When element evaluates to true.

Choose elements can be used as child elements of Project, When and Otherwise elements. When and Otherwise elements can have ItemGroup, PropertyGroup, or Choose child elements.


The following example uses the Choose and When elements for either/or processing. The properties and items for the project are set depending on the value of the Configuration property.

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" >
        <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
        <When Condition=" '$(Configuration)'=='Debug' ">
                <Compile Include="UnitTesting\*.cs" />
                <Reference Include="NUnit.dll" />
        <When Condition=" '$(Configuration)'=='retail' ">
    <!-- Rest of Project -->

In this example, a condition on a compiler constant DEFINED_CONSTANT is used. These are included in the DefinedConstants property. The regular expression is used to match the exact constant in a semicolon-separated list.

   <When Condition="$([System.Text.RegularExpressions.Regex]::IsMatch(
         $(DefineConstants), '^(.*;)*DEFINED_CONSTANT(;.*)*$'))">
      <!-- When DEFINED_CONSTANT is defined. -->
   <!-- other conditions -->

See also