K
K
killman2022-04-15 22:07:16
C++ / C#
killman, 2022-04-15 22:07:16

How to make c# action happen when changing the value of a variable?

I have a variable and I need to track the change, and if it has changed, then erase its value

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vasily Bannikov, 2022-04-15
@killman

You make a property instead of a "variable" and inside the setter you call some method that will notify interested parties about the change.
For example like this:

public class Test {
  private int _someValue;
  public int SomeValue
  {
    get => _someValue;
    set {
      if(value != _someValue) {
        _someValue = value;
        NotifyAboutChange(); // То самое "действие"
      }
    }
  }
}

You can read about events here:
https://docs.microsoft.com/ru-ru/dotnet/csharp/lan...

F
forced, 2022-04-15
@forced

To do this, an event is created: it is called by the method where the variable is used. Event subscribers receive information about the current value of the variable and execute their code.

F
freeExec, 2022-04-16
@freeExec

Or use some reactive framework
https://www.nuget.org/packages/ReactiveProperty/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question