Search code examples
c#oopparent

How to access to the parent object in c#


I have a "meter" class. One property of "meter" is another class called "production". I need to access to a property of meter class (power rating) from production class by reference. The powerRating is not known at the instantiation of Meter.

How can I do that?

public class Meter
{
   private int _powerRating = 0; 
   private Production _production;

   public Meter()
   {
      _production = new Production();
   }
}

Solution

  • Store a reference to the meter instance as a member in Production:

    public class Production {
      //The other members, properties etc...
      private Meter m;
    
      Production(Meter m) {
        this.m = m;
      }
    }
    

    And then in the Meter-class:

    public class Meter
    {
       private int _powerRating = 0; 
       private Production _production;
    
       public Meter()
       {
          _production = new Production(this);
       }
    }
    

    Also note that you need to implement an accessor method/property so that the Production class can actually access the powerRating member of the Meter class.