Conditionals that are always false will be removed by the compiler in C #

Let's say I have the following code snippet in C #

static const bool DO_PERFORMANCE_CODE = false;

if (DO_PERFORMANCE_CODE)
{
   // performance monitoring code goes here
}

Will this code be deleted by the compiler? This is the functionality that I would like. Basically, I want to emulate conditional compilation materials in C #, but I need other configurations besides Release and Debug. If there is a better way to do this, I would be open to hear it.

+3
source share
7 answers

When creating "debugging", the DEBUG preprocessor variable is defined. So you can do this:

public void MyFunc()
{
//do release stuff
#if DEBUG
//do performance testing
#endif
//finish release stuff
}

and it will be ignored by the compiler when switching to Release mode.

, , , "#define PERFORMANCE_TESTING", , , .

#define PERFORMANCE_TESTING

    public void MyFunc()
    {
    //do release stuff
    #if PERFORMANCE_TESTING
    //do performance testing
    #endif
    //finish release stuff
    }
+8

, , , , , ( VS 2008 ).

:

class Program
{
    static void Main(string[] args)
    {
        bool foo = false;

        if (foo)
        {
            Console.WriteLine("Hello, world?");
        }
    }
}

if:

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       16 (0x10)
  .maxstack  1
  .locals init ([0] bool foo)
  IL_0000:  ldc.i4.0
  IL_0001:  stloc.0
  IL_0002:  ldloc.0
  IL_0003:  brfalse.s  IL_000f
  IL_0005:  ldstr      "Hello, world\?"
  IL_000a:  call       void [mscorlib]System.Console::WriteLine(string)
  IL_000f:  ret
} // end of method Program::Main

:

class Program
{
    static void Main(string[] args)
    {
        bool foo = false;

        if (false)
        {
            Console.WriteLine("Hello, world?");
        }
    }
}

if:

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       1 (0x1)
  .maxstack  8
  IL_0000:  ret
} // end of method Program::Main

, , .

ildasm.exe, , .

+3

Reflector Visual Studio 2008 SP1, , .

  • (#if SOMETHING_FALSE...) ,
  • (.. if (false) {... if (constant_declared_false) {...) , , ( , , ..).
  • false , .
+2

.

 #define temp

 #if temp
 // Do something
 #endif
+1

:

 #define SUPERDOOPERDEBUG

 using System;

 ....


 #if SUPERDOOPERDEBUG

     // something

 #endif

, , "" "" (. " → " " → "

+1

, DEBUG/RELEASE... :-), , ,

0

DEBUG RELEASE. #define .

0

All Articles