Warning

Fraudulent domains such as innostaxtech.com or innostaxtechllc.com are NOT affiliated with Innostax. Official communication only comes from @innostax.com. We never request money, banking details, deposits, or equipment purchases during hiring.

Cross-Platform Mobile Development with .NET : Xamarin

Explore cross-platform mobile development with Xamarin and .NET. Learn to build native iOS and Android apps using C# with improved performance and scalability.

Building Your First Android App
Key takeaways
  • 1 Xamarin – allows to create a native application for iOS, Android and Windows from a single codebase implemented in C# using . NET framework as an environment for working with high-performance User Interface.
  • 2 By using Xamarin. Tenants, developers can achieve consistent user interface across the platforms, this decreases the costs and time needed for the development while offering the ability to implement the platform’s distinctive characteristics.
  • 3 When it comes to creating Xamarin, Visual Studio, Xcode, and Android Studio have to be integrated, and testing can be carried out on emulators or physical devices hence the development process is easy.
  • 4 Xamarin Has Reached End of Life: Microsoft discontinued all support, including Xamarin.Forms, on May 1, 2024; no new bugs, security patches, or compatibility updates will be released, and new projects should be developed on .NET MAUI.
  • 5 There are migration paths for companies that have existing Xamarin.Forms applications: Microsoft provides migration tools and guidance for porting code to .NET MAUI, and businesses can continue to use their existing C# codebase while benefiting from .NET MAUI's support and modern tooling.

Introduction

Mobile app development has become an integral part of the software industry, with a diverse range of devices and platforms available. Building native apps for each platform can be time-consuming and resource-intensive. Xamarin, a cross-platform mobile development framework, comes to the rescue by allowing developers to write native apps using C# and .NET, while sharing a significant portion of the codebase across iOS and Android platforms.

Important Update: Xamarin Has Reached End of Life

Before pressing on, it’s worth addressing an issue affecting anyone considering Xamarin at this point in time: Microsoft has officially withdrawn support for Xamarin (including Xamarin.Forms) from May 1 st 2024. This means that Xamarin will no longer recieve bug fixes or security updates after this date, including compatibility updates for new versions of iOS and Android.

It’s worth noting that this isn’t an immediate issue for Xamarin apps currently in production: However, from this point onward Xamarin will steadily fall behind with new versions of iOS and Android, and security issues found after May 1 st 2024 will no longer be patched in Xamarin. This can be an issue for apps that handle sensitive data after this date, potentially putting both the company hosting the app and the users of the app at risk.

The recommended path forward from Microsoft is to move toward .NET Multi-platform App UI (.NET MAUI), which is effectively Xamarin.Forms with updated tooling moving forwards. .NET MAUI retains much of the same C#/.NET syntax described in this guide while also providing a single project file structure, active bug fixes and security updates, and modern features like Hot Reload. .NET MAUI is thus recommended as the path forward for cross-platform apps, rather than continuing development in Xamarin.Forms.

The rest of this guide should still be relevant for understand how Xamarin.Forms works, and will still apply for people maintaining existing Xamarin apps; However, new development should be in .NET MAUI from this point onward.

What is Xamarin?

It is an open-source framework that enables developers to create native apps for iOS, Android, and Windows using a single codebase. It leverages the power of the .NET platform and the C# programming language to deliver high-performance, fully native user experiences.

Xamarin.Forms vs. Native Xamarin: Which Approach Should You Use?

Xamarin can be considered as providing two fundamentally different approaches to developing cross-platform applications and the difference between them is essential to understand the architectural solutions described later in this guide.

Xamarin.Forms, which is used in the examples provided in this guide, permits developing applications where the user interface is described once in XAML and rendered on all three target platforms, whereas native Xamarin (Xamarin.iOS and Xamarin.Android) is used to develop applications with shared business logic layer and independent user interfaces.

Both approaches have their advantages and drawbacks and the choice between them depends on specific conditions, but Xamarin.Forms applications typically consume less development time and effort due to the ability to write shared code, but they might be considered less flexible in terms of customizing the appearance and behavior of UI elements because they have to be rendered in a way compatible with all supported platforms. On the contrary, native Xamarin applications provide full control over the user interface but require writing more code since the same logic and appearance generally have to be implemented for all platforms. Therefore, Xamarin.Forms is a better choice for applications where shared UI is more important than the ability to customize each platform’s specific UI, whereas native Xamarin is more suitable for applications with highly customized UI for each platform.

