Going cross-platform with Xamarin–Adding a Portable Class Library

This blog post series is a documentation for a talk I give about cross-platform development with Xamarin. This series was co-authored by Johan Lindfors at Coderox. This post talks about how we move code from the phone app to a portable class library, in preparation for our Android implementation.


First we need to prepare the codebase so that we can reuse common code across platforms. There are different ways we can do this, but today we are going to move the code to a portable class library. A portable class library is a special .NET assembly where you target the platforms you want the code to run on. This will automatically limit the the part of .NET framework available to what’s common on your chosen platforms.

What’s great about this is that Xamarin for Android and Xamarin for iOS can be chosen as targets for this library. That means that we can move all our common code into this reusable Component to kick-start our Android development later. We will move all code that’s not view related or device specific. Here is how you do this.

Moving the code

So, this is what the project looks like today:


First, right-click on the solution, choose Add –> New Project… and select to create a new Portable Class Library as per below:


Hit OK and assuming that you have Xamarin for iOS and Android installed, check in the following boxes and press OK one more time:


Now, let’s move things over to portable class library. Start by removing Class1.cs, since it’s not needed. Then copy everything in Model, Service and ViewModels folders. Keep everything in the portable class library except PeriodicService.cs and PositionService.cs, and keep only these files in the Phone project. You should end up with a project structure like this:


One final thing to do; make sure that the phone project references the portable class library project:


Now, press F5 and see that we have the same functionality as before, but now all common code has been separated into a separate library, settings us up nicely for cross-platform development. We are moving closer to an Android version, but first we need to do one more step. Let’s port our code to use the MvvmCross framework.


I hope I have shown how easy it is to move your common code to a portable class library, and be ready for cross-platform development. Blog post about adding MvvmCross is here.