开发者

What is the use of #if in C#?

开发者 https://www.devze.com 2023-01-03 01:49 出处:网络
I need to know the usage of #if in C#开发者_如何学编程...Thanks..#if is a pre-processor command.

I need to know the usage of #if in C#开发者_如何学编程...Thanks..


#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 StingyJack 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.<YourServicesPrimaryMethodHere>();
    // 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.


"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.


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


#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 quickly turn off code

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


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


#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

0

精彩评论

暂无评论...
验证码 换一张
取 消