tags:

views:

784

answers:

5

Hi,

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 ?

Thanks in advance

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

   public Meter()
   {
      _production = new Production();
   }
}
+5  A: 

You would need to add a property to your Production class and set it to point back at its parent, this doesn't exist by default.

bwarner
A: 

something like this:

  public int PowerRating
    {
       get { return base.PowerRating; } // if power inherits from meter...
    }
Tony
It's a parent/child relationship, not an "inherits" relationship.
GalacticCowboy
@GalacticCowboy, oh yes, I see what you mean. Silly me
Tony
A: 

Why not change the constructor on Production to let you pass in a reference at construction time:

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

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

In the Production constructor you can assign this to a private field or a property. Then Production will always have access to is parent.

Rob Levine
+4  A: 

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.

Christian
A: 

You could maybe add a method to your Production object called 'SetPowerRating(int)' which sets a property in Production, and call this in your Meter object before using the property in the Production object?

Gary Willoughby
I think this violates KISS; having to remember to call a function before calling a property makes it overly complicated IMO.
Matt Ellen
True, the above design sounds as if it needs a whole re-think. I just supplied a solution and it's probably not the best one.
Gary Willoughby