9

Possible Duplicate:
Conditional compilation and framework targets

I have some code that works in .NET 4, but it does not work in .NET 3.5. In .NET 3.5 it requires to use interop calls to Windows.

I would like using a "ifdef" to use a different code path in both cases (eventually I will deprecate the .NET 3.5 code).

Is there a pre-defined directive value to identify when the code is compiled with .NET 4?

Is there a good link with all the predefined directives (DEBUG, TRACE, etc.)? The page below only gives the directives, but not the standard predefined values:

C# Preprocessor Directives

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
MMind
  • 1,845
  • 2
  • 17
  • 26

2 Answers2

15

I think this is what you are looking for:

#if NET40   
...  
#elif NET35  
...  
#else NET20  
...  
#endif  
Abel
  • 56,041
  • 24
  • 146
  • 247
Chingiz Musayev
  • 2,832
  • 1
  • 14
  • 6
  • 2
    Those do not seem to be pre-defined – MMind Feb 03 '11 at 19:48
  • 1
    It's true. But you can write tiny .bat script with something like this `%windir%\microsoft.net\framework\v3.5\msbuild /m /p:Configuration=Release /p:DefineConstants="NET35" /nologo /t:Build ...`. It always better have build scripts. Or more preferable NAnt/MSbuild tasks – Chingiz Musayev Feb 03 '11 at 20:28
  • 1
    So there is really no way proviced by the framework out of the box. – MMind Feb 06 '11 at 17:06
  • Or add #define NET35 on the first line of your code (even before using statements).. then comment it out for other versions, there are situations where preprocessor directives have advantages over if (constant) statements as the code that doesn't satisfy the statement *theoretically* doesn't exist and can't trip up the compiler; this is important when 95%+ of your code is the same but <5% is different in some situations. It's a nice fast way of switching with a few keystrokes. See https://msdn.microsoft.com/en-us/library/ed8yd1ha.aspx – Michael Stimson Apr 01 '16 at 04:14
7

The compiler isn't aware of any particular .NET Framework version. All it sees is the reference assemblies. Nor is there any guarantee that your program will run with the .NET version that you target. It is quite possible to run with the .NET 4.0 CLR even if you built for 2.0.

Use Environment.Version instead.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • 3
    Ths is a good option but obviously has the limitation that this only works if the code can compile as it is a runtime check. – MMind Feb 06 '11 at 17:10