Reputation:
I came across the following code as shown below. But I couldn't understand how # can be worked in c#?
using System;
public class Program
{
public static void Main(string[] args)
{
#if (!pi)
Console.WriteLine("i");
#else
Console.WriteLine("PI undefined");
#endif
Console.WriteLine("ok");
Console.ReadLine();
}
}
Output:
i
ok
Upvotes: 7
Views: 10107
Reputation: 4319
C# compiler does not have a separate preprocessor. however, the directives are processed as if there was one. In C# the preprocessor directives are used to help in conditional compilation. Unlike C and C++ directives, they are not used to create macros. A preprocessor directive must be the only instruction on a line.
The #define
preprocessor directive creates symbolic constants.
#define
lets you define a symbol such that, by using the symbol as the expression passed to the
#if
directive, the expression evaluates to true. Its syntax is as follows.
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. the #if
statement in C# is Boolean and only tests whether the symbol has been defined or no.
#define pi
using System;
namespace Sample
{
internal class Program
{
static void Main(string[] args)
{
#if (!pi)
Console.WriteLine("i");
#else
Console.WriteLine("PI undefined");
#endif
Console.WriteLine("ok");
Console.ReadLine();
}
}
}
Upvotes: 0
Reputation: 5211
In C# the lines starting with #
are preprocessor directives (and they must be the only instruction on the line).
When the C# compiler encounters an #if
directive, followed eventually by an #endif
directive, it compiles the code between the directives only if the specified symbol is defined.
N.B. Unlike C and C++, you cannot assign a numeric value to a symbol. The #if
statement in C# is Boolean
and only tests whether the symbol has been defined or not.
Upvotes: 12