I'm working on a Xamarin.Forms solution that uses a PCL library to share code between my Android and iOS projects. This has worked out great for the most part since most UI and logic code can be kept in one place. Of course, there are some platform-specific classes that I created and linked to the PCL using DependencyService
, and that's fine for most classes since code is significantly different between platforms (UI layout/appearance, for example).
However, there is one subset of classes that makes use of various namespaces that are unavailable for PCL projects (notably the System.Data namespace). To get around this restriction, I had to write a DependencyService for each of these classes. My concern is that the code between Android and iOS is exactly the same, minus one or two lines. The code is quite complex and I don't want to have to remember to update it twice when the need arises.
Is there a way I can reduce the amount of code duplicated between these two projects, considering that I cannot place the code into a PCL due to necessary namespaces which are unavailable?
I was able to eliminate all duplicated code using a shared project (as @matthewrdev suggested). The process was a little more complicated than I expected, though, so I'll add a guide on what I did.
Create a new Xamarin.Forms shared project. (Unfortunately, I only had the option of creating a "blank app (shared)" project, which came with pre-generated Android and iOS projects. I deleted those since I already had the necessary platform projects.)
Add all duplicated code to the shared project. You may need to update namespaces. For any code that you need to run specific to platform, you'll have to use #if __ANDROID__
or #if __IOS__
preprocessor directives.
Add a reference to the shared project in your platform projects (in my case, Android and iOS). In VS2013, this was a little complicated since you are (apparently) unable to add references to shared projects. You either have to modify the .csproj file manually (See this answer for details) or you can use the Shared Project Reference Manager extension for VS2013.
Make sure to add the __ANDROID__
and __IOS__
conditional compilation symbols to your platform projects. To do this, you need to open the project's properties, go to the "Build" tab, and add the symbol where it says "conditional compilation symbols".
These instructions are for Visual Studio 2013, but the steps are similar for Xamarin Studio and probably VS2015 as well.