Search code examples
visual-studio.net-corecsprojconditional-compilationmultitargeting

Conditional compilation constant not working in a .net core multitargeted sdk-style project


Here is how the conditional compilation constants were initially defined (notice multitargeting):

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFrameworks>netstandard2.0;netcoreapp2.0;net461</TargetFrameworks>
  </PropertyGroup>

  <PropertyGroup Condition=" '$(TargetFramework)' == 'netcoreapp2.0' OR '$(TargetFramework)' == 'netstandard2.0'">
    <DefineConstants>NETCORE;</DefineConstants>
  </PropertyGroup>

  <PropertyGroup Condition=" '$(TargetFramework)' == 'net461'">
    <DefineConstants>NETFULL;</DefineConstants>
  </PropertyGroup>
  ...

</Project>

At that time NETCORE constant was working fine.

#if NETCORE
    // Works Fine! Not gray in VS; Compiler recognizes code!
    public string Abc { get; set; }   
#endif

I was working with my code and my assembly didn't compile at that time.


After that I added additional conditional compilation constant (not editing the previous ones - NETFULL and NETCORE):

<PropertyGroup Condition=" '$(TargetFramework)' == 'netcoreapp2.0'">
    <DefineConstants>NETCOREONLY;</DefineConstants>
</PropertyGroup>

Overall code (assembly) still not compiling.

And deleted this additional NETCOREONLY as not needed, leaving only the previous ones (NETCORE and NETFULL).

Overall code (assembly) still not compiling.

The problem is that NETCORE stopped working like it had been before.

I'm switching to netcoreapp2.0 platform, but the code in

#if NETCORE
    // Problem; Stays gray in VS; 
    // Compiler does not understand that it shoud consume this code
    public string Abc { get; set; }   
#endif

is not visible to compiler. It stays gray in VS. As if it is not netcoreapp2.0.

The following declaration

  <PropertyGroup Condition=" '$(TargetFramework)' == 'netcoreapp2.0' OR '$(TargetFramework)' == 'netstandard2.0'">
    <DefineConstants>NETCORE;</DefineConstants>
  </PropertyGroup>

should make NETCORE constant work for netcoreapp2.0, but it doesn't.


Solution

  • Make sure you only append to the DefineConstants property and not reset it to a new value completely:

    <PropertyGroup Condition="'$(TargetFramework)' == 'netcoreapp2.0' OR '$(TargetFramework)' == 'netstandard2.0'">
      <DefineConstants>$(DefineConstants);NETCORE</DefineConstants>
    </PropertyGroup>
    <PropertyGroup Condition="'$(TargetFramework)' == 'netcoreapp2.0'">
      <DefineConstants>$(DefineConstants);NETCOREONLY</DefineConstants>
    </PropertyGroup>