tags:

views:

267

answers:

6

I need to know the usage of #if in C#.NET...Thanks..

+3  A: 

"When the C# compiler encounters an #if directive, followed eventually by an #endif directive, it will compile the code between the directives only if the specified symbol is defined"

Here's the MSDN link.

Colin Desmond
A: 

It is used for Preprocessor Directives, see here http://msdn.microsoft.com/en-us/library/4y6tbswk(v=VS.71).aspx

SQLMenace
+16  A: 

#if is a pre-processor command.

It's most common usage (which some might say is an abuse) is to have code that only compiles in debug mode:

#if DEBUG
    Console.WriteLine("Here");
#endif

One very good use (as StingJack points out) is to allow easy debugging of a Windows Service:

static void Main()
{
#if (!DEBUG)
    System.ServiceProcess.ServiceBase[] ServicesToRun;
    ServicesToRun = new System.ServiceProcess.ServiceBase[] { new Service1() };
    System.ServiceProcess.ServiceBase.Run(ServicesToRun);
#else
    // Debug code: this allows the process to run as a non-service.

    // It will kick off the service start point, but never kill it.

    // Shut down the debugger to exit

    Service1 service = new Service1();
    service.<Your Service's Primary Method Here>();
    // Put a breakpoint on the following line to always catch
    // your service when it has finished its work
    System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#endif 
}

Source

This means that running release mode will start the service as expected, while running in debug mode will allow you to actually debug the code.

ChrisF
Best use of #if that I have seen.... http://www.codeproject.com/KB/dotnet/DebugWinServices.aspx
StingyJack
@StingyJack - I've used that myself, it is a very good use.
ChrisF
A: 

#if is a compiler directive, for example you can #define test

and later in the code you may test #ifdef test compile code block with #ifdef

TonyP
+2  A: 

#if (C# Reference) is a compiler directive. See the MSDN article for more info.

James
A: 

if has lost so much compared to its ancestors -- c or C++. nowadays I use #if for only two scenarios

1) use it to enable code for debug or not debug

#if DEBUG
    // code inside this block will run in debug mode.
#endif

2) use it to quicky turn off code

#if false
     // all the code inside here are turned off..
#endi
Syd