Setting Up Your Development Environment

Before diving into Xamarin development, you need to set up your development environment. Ensure that you have the following components installed:

  1. Visual Studio: Xamarin development is tightly integrated with Visual Studio, Microsoft’s flagship IDE. You can download Visual Studio from the official website.
  2. Tools: Once Visual Studio is installed, you need to install the Xamarin workload. This includes the SDKs and emulators.
  3. Xcode (for Mac): If you plan to develop iOS applications, you’ll need Xcode installed on your Mac.
  4. Android Studio (for Android): For Android development, install Android Studio and configure the Android SDK.

Creating Your First Xamarin Project

Let’s create a simple Xamarin.Forms project to get started. It is a UI toolkit that allows you to create a single user interface that can be shared across iOS, Android, and Windows.

  1. Open Visual Studio and select “Create a new project.”
  2. Choose the “Mobile App (Xamarin.Forms)” template.
  3. Give your project a name and click “Create.”

This will create a basic Xamarin.Forms project with shared code for iOS, Android, and Windows.

Xamarin.Forms Structure

A Xamarin.Forms project typically consists of the following components:

  • App.xaml: Defines the application’s entry point and resources.
  • MainPage.xaml: The main page of the application.
  • App.xaml.cs and MainPage.xaml.cs: Code-behind files for the App.xaml and MainPage.xaml files.

Xamarin.Forms UI Elements

Xamarin.Forms provides a wide range of UI elements to create a responsive and visually appealing user interface. Here are a few examples:

// Creating a Label
Label myLabel = new Label
{
    Text = "Hello, Xamarin!",
    FontSize = 20,
    HorizontalOptions = LayoutOptions.Center,
    VerticalOptions = LayoutOptions.CenterAndExpand
};

// Creating a Button
Button myButton = new Button
{
    Text = "Click me!",
    Command = new Command(() => { myLabel.Text = "Button Clicked!"; })
};

// Creating an Entry (Text Input)
Entry myEntry = new Entry
{
    Placeholder = "Enter text here",
    Keyboard = Keyboard.Text
};

Common Challenges When Building Xamarin.Forms Applications

Xamarin.Forms is able to simplify a lot of aspects of cross-platform development but also has some potential pits that developers who utilize the framework could fall into.

A Xamarin.Forms application may have performance issues when it comes to rendering nested views compared to its native counterparts as it adds an extra abstraction layer for rendering views. The reason for this pitfall is that Xamarin.Forms adds a new abstraction layer for every native control for the purpose of being able to render elements using shared code. In order to mitigate the effect of this pitfall, developers should ensure that their applications’ UI is shallow and should use performance profiling tools during the development in order to identify potential bottlenecks.

There is also an issue which comes from the inability to render UI elements identically across different mobile operating systems. Developers often need to put in more effort in order to ensure that the UI of their application looks identical on different platforms as the controls which make up the UI of the application are not rendered identically. This is particularly the case between iOS and Android as the significantly divergent design philosophies of the two platforms. In order to ensure that the application’s UI looks consistent enough across different platforms, developers should consider adding custom styles for controls on each platform for elements for which there are no built-in alternatives.

Finally, new APIs which are introduced to the target platforms cannot be used right away in Xamarin.Forms applications as the framework needs to expose these new APIs through its own abstraction layer. In the meanwhile, developers should use an alternative approach to implement necessary logic. For example, the DependencyService can be used to access the native code on the target device as shown in the first article of this series. This problem, however, will no longer exist because Xamarin.Forms will support the latest developments of the target platforms in the future; Xamarin, on the other hand, is no longer supported, and developers should instead consider using Flutter or .NET MAUI.

Platform-Specific Code

While Xamarin.Forms allows you to share a significant portion of your code, there may be scenarios where you need platform-specific functionality. Xamarin allows you to write platform-specific code using DependencyService.

// Interface definition in shared code
public interface IDeviceService
{
    string GetDeviceName();
}

// Implementation in iOS project
[assembly: Dependency(typeof(DeviceService))]
namespace YourApp.iOS
{
    public class DeviceService : IDeviceService
    {
        public string GetDeviceName()
        {
            return UIDevice.CurrentDevice.Name;
        }
    }
}

