Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

System-wide compiler symbols

3.88/5 (7 votes)
11 Jul 2010CPOL1 min read 1  
A way to define system-wide compiler symbols to be used for all C# builds
On occasion, when writing code that should compile cleanly with various versions of .net, we run into situations where we need to use conditional compilation.

There are two often-used methods to define symbols for this:
0) Put a #define within the code we are working on.
1) Create a project-wide symbol (via project properties).

However, I feel a more general, system-wide, solution is required. With C and C++ there are various built-in symbols to indicate such things; C# currently has no such built-in symbols.

This tip describes my current method of defining a compiler symbol that indicates which version of .net is in use by the compiler.

The various versions of .net reside in the
%windir%\microsoft.net\framework directory; each version has its own subtree.

The files we want to edit are:
CSC.RSP -- which is used when command-line compiling with CSC (the C# compiler)
Microsoft.CSharp.targets -- which is used by MSBUILD (and therefore Visual Studio) when compiling C# code

In each CSC.RSP, add a line like /d:DotNet_4_0. You may choose your symbol, but it should be descriptive.

In each Microsoft.CSharp.targets, change
DefineConstants="$(DefineConstants)"
to
DefineConstants="$(DefineConstants) DotNet_4_0"
(or whatever symbol you chose, but it should match what you added to the CSC.RSP file).

You will need to do this on each development system. And it will need to be done as new versions of .net become available.

Thereafter, whenever you compile C# code, the appropriate symbol should exist, and you can use compiler directives (#if) to determine the .net version.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)