0

Can any one let me know "How to access base class variables in derived class"?

Example:

Class 1.cs Code

public class baseClass
{
    public int intF = 0, intS = 0;
    public int addNo()
    {
        int intReturn = 0;
        intReturn = intF + intS;
        return intReturn;
    }
}

Public class child : baseClass
{
    public int add()
    {
        int intReturn = 0;
        intReturn = base.intF * base.intS;
        return intReturn;
    }
}

Class2.cs Code

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();
    }
}

The problem is in child class which gets inherited from base class..

The value of intF and intS is always showing as 0 instead of 5&4.

Can any one let me know where I am going wrong?

Regards,

G.V.N.Sandeep

  • Both answers are correct. The two easiest ways to get the expected result are: 1) declare obj as "baseClass obj = new child()" and delete the line where you create obj1 (it will always be default); and 2) declare intF and intS as "public static int" – Daniel May 30 '13 at 10:47
  • Exact duplicate (why?): http://stackoverflow.com/questions/5296026/ – Jeppe Stig Nielsen May 30 '13 at 10:51

2 Answers2

3

Instance fields intF and intS belong to... instance, not to a type. When you're setting them for obj instance, the same fields in obj1 instance have their default values (zeroes).

You must assign 5 and 4 this way:

child obj1 = new child();
obj1.intF = 5;
obj1.intS = 4;
Dennis
  • 37,026
  • 10
  • 82
  • 150
1

Your fields are not static. There is one separate field for each instance (object) you create.

obj and obj1 are distinct instances.

By the way, there's no need to use the base keyword in this situation. The two fields are in the child class because of inheritance. Only use base when the current class overrides or hides a member from the base class.

Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181