Ads2

Saturday, 2 August 2025

Platform-Specific Code in .NET MAUI

 In .NET MAUI, you can write platform-specific code using several approaches:

  1. Using #if compiler directives

  2. Using Dependency Injection (DI) with platform implementations

  3. Using partial classes and platform folders

Here's a complete example using all three approaches for a feature that displays the current device's platform name.

Approach 1: Using Compiler Directives (#if)

csharp
public string GetPlatformName()
{
    string platform;
    
#if ANDROID
    platform = "Android";
#elif IOS
    platform = "iOS";
#elif MACCATALYST
    platform = "Mac Catalyst";
#elif WINDOWS
    platform = "Windows";
#else
    platform = "Unknown";
#endif

    return platform;
}

Approach 2: Using Dependency Injection (Recommended)

1. Create an Interface

csharp
public interface IDeviceService
{
    string GetPlatformName();
}

2. Implement Platform-Specific Services

Android Implementation (Platforms/Android/DeviceService.android.cs):

csharp
using YourApp.Platforms.Android;

namespace YourApp.Services
{
    public class DeviceService : IDeviceService
    {
        public string GetPlatformName() => "Android";
    }
}

iOS Implementation (Platforms/iOS/DeviceService.ios.cs):

csharp
using YourApp.Platforms.iOS;

namespace YourApp.Services
{
    public class DeviceService : IDeviceService
    {
        public string GetPlatformName() => "iOS";
    }
}

3. Register the Service in MauiProgram.cs

csharp
public static class MauiProgram
{
    public static MauiApp CreateMauiApp()
    {
        var builder = MauiApp.CreateBuilder();
        builder
            .UseMauiApp<App>()
            .ConfigureFonts(fonts =>
            {
                fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
            });

#if ANDROID
        builder.Services.AddSingleton<IDeviceService, Platforms.Android.DeviceService>();
#elif IOS
        builder.Services.AddSingleton<IDeviceService, Platforms.iOS.DeviceService>();
#endif

        return builder.Build();
    }
}

4. Use the Service in Your Code

csharp
public partial class MainPage : ContentPage
{
    private readonly IDeviceService _deviceService;
    
    public MainPage(IDeviceService deviceService)
    {
        InitializeComponent();
        _deviceService = deviceService;
        
        var platformName = _deviceService.GetPlatformName();
        PlatformLabel.Text = $"Running on: {platformName}";
    }
}

Approach 3: Using Partial Classes and Platform Folders

1. Create a Partial Class in Shared Project

csharp
public partial class DeviceInfo
{
    public partial string GetPlatformName();
}

2. Implement Platform-Specific Parts

Android Implementation (Platforms/Android/DeviceInfo.android.cs):

csharp
public partial class DeviceInfo
{
    public partial string GetPlatformName() => "Android";
}

iOS Implementation (Platforms/iOS/DeviceInfo.ios.cs):

csharp
public partial class DeviceInfo
{
    public partial string GetPlatformName() => "iOS";
}

3. Use the Class

csharp
var deviceInfo = new DeviceInfo();
var platform = deviceInfo.GetPlatformName();

Complete Example with Dependency Injection (Recommended)

Here's a complete end-to-end example using the DI approach:

  1. Create a new MAUI project

  2. Add IPlatformInfoService.cs:

csharp
public interface IPlatformInfoService
{
    string GetPlatformName();
    string GetPlatformVersion();
}
  1. Add Android implementation (Platforms/Android/PlatformInfoService.cs):

csharp
using Android.OS;

public class PlatformInfoService : IPlatformInfoService
{
    public string GetPlatformName() => "Android";
    
    public string GetPlatformVersion()
    {
        return Build.VERSION.Release;
    }
}
  1. Add iOS implementation (Platforms/iOS/PlatformInfoService.cs):

csharp
using UIKit;

public class PlatformInfoService : IPlatformInfoService
{
    public string GetPlatformName() => "iOS";
    
    public string GetPlatformVersion()
    {
        return UIDevice.CurrentDevice.SystemVersion;
    }
}
  1. Register services in MauiProgram.cs:

csharp
var builder = MauiApp.CreateBuilder();
builder
    .UseMauiApp<App>()
    .ConfigureFonts(fonts => { /* font config */ });

// Register platform-specific services
#if ANDROID
builder.Services.AddSingleton<IPlatformInfoService, Platforms.Android.PlatformInfoService>();
#elif IOS
builder.Services.AddSingleton<IPlatformInfoService, Platforms.iOS.PlatformInfoService>();
#endif

// Register MainPage with dependency
builder.Services.AddTransient<MainPage>();

return builder.Build();
  1. Use in MainPage.xaml.cs:

csharp
public partial class MainPage : ContentPage
{
    public MainPage(IPlatformInfoService platformInfo)
    {
        InitializeComponent();
        
        PlatformLabel.Text = $"Running on: {platformInfo.GetPlatformName()}";
        VersionLabel.Text = $"Version: {platformInfo.GetPlatformVersion()}";
    }
}
  1. Update MainPage.xaml:

xml
<VerticalStackLayout>
    <Label x:Name="PlatformLabel" FontSize="24" HorizontalOptions="Center"/>
    <Label x:Name="VersionLabel" FontSize="18" HorizontalOptions="Center"/>
</VerticalStackLayout>

This example shows the recommended way to handle platform-specific code in MAUI using dependency injection, which makes your code more testable and maintainable. The compiler will automatically include only the appropriate platform implementation when building for each target.

No comments:

Post a Comment

Fantasy Cricket Mobile App in .NET

  1. Planning the Fantasy Cricket App Key Features to Include: User registration and authentication Player selection interface Match schedul...