how is #if / #endif different than if?

It's useful when you need two (or more) versions of your code with little difference. Then instead of keeping two projects using complier directives like #if TEST you write both versions in the same project. Then from project properties you can set value for TEST llike TEST = true and then compile the project.

#if TEST
    Console.WriteLine("Hello World!");
#else
    Console.WriteLine("Goodbye World!");
#endif 

If TEST = true it's like you just write : Console.WriteLine("Hello World!"); and vice versa.


These are for compiler constants, for example:

#if DEBUG
  Debug.WriteLine("This is written in debug mode");
#endif

If the DEBUG constant is defined, that code gets compiled, if it's not then it's stripped out, ignored by the compiler..it's a way to determine what's in a certain build type, and stripped out for another.

It's usually used for additional debug type statements, but it's extensible enough to have many applications, testing code in your case.


Because using #IF will determine if the code is compiled or not.

Using if will determine if the code is executed or not.

It seems there's an "environment" TEST that's defined in compile time. So if that environment exists, the

if (i % 2 == 0)
continue;

will be tested and executed: Only odd numbers will be printed.

The important thing to notice is that the compiled code changes depending on the existence of TEST. In a "NON-TEST environment" the

if (i % 2 == 0)
continue;

wont even exist when the application is executed.

what is the purpose of using #IF TEST instead of just if(TEST)?

TEST is not a variable, nor a constant. It doesn't even exist at run time. It is a flag passed to the compiler so it can decide on compiling some code (i.e putting it into the executable)

Maybe it would be clearer if the #if directive had something else inside. Lets modify your snippet to this:

#if TEST
            if (i == 5)
                System.exit(1)//Not a c# programmer;
#endif

In this case, under the existence of TEST, the program will only loop 5 times. On each iteration, i will be tested against 5. Wait a minute!!! It wont even compile!

If TEST is not defined, then the application will continue until another exit condition is reached. No comparison of i against 5 will be made. Read more on directives here:

#if, along with the #else, #elif, #endif, #define, and #undef directives, lets you include or exclude code based on the existence of one or more symbols. This can be useful when compiling code for a debug build or when compiling for a specific configuration.

Tags:

C#