Daniel Herbrych
Daniel Herbrych

Reputation: 39

Reference between two classes

I have this code. Problem is I need access from class Database to class MainWindow. I tried to inherit in Database from MainWindow but it didnt work. I just need to have reference in both classes to each other class. Thanks for any advice!

public partial class MainWindow : Window
{
    Database db = new Database(@"database.txt");

    public MainWindow()
    {
        InitializeComponent();
    }

    public void setLabel(string s) 
    {
        Vystup.Content = s;
    }
}

class Database 
{
   //constructor and other methods

   public void doSomething()
   {
       //Here I want to set Label in MainWindow, something like
       //MainWindow.setLabel("hello");
   }
}

Upvotes: 0

Views: 502

Answers (1)

Blake Thingstad
Blake Thingstad

Reputation: 1659

There are a few ways to do this...

  • Passing a reference of MainWindow to Database in Database's constructor. This is not recommended because then Database is dependent on MainWindow.
  • Have the database function return the value that needs to be set whenever MainWindow has the Database do something.
  • Passing an Action in the Database constructor for it to invoke when doSomething is called.

Passing a reference (not recommended)...

public partial class MainWindow : Window {
    Database db = new Database(this, @"database.txt");
    public void setLabel(string s) {
        Vystup.Content = s;
    }
}

class Database {
    private MainWindow _mainWindow { get; set; }
    public Database(MainWindow window, string file) {
        this._mainWindow = window;
        ...
    }
    public void doSomething() {
        _mainWindow.setLabel("hello");
    }
}

Database returns value to be set...

public partial class MainWindow : Window {
    Database db = new Database(@"database.txt");
    public void setLabel(string s) {
        Vystup.Content = s;
    }
    public void SomeDatabaseThing()
    {
        string returnValue = db.doSomething();
        setLabel(returnValue);
    }
}

class Database {
    public Database(string file) {
        ...
    }
    public string doSomething() {
        return "hello";
    }
}

Passing Action in constructor...

public partial class MainWindow : Window {
    Database db = new Database(@"database.txt", setLabel);
    public void setLabel(string s) {
        Vystup.Content = s;
    }
}

class Database {
    private Action<string> _onDoSomething = null
    public Database(string file, Action<string> onDoSomething) {
        this._onDoSomething = onDoSomething;
        ...
    }
    public void doSomething() {
        onDoSomething("hello");
    }
}

Upvotes: 1

Related Questions