Implementing a cross-platform API
The preprocessor directives described in the previous recipe are easy to use but can become difficult to read and maintain. A better way to write platform-specific code while keeping things clear is to implement a common cross-platform class with platform-specific implementations.
In this recipe, we’ll create a class where the cross-platform logic is defined in the main project, while the platform-specific code is implemented in the Platforms/
Android/iOS/Windows
folders.
Getting ready
To follow the steps described in this recipe, simply create a blank .NET MAUI application.
The code for this recipe is available at https://github.com/PacktPublishing/.NET-MAUI-Cookbook/tree/main/Chapter07/c7-CrossPlatformApi.
How to do it…
Let’s modify the project from the previous recipe so that the platform name is returned by a method implemented in platform-specific code. Although .NET MAUI already provides APIs to access the...