This might be a silly question, but I’m a beginner in C#, so please bear with me.
What happens if I name a variable the same in both the base class and the sub class?
For example:
class BaseClass01
{
int x = 10;
}
class SubClass01 : BaseClass01
{
int x = 20;
public int Multiplicative(int a)
{
return x * a;
}
}
if a = 10, the answer I got was 200.
Does this mean variable “int x” in BaseClass01 is different from “int x” in SubClass01? Would anybody be able to provide an example that illustrate the differences?
Thanks in advance for helping me wrap my head around this confusing concept of inheritance!
Edit:
Based on the comments below, I tinkered with the code, and realized that when accessing methods from the base class, the “x” from the subclass does not carry over:
class BaseClass01
{
int x = 10;
public int Subtraction(int a)
{
return a - x;
}
}
class SubClass01 : BaseClass01
{
int x = 20;
public int Multiplicative(int a)
{
x = x * a
return x;
}
}
private void button4_Click(object sender, EventArgs e)
{
SubClass01 sb = new SubClass01();
int answer1 = sb.Multiplicative(10);
int answer2 = sb.Subtraction(answer1);
}
Subtraction() continues to use the “x” value from BaseClass01 (i.e. x remains 10). Using protected keyword avoids the issue entirely.
Thanks for the explanations!
Yes they are different fields that happen to have the same unqualified name.
You can think of:
as:
To access the
BaseClass01.x, use thebasekeyword:(You’d also need to make
BaseClass01.xprotected and markSubClass01.xas new.)