Conditional compilation for .NET 4 [duplicate]
Asked Answered
C

2

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

Clan answered 3/2, 2011 at 18:23 Comment(1)
#2923710Epistemic
P
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.

Percutaneous answered 3/2, 2011 at 18:41 Comment(1)
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.Clan
C
15

I think this is what you are looking for:

#if NET40   
...  
#elif NET35  
...  
#else NET20  
...  
#endif  
Commuter answered 3/2, 2011 at 18:30 Comment(4)
Those do not seem to be pre-definedClan
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 tasksCommuter
So there is really no way proviced by the framework out of the box.Clan
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 msdn.microsoft.com/en-us/library/ed8yd1ha.aspxOpportune
P
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.

Percutaneous answered 3/2, 2011 at 18:41 Comment(1)
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.Clan

© 2022 - 2024 — McMap. All rights reserved.