I just found two piece of code
#if CONSOLE // defined by the console version using
ournamespace.FactoryInitializer;
#endif
and
#if _NET_1_1
log4net.Config.DOMConfigurator.ConfigureAndWatch(new System.IO.FileInfo(s) );
#else
log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(s) );
#endif
Can any one please tell me with a running sample( please provide a simple one) what is the significance of those code snippets and when and how to use those?
Thanks.
Sure. These refer to conditional compilation symbols which can be defined at compile-time and which control what code is actually built. Here’s an example:
If you compile this with
It won’t print anything. If you compile it with
then it will print “FOO was defined” – and obviously the same is true for BAR.
Note that these aren’t the same as C++ macros – a symbol is either defined or not; it doesn’t have a “replacement value” as such.
In Visual Studio, you specify which symbols should be defined in the Build tab of the project properties. Additionally, at the very start of the file you can explicitly define and undefine symbols:
This can be important when calling methods decorated with
ConditionalAttribute– such calls are ignored by the compiler if the appropriate symbol isn’t defined. So if you wanted to make sure that all yourDebug.Printcalls came through even if you hadn’t defined the DEBUG symbol for the rest of the project, you could use:Personally, I don’t use all this very much. Aside from anything else, it makes it easier to understand the code if you know that it will all be compiled and run at execution time.
EDIT: Just to clarify a little on terminology –
#if,#line,#pragmaetc are all preprocessor directives; FOO and BAR (in this case) are the conditional compilation symbols.