Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access to the parent object in c#

Tags:

c#

oop

parent

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();    } } 
like image 760
Jean Duprez Avatar asked Dec 21 '09 13:12

Jean Duprez


People also ask

How to get parent object from child object in c#?

I would give the parent an ID, and store the parentID in the child object, so that you can pull information about the parent as needed without creating a parent-owns-child/child-owns-parent loop. Show activity on this post. something like this: public int PowerRating { get { return base.

How to get parent class in c#?

GetType(). BaseType returns the base Type of class o parent class. instance. GetType().

How to get parent object in Java?

Java uses class-based inheritance. if you have B b = new B(); you can get the parent A by default casting Java provides. A a = (A)b This is automatic, so just writing A a = b will have the same result.

Can we have child reference to parent object?

The parent class can hold reference to both the parent and child objects. If a parent class variable holds reference of the child class, and the value is present in both the classes, in general, the reference belongs to the parent class variable. This is due to the run-time polymorphism characteristic in Java.


1 Answers

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.

like image 110
Christian Avatar answered Sep 21 '22 08:09

Christian