Store data and global variables using the Application object


In Xamarin, I am wanting to store data and global variables using the Application object.

I looked at this resource for this code:

Here is my code:

    public class HelloApplication : Application
        private int GlobalVariable = 1;

        public int GetGlobalVariable()
            return GlobalVariable;

        public void SetGlobalVariable(int GlobalVariable)
            this.GlobalVariable = GlobalVariable;

I am trying to reference the class using this code:

    int variable=((HelloApplication)GetApplication()).getGlobalVariable();

When I build the application I am getting this error for both the above lines of code:

The name 'GetApplication' does not exist in the current context

Can I please have some help to get this code working?

Thanks in advance


Here is my code:

HelloApplication state = ((HelloApplication) this.ApplicationContext);
int globalVariable = state.GetGlobalVariable ();

Toast.MakeText (this, "Global variable " + globalVariable, ToastLength.Short).Show ();

This is the error I am getting:

UNHANDLED EXCEPTION: System.InvalidCastException: Cannot cast from source type to destination type.

Can I please have some help to get this working?

Looking at the code you could just make the variable a public static.

public class HelloApplication : Application
    public static int GlobalVariable = 1;


HelloApplication.GlobalVariable = 10;