Chapter 1 How does Xamarin.Forms fit in? 6
Sharing code
The advantage of targeting multiple platforms with a single programming language comes from the
ability to share code among the applications.
Before code can be shared, an application must be structured for that purpose. Particularly since the
widespread use of graphical user interfaces, programmers have understood the importance of separat-
ing application code into functional layers. Perhaps the most useful division is between user-interface
code and the underlying data models and algorithms. The popular MVC (Model-View-Controller) ap-
plication architecture formalizes this code separation into a Model (the underlying data), the View (the
visual representation of the data), and the Controller (which handles input from the user).
MVC originated in the 1980s. More recently, the MVVM (Model-View-ViewModel) architecture has
effectively modernized MVC based on modern GUIs. MVVM separates code into the Model (the under-
lying data), the View (the user interface, including visuals and input), and the ViewModel (which man-
ages data passing between the Model and the View).
When a programmer develops an application that targets multiple mobile platforms, the MVVM
architecture helps guide the developer into separating code into the platform-specific View—the code
that requires interacting with the platform APIs—and the platform-independent Model and View-
Model.
Often this platform-independent code needs to access files or the network or use collections or
threading. Normally these jobs would be considered part of an operating system API, but they are also
jobs that can make use of the .NET Framework class library, and if the class library is available on each
platform, it is effectively platform independent.
The part of the application that is platform independent can then be isolated and—in the context of
Visual Studio or Xamarin Studio—put into a separate project. This can be either a Shared Asset Project
(SAP)—which simply consists of code and other asset files accessible from other projects—or a Portable
Class Library (PCL), which encloses all the common code in a dynamic-link library (DLL) that can then
be referenced from other projects.
Whichever method is used, this common code has access to the .NET Framework class library, so it
can perform file I/O, handle globalization, access web services, decompose XML, and so forth.
This means that you can create a single Visual Studio solution that contains four C# projects to tar-
get the three major mobile platforms (all with access to a common SAP or PCL project), or you can use
Xamarin Studio to target iPhone and Android devices.
The following diagram illustrates the interrelationships between the Visual Studio or Xamarin Studio
projects, the Xamarin libraries, and the platform APIs: