Q:

Shouldn't an undefined variable throw an exception on checking with #if?

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

Can anybody explain to me how? If pi is not defined, shouldn't it throw an exception?

A:

The #If directive specifically checks whether the given symbol is defined or not.
From documentation:

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

Furthermore:

#define lets you define a symbol. By then using the symbol as the expression passed to the #if directive, the expression evaluates to
  true.

Therefore, if the symbol (pi in your case) hasn't been defined, the result is always false.

A:

The #if condition is a preprocessor directive.
The code between your condition is only compiled, if your condition is defined - or in your case, if pi is not defined #if !pi.
See the microsoft documentation at https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/preprocessor-directives/preprocessor-if

