Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In VS2022, how do I specify a conditional compilation symbol for a build configuration?

In VS2017, I had several different build configurations that built an application in different ways. One configuration would produce the default application. Another build configuration would produce the application with more features, etc.

This was done in the source code with #if FEATURE blocks. FEATURE was defined in the Conditional compilation symbols for a project's build configuration.

Now, I ported the code to Visual Studio 2022. It appears that the Conditional compilation symbols are now part of the project and not part of the build configuration. So I have to define FEATURE for the project and not the build configuration.

I've used #if FEATURE to put in attributes to classes and methods, so I can't replace this with a simple if statement in the source code.

I don't want to change the project settings every time I need to build the different applications.

What is the workaround for being able to build a project with different compilation symbols easily?

like image 481
Robert Avatar asked Oct 19 '25 05:10

Robert


1 Answers

Realise this is a year old now, but I've been looking at conditional compilation symbols this morning.

First, have a look at this: https://learn.microsoft.com/en-gb/dotnet/csharp/language-reference/compiler-options/language

The <DefineConstants> section deals with conditional compilation.

Edit the .csproj file directly, and in any applicable property group you can define constants that you can reference in code. e.g.

<PropertyGroup Condition="'$(Configuration)' == 'Debug'">
    <DefineConstants>MYDEBUGCONSTANT</DefineConstants>
</PropertyGroup>

Then in code you can use:

#if MYDEBUGCONSTANT
    // Some debug code
#endif

I had some issues with the conditions on the property groups, VS2022 got a little confused when two of the property groups applied at the same time. Once I sorted that everything worked as expected.

Hope that helps?

like image 64
David Brunning Avatar answered Oct 22 '25 07:10

David Brunning