Home > Enterprise >  C# Inheritance of variables and its modification
C# Inheritance of variables and its modification

Time:04-18

I have the following Control abstract class where some common variables, fields and methods are defined. ClickState is an emum type. Then I derive the button class where I do not override the Update method since I don't need any additional behaviour, so I use the base one.

public abstract class Control
{ 
private ClickState _clickState;

   public Control()
   {
      _clickState = CliskState.Start;
   }

   public virtual void Update()
   {
      if(***some check if mouse is over the control***)
        {
          _clickstate = ClickState.MouseOver;
        }
   }
}

public class Button : Control
{
///other code
}

...

b = new Button();

every frame:

b.Update();

Now, when I mouse over my button the check in the Update method (called every frame) actually works but somehow the _clickState variable does not change. If I put a breakpoint in the code after the assignment I see that the _clickState variable of the Control class changed but the one in Button did not... I am conused, I tought that the Button._clickState should be the same of its "mother" class Control since is inherited. Is the issue with some access modifier? Thank you for your help.

CodePudding user response:

Your understanding is correct and I believe your code works correct also. Or you didn't show some piece of code that may do some changes.
Be sure you don't have another _clickState field in your Button class.

Here is my version of your code: https://dotnetfiddle.net/OKdSnj
Try to add console output inside of your IF statement to see all values in real-time - it might help you to troubleshoot.

    if(/*some check if mouse is over the control*/)
    {
        _clickState = ClickState.MouseOver;
        // Try to add console output to see all values here
        Console.WriteLine($"New state: {_clickState}");
    }
  • Related