2

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.

Daniel Fortunov
  • 43,309
  • 26
  • 81
  • 106
Ohad Horesh
  • 4,340
  • 6
  • 28
  • 45

4 Answers4

4

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.

deerchao
  • 10,454
  • 9
  • 55
  • 60
  • 2
    for example: #define CLR_V4 // you can define the symbol in the Project properties of VS, or via csc command line arguments, too using 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 #endif Console.WriteLine("clr 2.0"); #elif CLR_V4 Console.WriteLine("clr 4.0"); #else #error Define either CLR_V2 or CLR_V4 to compile #endif } } – deerchao Dec 10 '09 at 09:39
  • Thanks, the define in the project properties was what I was missing. – Ohad Horesh Dec 12 '09 at 16:44
1

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.

Chris Fulstow
  • 41,170
  • 10
  • 86
  • 110
0

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

edit: completely misread that question - time for a break

jk.
  • 13,817
  • 5
  • 37
  • 50
0

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
  • 64,563
  • 18
  • 145
  • 216