Lennie
Lennie

Reputation: 2069

Private in class call parent class method

A newbie question, I got the following C# code where there is a inner-class B that need to call a method on class A.

Please advise how.

class A
{
  void MethodA() {
  }

  class B {
    void MethodB {
      // Now method B need to call Method A above
    }
  }
}

Upvotes: 2

Views: 113

Answers (2)

fhnaseer
fhnaseer

Reputation: 7277

Make object of A inside class B. And use it inside MethodB.

class B
{
    private A objectA;
    void MethodB()
    {
        objectA.MethodA();
    }
}

Initialize objectA before using. You can do this in constructor.

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062780

Nested types don't automatically have an instance of their parent type; you would need something like:

class B {
    private readonly A a;
    public B(A a) { this.a = a; }
    void MethodB() { a.MethodA(); }
}

and instead of new B(), you would use new B(this).

Upvotes: 4

Related Questions