[Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1391
  • Last Modified:

Workaround for C# conditional compilation depending on CLR version

I have C# code that needs compiling in both VS .NET 2003 and VS .NET 2005. Turns out the latter defaults to .NET 2.0, and a few tweaks are needed to my code when building in this environment.
I understand C++ supports this by conditional compilation via the predefined __CLR_VER macro, but C# does not. What is the best workaround without forking code and setting up two seperate projects?
0
bgauweiler
Asked:
bgauweiler
2 Solutions
 
neilpriceCommented:
Hi,

You have some preprocessor-like support in C# using #DEFINE, #UNDEF, #IF, #ELIF, #ELSE, #ENDIF

(Note that I say preprocessor-like because strictly speaking there is no preprocessor in C#, the preprocessing directives are processed as part of the lexical analysis phase of the compiler)

You'll have to define your own symbols though and change them for each version.

So at the top of your source file you can define like this;

#DEFINE DOTNETTWO // This line when you are compiling against VS2005

then in code

#IF DOTNETTWO
// stuff that's .NET2.0 specific
#ELSE
// stuff that's not
#ENDIF

You can also set project wide symbols through a project's properties to avoid having to type #DEFINE DOTNETTWO at the top of every source file (which could get annoying).  In VS2005 go to properties->Build and add to the CONDITIONAL COMPILATION SYMBOLS box.

Hope this helps
Neil

0
 
AlexFMCommented:
You can create different configurations for different .NET versions. For example, instead of standard Debug and Release you can define Debug 2.0, Release 2.0, Debug 1.1 and Release 1.1 configurations. DOTNETTWO constant should be defined in the configuration properties: see Project - Properties - Build - Conditional compilation symbols. Define it only for 2.0 configurations, and use in the code as neilprice suggests.
0
 
bgauweilerAuthor Commented:
Thanks guys - I guess you're right, the combination of your answers is probably the easiest way out of the dilemma. Oh, I wished Microsoft had provided a predefined version macro, but I gather the __CLR_VER macro is only available in VS2005, and only for C++. Grrr.
Thanks for your help.
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now