Quick Tip - Sharing code between multiple projects in Visual Studio 2005

I have long been an advocate for putting common code into an assembly that is shared by applications needing the functionality.  That said, there are times where the separate assembly approach is not appropriate.  For those situations, today's tip may help make code sharing easier.

I have a project (called TestApp) that targets the .NET Compact Framework version 2.  In the TestApp project, there is a file called Helper.cs which implements a class containing static methods that I use throughout the TestApp project.

While working on TestApp, I decide that a .NET Framework (for desktop PCs) version would be nice to have.  Since I already have Helper.cs written, I would like to use the existing version.  I had previously chosen to not use an assembly for these helpers, so I add the existing file to my new project. 

I would prefer to not create a duplicate of this file as maintaining changes between the two copies can be time consuming and error prone.  Fortunately, Visual Studio 2005 has a great feature to allow for file sharing between projects -- you can add an existing file as a link.  Here's how:

  1. In the project where you wish to add the file, right click the project name in the Solution Explorer
  2. Select Add and then Existing Item...
  3. In the Add Existing Item dialog, navigate to the desired file
  4. Click the downward pointing arrow next to the Add button and select Add As Link.
    Once added to a project, linked files are easy to identify by the small arrow in the lower-left corner of the file icon in the Solution Explorer.

My new project now has a reference to the original Helper.cs and any changes I make to it, from either project, are reflected in both projects.

Note: It is important to remember that if you are sharing a file between different versions of the .NET Framework, you need to verify that any changes made are compatible with all projects using the file.

-- DK

This posting is provided "AS IS" with no warranties, and confers no rights.