Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 42 ยท Platform Features

Platform-Specific Code

Learn how a .NET MAUI app adapts to Android, iOS, macOS and Windows with DeviceInfo, OnPlatform, conditional compilation, the Platforms folder and partial classes.

One of the promises of .NET MAUI is a single project that runs on Android, iOS, Mac Catalyst and Windows. Most of your code really is shared, but sooner or later you need something that only one platform can do: a different font size, a native API, or a layout tweak for tablets. MAUI gives you several tools for this, from one-line XAML switches to full per-platform implementations.

This lesson walks through them from the lightest to the heaviest. The real MAUI APIs are shown read-only, because the platform runtimes cannot run inside a browser. The runnable examples are plain C# stand-ins that model the same ideas, so you can experiment with the patterns.

The runnable blocks on this page are hand-written stand-ins in plain C#. They are not .NET MAUI. They show the design, and the read-only snippets show the real API.

What the project looks like

A MAUI project is multi-targeted. The project file lists one target framework per platform:

XML
<TargetFrameworks>net10.0-android;net10.0-ios;net10.0-maccatalyst</TargetFrameworks>
<TargetFrameworks Condition="$([MSBuild]::IsOSPlatform('windows'))">$(TargetFrameworks);net10.0-windows10.0.19041.0</TargetFrameworks>

The compiler builds your project once for each target. Files in the Platforms folder (Platforms/Android, Platforms/iOS, Platforms/MacCatalyst, Platforms/Windows) are only compiled for their own platform. That is the foundation of everything else below.

flowchart LR
    A["Shared code<br/>(Views, ViewModels, Services)"] --> B["net10.0-android"]
    A --> C["net10.0-ios"]
    A --> D["net10.0-maccatalyst"]
    A --> E["net10.0-windows"]
    P1["Platforms/Android"] --> B
    P2["Platforms/iOS"] --> C
    P3["Platforms/MacCatalyst"] --> D
    P4["Platforms/Windows"] --> E

Shared code goes into every build; each Platforms folder goes into one build.

Asking which platform you are on

The DeviceInfo class tells you about the running device at runtime:

C#
if (DeviceInfo.Current.Platform == DevicePlatform.Android)
{
    // Android only
}

var idiom = DeviceInfo.Current.Idiom;       // Phone, Tablet, Desktop, Watch, TV
var model = DeviceInfo.Current.Model;       // for example "Pixel 8"
var version = DeviceInfo.Current.VersionString;

Runtime checks are easy to read, but both branches are compiled into every build. That means a runtime check cannot call an API that exists on only one platform, because the other builds would not compile.

OnPlatform and OnIdiom in XAML

For small visual differences, XAML has markup that picks a value per platform:

XML
<Label Text="Hello"
       FontSize="{OnPlatform Android=16, iOS=17, WinUI=15, Default=16}" />

<StackLayout Padding="{OnIdiom Phone='12', Tablet='32', Desktop='48'}">
    <!-- content -->
</StackLayout>

OnPlatform matches the platform names Android, iOS, MacCatalyst and WinUI. OnIdiom matches the form factor. The longer element syntax does the same for values that cannot be written inline:

XML
<Image>
    <Image.Source>
        <OnPlatform x:TypeArguments="ImageSource">
            <On Platform="Android" Value="icon_android.png" />
            <On Platform="iOS, MacCatalyst" Value="icon_apple.png" />
        </OnPlatform>
    </Image.Source>
</Image>

Conditional compilation with #if

When you must call a native API, use compiler symbols. The MAUI build defines ANDROID, IOS, MACCATALYST and WINDOWS:

C#
public static string GetAppFolderLabel()
{
#if ANDROID
    return Android.OS.Environment.DirectoryDocuments!;
#elif IOS || MACCATALYST
    return Foundation.NSSearchPath.GetDirectories(
        Foundation.NSSearchPathDirectory.DocumentDirectory,
        Foundation.NSSearchPathDomain.User)[0];
#elif WINDOWS
    return Windows.Storage.ApplicationData.Current.LocalFolder.Path;
#else
    return "unknown";
#endif
}

