Reputation: 1
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
Upvotes: 0
Views: 1372
Reputation: 61912
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.
Upvotes: 1
Reputation: 37760
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;
Upvotes: 3