What are they for and when to use the Preprocessor directives?

Asked

Viewed 231 times

6

Some time ago I had seen the use of #define in C#. Today I searched about it and found its documentation here, but did not answer all my doubts.

Code example with Preprocessor directives:

#define DEBUG  

#if DEBUG  
    Console.WriteLine("Debug version");  
#endif

Upon that, my doubts are:

  • What are Preprocessor directives for?
  • When I should use Preprocessor directives?

1 answer

7


They serve a lot of things, each one serves for something different. They serve to change the behavior of the compiler in a given stretch.

You should use whenever you need to change the build. It almost never exists in normal codes. In fact they should be avoided until they have no better solution. And C# has few.

It actually has the directive #region that does not change the compilation and helps the organization in the IDE, and many consider this a language error.

Passing them all is a very broad question. Have a few questions on the subject:

The #if determines whether the code within it will be compiled or ignored. This is decided whether a compilation variable, which has nothing to do with code variables, exists. In general these variables are defined as argument in the compiler.

In C# it is rare to need to create a variable with #define, in some cases another piece can generate conditionally. This was often used in C because the language was not powerful and needed almost another language to help create what was desired. Even today C needs less of that, and C++ can eliminate almost completely.

In the example shown the code will be compiled because the variable was created just above, which doesn’t even make sense in real code.

So then it’s to compile snippets conditionally. Actually it has other ways to solve the same to debug code that does not need the directive.

Browser other questions tagged

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