Working with Preprocessor Directives - CSharp Language Basics

CSharp examples for Language Basics:Preprocessor

Introduction

Directive Description
#define Defines a symbol.
#else Starts an else block.
#elif Combination of an else statement and an if statement.
#endregionIdentifies the end of a region.
#endifEnds an #if statement.
#if Tests a value.
#errorSends a specified error message when compiled.
#line Specifies a line source code line number. It can also include a filename that will appear in the output.
#region Identifies the start of a region. A region is a section of code that can be expanded or collapsed in an IDE.
#undefUndefines a symbol.
#warning Sends a specified warning message when compiled.

The basic format of #define and #undef is

#define xxxx

and

#undef xxxx

Demo Code

#define DEBUG//from ww  w. j  a  v  a  2 s . c o m
using System;
using System.IO;
public class Reading
{
   public static void Main(String[] args)
   {
      if( args.Length < 1 )
      {
         Console.WriteLine("Must include file name.");
      }
      else
      {
         #if DEBUG
         for ( int x = 0; x < args.Length ; x++ )
         {
            Console.WriteLine("Arg[{0}] = {1}", x, args[x]);
         }
         #endif
         string buffer;
         StreamReader myFile = File.OpenText(args[0]);
         while ( (buffer = myFile.ReadLine()) != null )
         {
            #if DEBUG
            Console.Write( "{0:D3} - ", buffer.Length);
            #endif
            Console.WriteLine(buffer);
         }
         myFile.Close();
      }
   }
}

Result

Defining Values on the Command Line

you can use the /define flag on the compile option. The format of this compile option is as follows:

csc /define:DEBUG Reading.cs

Related Tutorials