views:

86

answers:

3

We can switch to different .NET Framework target in Visual Studio after 2008.

I have a project, and I want to build 2 different target Frameworks assembly of it. If my target Framework is 2.0, I want it to build some code, and when I switch to another target Framework, I want it to build another code fragment to use some new functions.

now I have to manually comment and uncomment code everywhere, I wonder if I can use some precompile symbols to dynamically do this to me. Like:

#if Framework3
<do something>
#else
<do something else>
#endif

Can I?

+1  A: 

Just define one in the build options before you compile for each framework version.

  1. Add Framework3
  2. Compile for .NET Framework 3.5
  3. Change to Framework2
  4. Compile for .NET Framework 2.0

This still isn't as automated as you probably want it to be, but it's better than uncommenting a bunch of lines, in my opinion.

David Brown
A: 

Yes, you can set defined constants in the project properties. The best way to manage this, imho, is to have separate project files that share the code but have different defined constants. So a mycode_Framework1.csproj, mycode_Framework2.csproj, etc. You can have them in the same solution or not, but if you do, it makes building them all at once a bit easier.

Qberticus
Sharing code across projects is very brittle in my experience - it's easy to forget to add a new file to all the projects. It's a shame that Visual Studio doesn't really handle this kind of thing elegantly.
Jon Skeet
+2  A: 

Yes, we do this in MiscUtil. I'm not sure you can do it directly in Visual Studio, as the target framework choice is in a property page which ignores the current configuration. However, you can edit the project file directly, to get the right target framework for the right configuration. In particular, you'll want to make sure you don't have .NET 3.5 references when targeting .NET 2.0. Have a look at our main project file (MiscUtil.csproj) for more details.

The preprocessor symbol part is easy - once you've got a build configuration for .NET 2.0 you can add preprocessor symbols directly in Visual Studio.

Jon Skeet
I have read your code, and I have to say modifying project file directly if brilliant. That's What I want I think. Thank you.
redjackwong