What is the function of #if false in C#?

Asked

Viewed 285 times

14

I’m working on a project and I saw blocks of code with this #if false: inserir a descrição da imagem aqui

What’s the difference to it (commented vs #if false) ?

inserir a descrição da imagem aqui

3 answers

18


The #if is a pre-processing directive which allows you to pass parameters to the compiler.

When you do

#if false
 ...
#endif

The compiler understands that nay is to compile/interpret the #if.

A more common use of this directive is:

#if DEBUG
    Console.WriteLine("Olá mundo!");
#endif

Which will run the block only if the project is in DEBUG.

The directive #if false does not work as a comment.

Inside the comment you don’t need to respect the syntax of C#, for example, the #if false causes the compiler to delete everything from this compilation block but does not ignore it completely equal to a comment, so the compiler will still look at the text that is inside the block.

For example, the code below will generate an error:

#if false
 #foo
#endif

inserir a descrição da imagem aqui

  • Right, and what’s the real difference between #if false and you comment on the code block ?

  • 1

    @Thiagoloureiro a lot. Pre-compilation things can be solved by adding headers, or by commands played to the pre-compiler

  • In VB.NET, #if works as a comment.

6

In your case, the result will be the same. But many code refactoring/analysis tools can mark code comments as a Smells code (which is actually).

Thinking about the compilation of your code, the directive (#IF) is interpreted before you even begin the lexical analysis and will be analyzed if that code will be used in the Build process (I need sources to confirm this statement). In your case since the condition is always false, it will not be part of the build.

The comment will be ignored when the lexical analysis does the reading trying to create known tokens.

  • Understood, it seems simple but in detail 'and interesting to understand, Tks+1

6

Compilation Condicional

The #IF is a pre-compilation command. With it you can modify your code according to parameters (constants) that you define or use predefined constants like the DEBUG or TRACE.

If you open the build options window of the project you will see a window similar to this:

inserir a descrição da imagem aqui

As you can see, in the conditional symbol box I registered a constant call MINHA_CONSTANTE. That way I can create a code like:

#IF MINHA_CONSTANTE
     ... código que vai compilar apenas quando essa constante estiver definida
#ENDIF

And that way when you want, you can go to the build tab and remove this constant or add others and your code will compile according to this logic that you defined.

For this reason a #IF false doesn’t make much sense and he does the same job as commenting on the code, since that chunk will not be compiled.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.