Julian Julian - 2 months ago 13
C# Question

Is it valid to use the #define preprocessor directive inside an #if in C#

Could I use

#define
preprocessor directive inside
#if
and
#endif
, in C# ?

e.g.

#if !SILVERLIGHT && !__ANDROID__ && !__IOS__
#define SupportsMutex
#endif


It looks like it works, but I need to be sure. There is a lot written about this, but most of the time in the context of C and not C# - the preprocessor directives a in C# far more limited.

Visual Studio's highlighting seems to support it, but it this really valid according to the language / compiler specs?

The This MSDN page gives the following note:


The #define directive cannot be used to declare constant values as is typically done in C and C++. Constants in C# are best defined as static members of a class or struct. If you have several such constants, consider creating a separate "Constants" class to hold them.


I need this because using
#if !SILVERLIGHT && !__ANDROID__ && !__IOS__
multiple times is difficult to manage.

Of course we could also add
SupportsMutex
to the "conditional compilation symbols" of a project, but this is more difficult to manage and less transparant.

Answer

Yes. Looking at the C# specification a particular example of this usage is given in section 2.5.3 Declaration directives and deemed as valid:

#define Enterprise
#if Professional || Enterprise  
   #define Advanced
#endif 
namespace Megacorp.Data 
{
    #if Advanced    
    class PivotTable {...}  
    #endif 
}