Gintas_
Gintas_

Reputation: 5030

Calling other class function

I have a grid class and a MainWindow class. Grid's class function needs to call MainWindow's function:

    // function from grid class:
    public Point functionFromGridClass()
    {
        Point variable = MainWindow.functionFromMainWindowClass(0, 0);
        // ...
    }
    // function from MainWindow class:
    public static Point functionFromMainWindowClass(int x, int y)
    {
        Vector2 mouse;
        mouse.X = x;
        mouse.Y = y + (ClientRectangle.Height - glview.Size.Height);
        // ...
    }

If I remove static keyword in functionFromMainWindowClass, then I can't call it from grid class. If I don't remove static keyword, then I can't use the MainWindow's class variables ClientRectangle and glview, I get a warning "An object reference is required for the non-static field, method, or property". I've never faced this problem, what should be the solution?

Upvotes: 0

Views: 1308

Answers (4)

Gurmeet
Gurmeet

Reputation: 3314

Static methods are called with reference of the className. Call you Main window class function like this:

public Point functionFromGridClass()
{
     MainWindowClass.functionFromMainWindowClass(val1, val2);

}

Upvotes: 0

Babak
Babak

Reputation: 121

The grid class has to hold a reference of an instance of the MainWindow and probably provided to grid upon construction.

public class GridClass
{
  private MainWindow window;
  public GridClass( MainWindow Window)
  {
     window = Window;
  }
  public Point functionFromGridClass()
  {
     Point variable = window.functionFromMainWindowClass(0, 0);
  }
}

Upvotes: 2

carlpett
carlpett

Reputation: 12583

It's hard to give specific advice without knowing exactly what is going on, but the general picture is that you need to somehow get the instance of the MainWindow class that you want to call the method on, either by passing it into Grid at construction or similar, or by getting it from some resource manager.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

I get a warning "An object reference is required for the non-static field, method, or property"

The warning tells you what to do: you need an instance in order to call instance methods.

So you could remove the static keyword from the method and then in your Grid class create an instance of MainWindow in order to be able to call the method:

var mainWindow = new MainWindow();
var result = mainWindow.functionFromMainWindowClass(5, 6);

Upvotes: 2

Related Questions