Part 4 in my Xamarin series of articles explains Shared Projects and the benefits of sharing code. You have come a long way so far within the Xamarin series. We have covered the basics and the installation of Xamarin, as well as Layouts in Xamarin.
Shared Projects enables you to write common code that can be referenced by different application projects. In other words: Shared Projects empowers you to write code that is shared between target projects. A Shared Project cannot get compiled on its own; it is merely a grouping of source code files which can be included in other projects. A Shared Project’s code gets compiled as part of a project in which it resides. Shared Projects contain no references or Component Nodes in the Solution Explorer.
To make use of a Shared Project, it needs to be referenced, just like a normal library would be referenced.
- Start a new Project.
- Search for the Shared Library Template, as shown in Figure 1.
Figure 1: New
The Solution Explorer would resemble Figure 2, after two Classes have been added.
Figure 2: Solution Explorer
Now, to use this Shared Project, we need other projects to reference it. Add New Projects to the Solution by Clicking File, Add. Choose any project type; this is just a short example. Once done, add another project. Your Solution Explorer should resemble Figure 3.
Figure 3: More projects added
Add a Reference to the Shared project, by right-clicking the project in your Solution Explorer and selecting Add, Reference, as shown in Figure 4:
Figure 4: Add Reference
Inside the Reference Manager box, select Shared Projects, and select the one you have created now (see Figure 5).
Figure 5: Reference Manager
Now, you can use the Shared Project’s logic inside both linked projects. The Solution Explorer shows the reference that was added, as you can see in Figure 6.
Figure 6: References
The next and final installment will cover PCLs in Xamarin. Until then, keep learning!