Delen via


Summary of Chapter 9. Platform-specific API calls

Note

This book was published in the spring of 2016, and has not been updated since then. There is much in the book that remains valuable, but some of the material is outdated, and some topics are no longer entirely correct or complete.

It is sometimes necessary to run some code that varies by platform. This chapter explores the techniques.

Preprocessing in the Shared Asset Project

A Xamarin.Forms Shared Asset Project can execute different code for each platform using the C# preprocessor directives #if, #elif, and endif. This is demonstrated in PlatInfoSap1:

Triple screenshot of variable formatted paragraph

However, the resultant code can be ugly and difficult to read.

Parallel classes in the Shared Asset Project

A more structured approach to executing platform-specific code in the SAP is demonstrated in the PlatInfoSap2 sample. Each of the platform projects contains an identically named class and methods, but implemented for that particular platform. The SAP then simply instantiates the class and calls the method.

DependencyService and the Portable Class Library

Note

Portable Class Libraries have been replaced by .NET Standard libraries. All the sample code from the book has been converted to use .NET standard libraries.

A library cannot normally access classes in application projects. This restriction seems to prevent the technique shown in PlatInfoSap2 from being used in a library. However, Xamarin.Forms contains a class named DependencyService that uses .NET reflection to access public classes in the application project from the library.

The library must define an interface with the members it needs to use in each platform. Then, each of the platforms contains an implementation of that interface. The class that implements the interface must be identified with a DependencyAttribute on the assembly level.

The library then uses the generic Get method of DependencyService to obtain an instance of the platform class that implements the interface.

This is demonstrated in the DisplayPlatformInfo sample.

Platform-specific sound generation

The MonkeyTapWithSound sample adds beeps to the MonkeyTap program by accessing sound-generation facilities in each platform.