access base class variable in derived class

sam picture sam · Mar 14, 2011 · Viewed 28.2k times · Source
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 child class whatever i input.. but i always get the values of both variables 0. 0 is default value of both variables.

Can anyone tell me that how can i get the value???

thx in adv..

Answer

Furqan Hameedi picture Furqan Hameedi · Mar 14, 2011

Yes, Zero is what you should get, since you made single instance of child class and did not assign any value to its inherited variables,

child obj1 = new child();

rather you have instantiated another instance of base class separately and assign value to its members,

baseClass obj = new baseClass();

both runtime both the base class instance and child instance are totally different objects, so you should assign the child values separately like

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

then only you shall get the desired result.