I'm sharing C# code with a fellow programmer who is more use to writing C++. He uses #if and #endif directives (which I do not tend to use) and when they occur they have no indentation, for example

        private void dumpToDisplay()
#if false
            ushort[] ScanStatus = new ushort[6];
            for (int ch = 0; ch < 6; ch++)
                ScanStatus[ch] = mySteppers.GetStatus(ch);

            string dumpString = stepDump();


It is interesting that the code sample in the #if C# documentation adopts the same convention and has no indentation for the #if and #endif directives. Is this important? It certainly makes them stand out, but is that good?


Is indentation of #if & #endif directives an important readability convention?

I think you mean outdentation (i.e. the #if is at the start of the line).

I'd say 'yes' because:

  • It's conventional
  • Unlike if statements, #if ... #endif statements don't use braces ({ and })
  • The contents of (i.e. lines between) a #if ... #endif don't have an extra indent (as they would inside an if { ... } statement)

It's also/more important for readability to have a language-aware IDE which:

  • Knows what preprocessor symbols are defined/redefined
  • Therefore knows whether each #if is true or false
  • And colorizes the text accordingly (e.g. grey for disabled text)

The Visual Studio IDE automatically moves #if statements to the left-most column. Any formatting which the IDE does automatically is, I assume, the best way to do it (if only because otherwise you're fighting with the IDE reformatting your code).


I think it makes sense this way, because the #if directives are pretty much outside of the normal syntax. For example, you can write something like:

    if (CheckConditionDebug())
    if (CheckCondition())

This is valid code in both states (DEBUG defined or not), but there is no good way to indent the directives.

Note: I'm not saying that this is a good use of #if, just that it is a possible use and that it makes sense to take this into account.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.