TheDoomDestroyer
TheDoomDestroyer

Reputation: 3085

Does Visual Studio ignore DefineConstants in csproj?

I have a CSPROJ in which I define my own constant / compiler directive.

<PropertyGroup>
    <DefineConstants>$(DefineConstants);MY_DIRECTIVE</DefineConstants>
    <MY_DIRECTIVE>true</MY_DIRECTIVE>
</PropertyGroup>

Then I proceed to include its use somewhere in my application, like this:

#if MY_DIRECTIVE
    System.Console.WriteLine("Yes");
#else
    System.Console.WriteLine("No");
#endif

Picture:

Visual Studio view

That works fine after building and running the application, but Visual Studio has both lines (Yes and No) highlighted, so if I were to do something like <MY_DIRECTIVE>false</MY_DIRECTIVE>, Visual Studio should "hide" and grey out and ignore the line where it says System.Console.WriteLine("Yes");, shouldn't it? I would expect it to, but it doesn't. Am I doing something wrong?

Upvotes: 0

Views: 1347

Answers (1)

mu88
mu88

Reputation: 5434

This is not going to work because the MSBuild property (<MY_DIRECTIVE>true</MY_DIRECTIVE>) has nothing to do with the C# preprocessor directive (<DefineConstants>$(DefineConstants);MY_DIRECTIVE</DefineConstants>) - these are two independent concepts.

If you want to trigger the #else branch you have to bring these concepts together, e. g.:

<PropertyGroup>
    <MY_DIRECTIVE>true</MY_DIRECTIVE>
    <DefineConstants Condition="'$(MY_DIRECTIVE)' == 'true'">$(DefineConstants);MY_DIRECTIVE</DefineConstants>
</PropertyGroup>

Upvotes: 4

Related Questions