Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can C# preprocessor directives be nested?

I have done some googling around but have not found any positive statements about preprocessor directive nesting. I would like to be able to do something like this:

#if FOO
// do something
#if BAR
// do something when both FOO and BAR are defined
#endif 
#endif

I know I can do something like below instead but was just wondering.

#if FOO && (!BAR)
#elif FOO && BAR
#endif

(Edit) Actually I have a more complex nested statement already active in my code but it does not do what I expect. Hence my curiosity whether there is an official take on this.

like image 534
wecky Avatar asked Jul 24 '26 09:07

wecky


1 Answers

Yes, they can be nested.

#define A
#define B

void Main()
{
#if A
#if B
    Console.WriteLine("A and B");
#else
    Console.WriteLine("A and not B");
#endif
#else
#if B
    Console.WriteLine("B and not A");
#else
    Console.WriteLine("neither A nor B");
#endif
#endif
}

Outputs:

A and B

Here's a .NET Fiddle for you to try.

You can comment out the two lines at the top individually to get different results, like:

#define A
// #define B

Outputs:

A and not B

Here's the same code with indentation that makes it clearer, though I would not indent the code like this. Overuse of conditional directives like this is a code smell in my opinion.

#define A
// #define B

void Main()
{
    #if A
        #if B
            Console.WriteLine("A and B");
        #else
            Console.WriteLine("A and not B");
        #endif
    #else
        #if B
            Console.WriteLine("B and not A");
        #else
            Console.WriteLine("neither A nor B");
        #endif
    #endif
}
like image 140
Lasse V. Karlsen Avatar answered Jul 26 '26 23:07

Lasse V. Karlsen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!