Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested C# Classes - Calling Outer Method From Inner

I have a ViewController class called GamePlay. In GamePlay there is a nested class called MyPinAnnotationView. When MyPinAnnotation's method TouchesBegan() gets called, I want to call a method CheckAnswer() from the parent GamePlay.

I do not want to create a new GamePlay instance because I have variables and instances already set. Can I access the parent in some way? ( Other than event listeners)

like image 585
Bryan Avatar asked Sep 16 '26 08:09

Bryan


1 Answers

The nested class will only be able to reference static members in the parent. If you want to access instance members, you need to get a reference to the instance. The simplest way to do this is to add it as a parameter to the constructor of MyPinAnnotationView like so:

class MyPinAnnotationView
{
  private GamePlay gamePlay;

  public MyPinAnnotationView(GamePlay gamePlay)
  {
    this.gamePlay = gamePlay;
  }

  public void TouchesBegan()
  {
    this.gamePlay.CheckAnswer();
  }
}

When you instantiate MyPinAnnotationView from GamePlay, just do this:

MyPinAnnotation annotation = new MyPinAnnotation(this);
like image 91
Asbjørn Ulsberg Avatar answered Sep 17 '26 20:09

Asbjørn Ulsberg