Search code examples
msbuildnuget-packagevisual-studio-macmultitargetingmsbuild-projectreference

Conditional reference in Visual Studio Community 2017


I am creating a multi-platform application. I have a multi-targeted shared library (targeting .netstandard 2.0 and .net 4.5)...See project file:

  <PropertyGroup>
    <TargetFrameworks>netstandard2.0;net45</TargetFrameworks>
  </PropertyGroup>

When I build the project in visual studio 2017 on windows, I get two directories in the output (netstandard2.0, net45) and the corresponding dlls. The build is a success.

When I build the exact same project (same code) in visual studio 2017 on a mac, I get errors of this nature:

The type 'OptionAttribute' exists in both 'CommandLine.DotNetStandard, Version=1.0.30' and 'CommandLine, Version=1.9.71.2'

I conditionally referenced a command line parser library in the following way:

  <!-- CommandLineParser library -->
  <ItemGroup Condition="'$(TargetFramework)' == 'netstandard2.0'">
    <PackageReference Include="CommandLine.DotNetStandard">
      <Version>1.0.3</Version>
    </PackageReference>
  </ItemGroup>

  <ItemGroup Condition="'$(TargetFramework)' == 'net45'">
    <PackageReference Include="CommandLineParser">
      <Version>1.9.71</Version>
    </PackageReference>
  </ItemGroup>

This works great for windows, but on the mac it appears it is not observing the condition. Is this a known bug for visual studio on mac? Am I doing something wrong?


Solution

  • Visual Studio ignores the condition in these cases. Use a Choose/When instead, that should be fully supported: https://msdn.microsoft.com/en-us/library/ms164282.aspx

    <Choose> 
      <When Condition=" '$(TargetFramework)' == 'netstandard2.0' ">
        <ItemGroup>
          <PackageReference Include="CommandLine.DotNetStandard">
            <Version>1.0.3</Version>
          </PackageReference>
        </ItemGroup>
      </When>
      <When Condition=" '$(TargetFramework)' == 'net45' ">
        <ItemGroup> 
          <PackageReference Include="CommandLineParser">
            <Version>1.9.71</Version>
          </PackageReference>
        </ItemGroup>
      </When>
    </Choose>