Julian Julian - 2 years ago 192
C# Question

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

Could I use

preprocessor directive inside
, in C# ?


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

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
to the "conditional compilation symbols" of a project, but this is more difficult to manage and less transparant.

Answer Source

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
namespace Megacorp.Data 
    #if Advanced    
    class PivotTable {...}  
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download