views:

272

answers:

4

Hi,

I need to compile code conditionally by the CLR version.
e.g there's a code that I need to compile only in CLR 2 (.NET 3.5 VS2008) and not in CLR 4 (.NET 4 VS2010)
Is there a precompiler directive for the current CLR version that I can use inside an #if clause?

Thanks.

A: 

You could always add something to your MSBuild script that checks the CLR version, then conditionally defines and passes in a preprocessor symbol to the compiler that can be tested inside the code with an #if.

cxfx
+2  A: 

Not as I know.

try use your own one, such like:

#if CLR_V2

#if CLR_V4

#error You can't define CLR_V2 and CLR_V4 at the same time

#endif

code for clr 2

#elif CLR_V4

code for clr 4

#else

#error Define either CLR_V2 or CLR_V4 to compile

#endif

deerchao
for example:#define CLR_V4// you can define the symbol in the Project properties of VS, or via csc command line arguments, toousing System;class Program{static void Main(){ #if CLR_V2#if CLR_V4#error You can't define CLR_V2 and CLR_V4 at the same time#endifConsole.WriteLine("clr 2.0");#elif CLR_V4Console.WriteLine("clr 4.0");#else#error Define either CLR_V2 or CLR_V4 to compile#endif}}
deerchao
Thanks, the define in the project properties was what I was missing.
Ohad Horesh
A: 

Yes there are conditional compilation directives they look just like C preprocessor stuff

edit: completely misread that question - time for a break

jk
A: 

According to here the answer is no. However one trick we use is to put the version specific code into assemblies that are loaded at runtime. You can then get the version of the CLR at runtime by System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory().

The version specific code is compiled using the targeting facility available from the C#3.5 onwards.

Preet Sangha