Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Define a preprocessor directive constant conditionally

How can I make it work?

In C# code:

if (condition)
{
    #define CONSTANT
}

I tried doing something through <DefineConstants Condition="'$condition'"></DefineConstants> in a project file’s <PropertyGroup> section.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But it won’t work because the condition will be based on something that we know AFTER the program is built.

>Solution :

No; your runtime code (if) cannot affect compile-time directives (#define). You need to use another approach. Maybe use a static readonly bool that you calculate once at runtime – the JIT on up-to-date .NET versions will usually treat this the same as a const, and perform dead-code removal appropriately during the JIT process, making if (SomeStaticReadOnlyOrConst) almost the same as #if SOME_SYMBOL.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading