Base Access Class Variable in a Derived Class

class Program { static void Main(string[] args) { baseClass obj = new baseClass(); obj.intF = 5; obj.intS = 4; child obj1 = new child(); Console.WriteLine(Convert.ToString(obj.addNo())); Console.WriteLine(Convert.ToString(obj1.add())); Console.ReadLine(); } } public class baseClass { public int intF = 0, intS = 0; public int addNo() { int intReturn = 0; intReturn = intF + intS; return intReturn; } } class child : baseClass { public int add() { int intReturn = 0; intReturn = base.intF * base.intS; return intReturn; } } 

I want to access intF and intS in a child class no matter what I entered .. but I always get the values ​​of both variables 0. 0 is the default value for both variables.

Can someone tell me how can I get the value ???

thanks in adv ..

+4
source share
2 answers

Yes, Zero is what you should get, since you made a single instance of the child class and did not assign its values ​​to the inherited variables,

 child obj1 = new child(); 

instead of creating an instance of another instance of the base class separately and assigning value to its members,

 baseClass obj = new baseClass(); 

both runtimes, both an instance of the base class and a child instance, are completely different objects, so you must assign child values ​​separately, for example

 obj1.intF = 5; obj1.intS = 4; 

then you get the desired result.

+4
source

You have two separate objects - this problem. The values ​​of the base class variables in the object referenced by obj1 are 0, since they were not configured for anything else. There is nothing to associate this object with the object referenced by obj .

If you need to access the variables of another object, you need to make this object available to someone who is trying to access the data. You can pass obj as an argument to the method, or perhaps make it a property. There are many different approaches here, but we don’t know what the big picture is - what are you really trying to do. Once you understand why it doesn't work the way you expect, you can start thinking about what you are really trying to do.

To be understood, this has nothing to do with inheritance. It has everything related to the creation of two different objects. You will get the same effect if you used only one class, but created two different instances of this class.

+2
source

Source: https://habr.com/ru/post/1343599/


All Articles