This might be a dumb question, but I'm new to C #, so please bear with me.
What happens if I name the variable the same in both the base class and subclass?
For instance:
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 received was 200.
Does this mean that the variable "int x" in BaseClass01 is different from "int x" in SubClass01? Can anyone provide an example illustrating the differences?
Thank you in advance for helping me trick this confusing concept of inheritance!
Edit:
Based on the comments below, I was messing around with the code and realized that when accessing methods from the base class "x", it is not transferred from the subclass:
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 value "x" from BaseClass01 (that is, x remains 10). Using a secure keyword completely fixes the problem.
Thanks for the explanation!
source share