Glinkot
Glinkot

Reputation: 2964

Monotouch - Accessing App level variables (CS0120)

I am creating an instance of something (a database class) in AppDelegate.cs and would like to access this instance from my ViewControllers. It returns a CS0120 error, "An object reference is required to access non-static member `GeomExample.AppDelegate._db' (CS0120)"

I create my instance in AppDelegate like this:

[Register ("AppDelegate")]
    public partial class AppDelegate : UIApplicationDelegate
    {
        ...
        public Database _db;

        public override bool FinishedLaunching (UIApplication app, NSDictionary options)
        {
            ...
            _db = new Database (Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments), "myDb.db"));
            _db.Trace = true;

I then try to access it like so, which generates the error:

IEnumerable<DbShapeElement> shapes = AppDelegate._db.GetShapeElements (_shapeName, null);

Any help appreciated!

Upvotes: 2

Views: 1400

Answers (1)

Preet Sangha
Preet Sangha

Reputation: 65506

Caveat: I don't know MonoTouch but reading this this question : Monotouch: How to update a textfield in AppDelegate partial class?.

It seems to me that :

public Database _db; is non Static. You need to use the instance of the AppDelegate that you have.

Try this:

var ad = (AppDelegate) UIApplication.SharedApplication.Delegate;
IEnumerable<DbShapeElement> shapes = ad._db.GetShapeElements (_shapeName, null);

Edit:

Instead of using a public instance variable, it's cleaner to use a property with a private setter to prevent modification outside the AppDelegate class:

[Register ("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
    ...
    public Database Db {
        get;
        private set;
    }

    public override bool FinishedLaunching (UIApplication app, NSDictionary options)
    {
        ...
        Db = new Database (Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments), "myDb.db"));
        Db.Trace = true;
        ...

then you access it like this outside the AppDelegate class:

var ad = (AppDelegate) UIApplication.SharedApplication.Delegate;
IEnumerable<DbShapeElement> shapes = ad.Db.GetShapeElements (_shapeName, null);

Upvotes: 4

Related Questions