This works, but a method sprinkled with #if blocks gets hard to read. Keep each block small, and move bigger pieces into the pattern below.

Partial classes and the Platforms folder

The cleanest approach is a partial class. You declare the shape once in shared code and implement it separately for each platform:

C#
// Services/DeviceThemeService.cs  (shared)
namespace MyApp.Services;

public partial class DeviceThemeService
{
    public partial string GetSystemFontName();
}
C#
// Platforms/Android/DeviceThemeService.android.cs
namespace MyApp.Services;

public partial class DeviceThemeService
{
    public partial string GetSystemFontName() => "Roboto";
}
C#
// Platforms/iOS/DeviceThemeService.ios.cs
namespace MyApp.Services;

public partial class DeviceThemeService
{
    public partial string GetSystemFontName() => "San Francisco";
}

Each platform file is compiled only for its target, so it can use native types freely. A related option is filename-based multi-targeting: with the right project settings, files named *.android.cs or *.windows.cs anywhere in the project are compiled only for that platform.

The interface plus dependency injection pattern

Partial classes are great for small helpers. For services you want to test or swap, put an interface in shared code and register the platform implementation at startup:

C#
// MauiProgram.cs
builder.Services.AddSingleton<IDeviceThemeService, DeviceThemeService>();

Your view models ask for IDeviceThemeService in their constructor and never know which platform they are on. You will also see this pattern in the unit testing lesson, where a fake implementation replaces the real one.

Try it: a platform switch you can run

The stand-in below models the three ideas: a platform value, an OnPlatform-style picker, and a service chosen by platform.

C# Stand-in: OnPlatform and a platform service

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

In a real app the factory disappears: the compiler includes only one implementation per build and the DI container hands it out.

Choosing the right tool

Four ways to adapt

OnPlatform / OnIdiom Small visual differences in XAML
DeviceInfo Runtime checks for logic
#if symbols Tiny native snippets
Partial classes Real per-platform code

Start at the left, move right only when you must.

1 / 2

Try it: capability checks instead of platform checks

Asking "which platform?" spreads knowledge about platforms through your code. It is often better to ask "does this device have the capability?" and to hide the answer behind one object.

C# Stand-in: capability-based design

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

MAUI does the same thing with its feature APIs such as Vibration.Default.IsSupported. You will meet more of them in permissions and connectivity and sensors.

Common mistakes

  • Calling a native type inside a plain if (DeviceInfo.Platform == ...). The other targets will fail to compile; use #if or a partial class.
  • Forgetting that #if WINDOWS code compiles only for the Windows target, so IntelliSense in the editor may grey it out until you switch the active target framework.
  • Duplicating the same #if block in many files. Wrap it once in a service.
  • Using OnPlatform for behavior. It is meant for values.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a MAUI project do with files inside Platforms/Android?

    Each Platforms subfolder is compiled only into its own platform build, which is why it can use native APIs.
  2. 2. Which approach cannot call an Android-only type?

    A runtime if still compiles for all targets, so the Android type would not exist when building for iOS or Windows.
  3. 3. What is OnIdiom for?

    OnIdiom picks values by device type (Phone, Tablet, Desktop, Watch, TV). OnPlatform picks by operating system.
  4. 4. Why register platform services through an interface?

    Depending on an interface keeps view models platform-neutral and lets tests supply a fake.

Summary

  • A MAUI project is multi-targeted; Platforms/* folders compile into one platform each.
  • DeviceInfo gives runtime facts; OnPlatform and OnIdiom pick XAML values.
  • #if ANDROID, IOS, MACCATALYST and WINDOWS guard native snippets.
  • Partial classes or interfaces plus DI are the clean way to write per-platform code.
  • Prefer capability questions to platform questions.

Next: Permissions