How to access to the parent object in c#
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.
I wouldn't reference the parent directly in the child objects. In my opinion the childs shouldn't know anything about the parents. This will limits the flexibility!
I would solve this with events/handlers.
public class Meter
{
private int _powerRating = 0;
private Production _production;
public Meter()
{
_production = new Production();
_production.OnRequestPowerRating += new Func<int>(delegate { return _powerRating; });
_production.DoSomething();
}
}
public class Production
{
protected int RequestPowerRating()
{
if (OnRequestPowerRating == null)
throw new Exception("OnRequestPowerRating handler is not assigned");
return OnRequestPowerRating();
}
public void DoSomething()
{
int powerRating = RequestPowerRating();
Debug.WriteLine("The parents powerrating is :" + powerRating);
}
public Func<int> OnRequestPowerRating;
}
In this case I solved it with the Func<> generic, but can be done with 'normal' functions. This why the child(Production) is totally independent from it's parent(Meter).
But! If there are too many events/handlers or you just want to pass a parent object, i would solve it with an interface:
public interface IMeter
{
int PowerRating { get; }
}
public class Meter : IMeter
{
private int _powerRating = 0;
private Production _production;
public Meter()
{
_production = new Production(this);
_production.DoSomething();
}
public int PowerRating { get { return _powerRating; } }
}
public class Production
{
private IMeter _meter;
public Production(IMeter meter)
{
_meter = meter;
}
public void DoSomething()
{
Debug.WriteLine("The parents powerrating is :" + _meter.PowerRating);
}
}
This looks pretty much the same as the solution mentions, but the interface could be defined in another assembly and can be implemented by more than 1 class.
Regards, Jeroen van Langen.
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.