17

I want to compile a project differently, according to a constant defined by #define, like this:

#define USE_COMPONENT_X

#if USE_COMPONENT_X
...

#endif

and I can do that in C#. But when I go to another file in the same project, this constant is not defined. Can I in some way define a constant to all the project, like DEBUG is defined so?

Victor Rodrigues
  • 11,353
  • 23
  • 75
  • 107

5 Answers5

32

You can add the /define compiler switch.

  1. Open the project's Property Pages dialog box.
  2. Click the Configuration Properties folder.
  3. Click the Build property page.
  4. Modify the Conditional Compilation Constants property.
Jason Diller
  • 3,360
  • 2
  • 24
  • 25
6

You may want to go a step further and create different project configurations as variants of the standard Debug and Release project configuration. The Configuration Manager under the build menu will let you accomplish this. Then while you are in the project properties' Build tab you can select the various configurations and set the conditional compilation constants that are appropriate for each configuration. This will save you lots of time when you want to swap back and forth between various permutations of your conditionally compiled code.

1

Hopefully I'm not way off topic, but rather than a "constant" perhaps define an interface for the constant's type and then use one of the many dependency injection frameworks to manage the definition, injection and lifetime of your "constant".

Reddog
  • 15,219
  • 3
  • 51
  • 63
  • Can you explain more about this? – Victor Rodrigues Jan 12 '09 at 18:17
  • 2
    This sounds like something you would do to alter the course of an application during runtime, not during compile time (which the author is talking about). If the /define constant is set, the code shouldn't be included in the resulting assembly. – Astra Jan 12 '09 at 18:36
0

Set it in your IDE or use the the compiler command line switch i.e. -define for Mono.

polyethene
  • 79
  • 1
  • 4
0

You can do it like this:

#define DEBUG_DIFF  //uncomment to enable debug code.
using System;
namespace Common
{
  class Scrapper
  {
    //Debug helper switches
#if DEBUG_DIFF  
    public const bool Load_From_Serialized_Controltrees = true;
    public const bool Insert_Debug_Grid = true;
#else
    public const bool Load_From_Serialized_Controltrees = false;
    public const bool Insert_Debug_Grid = false;

#endif
  }

}
VarunB
  • 81
  • 6