C# Frequently Asked Questions

The C# team posts answers to common questions

Leverage the C# Preprocessor

Like other languages in the C-family, C# supports a set of 'preprocessor' directives, most notably #define, #if and #endif (technically, csc.exe does not literally have a preprocessor as these symbols are resolved at the lexical analysis phase, but no need to split hairs…).

The #define directive allows you to set up custom symbols which control code compilation. Be very aware that unlike C(++), C#'s #define does not allow you to create macro-like code. Once a symbol is defined, the #if and #endif maybe used to test for said symbol. By way of a common example:

#define DEBUG
using System;

public class MyClass
{
  public static void Main()
  {
    #if DEBUG
      Console.WriteLine("DEBUG symbol is defined!");
    #endif
  }
}

When you use the #define directive, the symbol is only realized within the defining file. However if you wish to define project wide symbols, simply access your project's property page and navigate to the "Configuration Properties | Build" node and edit the "Conditional Compilation Constants" edit field. Finally, if you wish to disable a constant for a given file, you may make use of the #undef symbol.


Tip from Andrew Troelsen
Posted by: Duncan Mackenzie, MSDN
This post applies to Visual C# .NET 2002/2003/2005

Published Wednesday, October 20, 2004 1:20 PM by CSharpFAQ
Filed under:

Comments

 

Sean Gephardt said:

This is a great feature of C#, that work well in ASP.NET also.
October 20, 2004 2:18 PM
 

AT said:

If you are real-geek and miss C++ macros - you can use C++ proprocessor "cl.exe -E" to preprocess C# files.

For examples and if you would like Microsoft to support this natively - visit http://lab.msdn.microsoft.com/productfeedback/viewfeedback.aspx?feedbackid=FDBK16094

The only problem I see - it's includes. You can not reuse the same classes/interfaces in more that two files that will be compiled into one assembly. But 'partial' keyword can allow to do some magic.

It looks like I've "invented" C#++ language ;-)

Do you see any major problems with using "cl -E" for C# files ? If you will select names for defines carefully - then you will not have any.
October 21, 2004 11:46 AM
 

Antonio Chiarello said:

Hi,
I'm a computer enginner of Genoa.
I'm working on a C# parser and I have a problem with project wide symbols. How can I obtain information about symbol which are defined and not defined in a project?

Thanks.
Antonio.
November 4, 2004 1:25 AM
 

RebelGeekz said:

December 28, 2004 4:54 AM
 

FAQ C# said:

April 20, 2005 7:14 PM
 

FAQ C# (par Yannick Lejeune) said:

August 23, 2005 5:28 AM
 

Leverage the C# Preprocessor : F9 Group Marketing and Technology Blog said:

September 17, 2008 3:33 PM
Anonymous comments are disabled

© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Microsoft
Page view tracker