2
  • I am writing C# code using Jetbrains Rider.
  • I would like to compile different behaviours depending on certain circumstances (as specified by my preprocessor constant). The idea is to have code such as this
#if MYCONSTANT
CallAGivenFunction();
#else
CallAnotherFunction();
#endif

So, if I want the first branch to be compiled (and seen by the Intellisense), I will define a preprocessor constant called MYCONSTANT; otherwise (by doing nothing), I will have the second branch be compiled.

Looking through the documentation I understood that I should create a file named Directory.build.props in the same folder as my .csproj, and that file should have

<Project>
    <PropertyGroup>
        <DefineConstants>MYCONSTANT</DefineConstants>
    </PropertyGroup>
</Project>

However after doing that, the code in the #if clause CallAGivenFunction(); is still greyed out (i.e. Rider does not recognize the preprocessor constant I have defined). What am I doing wrong?

Alterino
  • 43
  • 4
  • Did you try just adding them to the `csproj` file? https://learn.microsoft.com/en-us/visualstudio/msbuild/common-msbuild-project-properties?view=vs-2022. I believe Rider handles csproj much the same as VS – Flydog57 May 04 '23 at 03:23
  • @Flydog57, adding them to the csproj file MYCONSTANT did not work either. However, adding MYCONSTANT to the already existing AnyCPU true false bin\Debug\ DEBUG;TRACE;MYCONSTANT worked. – Alterino May 04 '23 at 03:47
  • Consider using Solution Configuration in combination with defines. Would give you drop down in the UI. – Ivan Shakhov May 04 '23 at 19:32

2 Answers2

1

You can declare preprocessors in your project's properties.

#if TEST
private void test_function_a(int a)
{
}
#else
private void test_function_b(int b)
{
}
#endif

You can then go into the project's properties and add a preprocess called TEST to use, like this

enter image description here

eloiz
  • 81
  • 9
  • This is equivalent to modifying the .csproj and adding MYCONSTANT to the DEBUG;TRACE that already exists in there. I am wondering if there isn't a solution that will use a separate file (that way I can build the same project in different ways on different machines (depending on the existence of that separate file) – Alterino May 04 '23 at 03:49
1

Within your .csproj file, some preprocessor directives are defined using the same <DefineConstants></DefineConstants> element that you are using within Directory.build.props. The element within .csproj overrides anything you create within Directory.build.props For your own constants to be be taken into account, you need to precede the element in .csproj with $(DefineConstants) (for example)

<DefineConstants>$(DefineConstants);DEBUG;TRACE;</DefineConstants>
Cois
  • 83
  • 7