| MAUI-Device-APIs | MAUI-Permissions | |
.NET MAUI Conditional Compilation |
When you need to call a feature that .NET MAUI hasn't abstracted (or you need a specific native behavior), you use Conditional Compilation with #if directives. This tells the compiler to only include that block of code when building for that specific platform.
The compiler recognizes these built-in symbols:
You can use these inside any .cs file. The code inside inactive blocks is completely ignored by the compiler for that build target.
public void ShowPlatformMessage()
{
#if ANDROID
// This code only exists in the Android APK
var message = "Hello from Android Native!";
#elif IOS
// This code only exists in the iOS IPA
var message = "Hello from iOS Native!";
#else
var message = "Hello from an unknown platform!";
#endif
Console.WriteLine(message);
}
The real power comes from accessing native classes (like Android.App or UIKit.UIView) directly inside your shared logic.
public string GetSystemVersion()
{
#if ANDROID
return Android.OS.Build.VERSION.Release;
#elif IOS
return UIKit.UIDevice.CurrentDevice.SystemVersion;
#elif WINDOWS
return Microsoft.Windows.System.UserProfile.GlobalizationPreferences.Languages[0];
#else
return "Not available";
#endif
}
This is the most common place to use #if for configuring platform-specific lifecycle events or handlers.
builder.ConfigureLifecycleEvents(events =>
{
#if ANDROID
events.AddAndroid(android => android
.OnCreate((activity, bundle) =>
Log.Info("TAG", "Android Created!")));
#elif IOS
events.AddiOS(ios => ios
.FinishedLaunching((app, options) =>
{
Console.WriteLine("iOS Launched!");
return true;
}));
#endif
});
While #if directives are great for quick fixes, MAUI also supports Partial Classes and the Platforms Folder (Platforms/Android/, Platforms/iOS/, etc.).
Think of #if directives as a safety valve: you use them only when you must dip into platform-specific territory, while keeping most of your app cross-platform
| MAUI-Device-APIs | MAUI-Permissions | |