2
votes

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.

4

4 Answers

4
votes

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

And then you can define CLR_V2 and/or CLR_V4 in project properties window of Visual Studio, or csc command line arguments.

1
votes

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.

0
votes

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

edit: completely misread that question - time for a break

0
votes

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.