Feb 27 2010

Sharing Source Files Among Projects

Category: Desktop and Server | MobileJoel Ivory Johnson @ 06:01

There are times when you will want to share the same source code among several projects. A common way to do so is with a shared assembly; you put common functionality in one project and then share the output among several other projects. But at times this solution isn't suitable such as when you have functionality that you plan to share across more than one .Net runtime (ex: Desktop Framework, Compact Framework, and Silverlight Runtime). For these cases you can copy your source code to the projects for all three run times. But then you end up with three branches of code and may need to make sure thay are synced up with each other.

It is possible to use the same source file in different projects by adding a link for the file from another project so that each project is using the same runtime. Since it is the same physical files changes to the file done from one project are visible to all the projects using the same linked file. Adding a linked file is easy. To link to one file's project from another right-click on the project, select Add->Existing Item and navigate to the file. Once you've found the file click on it and then click on the down triangle on the Add button and select "Add as Link."

A potential problem from using this solution is you may have items in a class that you don't want to be visible in another class. You can selectivly hide sections of code using a few preprocessor directives. As a simple example let's say I made a Windows Form application and I have all of the files from it linked to a second project. I have code in a method that is setting the text on a label. But I want the text to be set differently depending on the project in which it is run. The preprocessor directives I will use are #if, #else, and #endif.

#if App1
            txtMyMessage.Text="Hello from App1";
#else
            txtMyMessage.Text = "Hello from App2";
#endif

In the above code only the C# code in the #else, block will be compiled. The code in the #if block will be ignore. For my first project I want to code in the #if block to be used. To accomplish this I need to add a Conditional Compilation Symbol. I right-click on the project and select Properties. Under the Build tab I can add conditional compilation symbols. I've done this for the first project and have added a symbol named App1. So now the first block of code will get compiled and the second block ignored.

While this solution has it's advantages it is not the end-all solution for sharing functionality across projects. If you find yourself using excessive conditional compilation blocks in your code then you may have reached a point at which it is better off having two seperate source files.

Tags: