Clear Preferences on Startup in Xamarin.Forms When Debugging

Published on

I'm building a cross platform app in Xamarin.Forms for iOS, Android & UWP and needed to find a way to clear the preferences on start-up, but only while debugging.

Example Use Case

This is for testing purposes and shouldn't happen when the app is deployed to a live environment. For example in my particular business application, there is an ID that needs to be typed by a user when the app runs for the first time. The ID is saved to the preferences store using something like the below:

Xamarin.Essentials.Preferences.Set("idString", idString);

While i'm debugging, I might want to test a different ID each time I run the app. Or test a particular script that only runs on the very first launch of the application (when no preferences have been saved).

Here are the best two ways I found to accomplish this task.

Method 1 (Recommended)

This first method is what I chose to use.

Essentially, we check to see if the debugger is attached to the Xamarin.Forms application.

If the debugger is attached, then we clear the preferences. We can then have an else statement to do something else, or if you remove the else statement then the application will continue as normal.

using System.Diagnostics;

if (Debugger.IsAttached)
    Xamarin.Essentials.Preferences.Clear();
else
    DoSomethingElse();

Method 2

The second method for achieving this goal is to use the preprocessor directive #if DEBUG.

#if DEBUG
  Xamarin.Essentials.Preferences.Clear();
#endif

As a personal preference I don't like to use this method because I think it looks a little uglier. But it works and is perfectly fine and valid code.

Where to place?

Whichever method you choose to clear the preferences from the local cache, you could place the code in either the main app class's constructor or in the OnStart method in the shared project. This will ensure that the code runs ASAP once the application starts.

using System.Diagnostics;

public App()
{
    if (Debugger.IsAttached)
        Xamarin.Essentials.Preferences.Clear();
    else
        DoSomethingElse();

    InitializeComponent();
    MainPage = new MainPage();
}

// OR


protected override void OnStart()
{
    if (Debugger.IsAttached)
        Xamarin.Essentials.Preferences.Clear();
    else
        DoSomethingElse();
}

 


Article Categories: # xamarin # c# # xamarin.forms
Date Published: Apr 23, 2020

About

A tech blog by Andy P. I talk about coding, enterprise software development, tech, games design & other things that interest me.

Signup To The Newsletter

I try to post a new interesting article every saturday.

IT Asset Management

Our friends at AssetPad are building a complete online solution for managing the IT assets within your organisation. With barcodes and documentation tools.