// Implementation in Android project
[assembly: Dependency(typeof(DeviceService))]
namespace YourApp.Droid
{
    public class DeviceService : IDeviceService
    {
        public string GetDeviceName()
        {
            return Build.Model;
        }
    }
}

Migrating an Existing Xamarin App to .NET MAUI

For teams who already have a Xamarin.Forms code base, it makes more sense to migrate to .NET MAUI rather than re-write the application from scratch, since the majority of one’s C# business logic and XAML code will be reused with only minor corrections.

The migration process can be largely automated with the official .NET Upgrade Assistant tool, which will update one’s namespace references, project structure, and NuGet packages. One should note, however, that one will need to merge one’s individual projects for different platforms into one in .NET MAUI, which is a major difference between the two.

Some controls and APIs have also been renamed in .NET MAUI for consistency, so it is necessary to invest time in testing one’s migrated code and studying the API reference. One may also need to update their custom controls, since Xamarin.Forms’ custom renderers have been replaced by .NET MAUI’s Handlers.

Third-party libraries and NuGet packages should also be checked for .NET MAUI compatibility prior to migration, since there may not be an appropriate alternative at the time of one’s adoption. It is recommended to plan one’s migrations in .NET MAUI as a series of iterative steps, and prioritize the migration of one’s core business logic, postponing the platform-specific customizations.

Running Your App

To test your app, select the target platform (iOS, Android, or Windows) and click the “Run” button in Visual Studio. This will launch the emulator or connect to a physical device for testing.

Testing Strategies for Xamarin.Forms Applications

Running an app on an emulator manually as described in the previous section is an option, but a production-ready application has to go through more rigorous testing before its launch.

Xamarin.UITest is a great tool that allows one to create unit tests that run on iOS and Android simulators and perform actions like clicking a button or typing a word into a text field, which in turn allows to verify that the application works correctly. It is recommended to run such tests against the compiled version of the project, as opposed to a test version, so that issues that may arise due to the two versions of the code existing can be detected.

If one wants to test the business logic of an application, writing unit tests in C# is an option, as the code can be compiled directly into .NET assembly. It will require using either NUnit or xUnit framework, which is standard for most .NET projects, but not any special Xamarin tools. The tests can be written in isolation from the UI, which is possible in Xamarin.Forms due to the separation of concerns and MVVM pattern suggested by the framework, so that no emulator has to be launched.

However, if the app is supposed to run on real devices, testing it on emulators is only a necessary evil due to the performance differences between the two, as well as other discrepancies like battery drain or camera issues. It is important to test on real devices, preferably different from one another, but a combination of a couple of devices and a couple of OS versions on them may suffice. Testing on older OS versions is especially important due to the amount of users that still use Android, for whom it is quite common to have a device with an older version of the OS.

Finally, such tools as Azure DevOps or App Center can be used to perform automated unit and integration tests every time a commit is made, which helps to detect issues earlier rather than waiting for the final stage of product launch.

Conclusion

Xamarin simplifies cross-platform mobile development by allowing developers to write native apps using the familiar C# language and .NET framework. With Forms, you can create a shared user interface for iOS, Android, and Windows, while still having the flexibility to write platform-specific code when needed. As you delve deeper, explore additional features, plugins, and community resources to enhance your mobile app development experience.

Additional Resources

Get a Fast Estimate on Your Software
Development Project

Chat With Us

Frequently Asked Questions

The Xamarin platform (including Xamarin.Forms) is no longer supported by Microsoft as of May 1, 2024.

Microsoft does not recommend starting new projects in Xamarin. It is advised to start new projects in .NET MAUI instead of Xamarin.

They will continue to work, but they will no longer receive security or compatibility updates.

It will depend on the complexity of your application, but Microsoft has an Upgrade Assistant that can help you automatically migrate most of your code. You can also reuse most of your C# business logic code.

In Xamarin.Forms, you need to create separate projects for each platform (iOS, Android, etc.), whereas in .NET MAUI, you can use one project for all platforms.

Xamarin.Forms can target Windows in addition to iOS and Android, but it is recommended to use .NET MAUI for developing applications for all three platforms.

Custom renderers in Xamarin are replaced with Handlers in .NET MAUI, but you will have to write new code for them, as there is no direct equivalent.