Nick Tsui
Nick Tsui

Reputation: 634

Monitoring a variable in C#

I am wondering what is the best way to monitor a variable in C#. This is not for debugging. I basically want the program it self to monitor one of its variable all the time during running. For example. I am trying to watch if _a is less then 0; if it is, then the program stops.

 _a = _b - _c; // (_b >= _c) 

So _a ranges within [0 N], where N is some positive int; I feel the best is to start a thread that monitors the _a value. Once it, then I should response. But I have no idea how to implement it. Any one has any suggestions? A short piece of code sample will be highly appreciated.

Upvotes: 3

Views: 2093

Answers (3)

Jehof
Jehof

Reputation: 35544

The best way is to encapsulate your variable with a property.

Using this approach you can extend the setter of your property with custom logic to validate the value, logging of changes of your variable or notification (event) that your variable/property has changed.

 private int _a;

 public int MyA {
  get{
    return _a;
  }
  set {
    _a = value;
  }
 }

Upvotes: 2

Reed Copsey
Reed Copsey

Reputation: 564383

Instead of trying to monitor the value within this variable, you can make this "variable" a property of your class, or even wrap it's access into a method for setting the value.

By using a property or method, you can inject custom logic into the property setter, which can do anything, including "stopping the program."

Personally, if the goal was to stop the program, I would use a method:

private int _a;
public void SetA(int value)
{
    if (value < 0)
    { 
        // Stop program?
     }
    _a = value;
}

Then call via:

yourClass.SetA(_b - _c);

The reason I would prefer a method is that this has a distinct, dramatic side effect, and the expectation is that a property setter will be a quick operation. However, a property setter would work just as well from a technical standpoint.

A property could do the same thing:

private int _a;
public int A
{
    get { return _a; }
    set
    {
        if (value < 0)
        {
            // Handle as needed
        }

        _a = value;
    }
}

Upvotes: 5

Related Questions