2

So, I'm trying to figure out, how to determine whether or not my variable changing, is increasing it's value, or decreasing it. I know I could use a variable for this, to just store the old value, but it's not an option in this case.

int variable = 0;
variable = 1;
if(variable has increased) {
      //Do Magic stuff
}

That's basicly, how I would think of doing it. I don't know if it's possible this way, without a container for the old value, but I thought there might be a C# Function, that could figure this out, from perhaps a Memory address?

I haven't got a clue on, what this method or technique is called either, so a heads up on that would be great too.

Preet Sangha
  • 61,126
  • 17
  • 134
  • 202
Kevin Jensen Petersen
  • 323
  • 1
  • 17
  • 39
  • http://stackoverflow.com/questions/5842339/how-to-trigger-event-when-a-variables-value-is-changed is a similar question. It should have what you need. – damienc88 Dec 09 '13 at 23:58
  • I think the 'method or technique' you are looking for is called a [state machine](http://stackoverflow.com/questions/5923767/simple-state-machine-example-in-c). – crthompson Dec 09 '13 at 23:58

2 Answers2

5

Make the variable a property (in a class).

In that property's setter, record whether the variable is increasing or decreasing each time it is set.

For example:

class Class1
{
    private int _counter;
    private int _counterDirection;

    public int Counter
    {
        get { return _counter; }

        set
        {
            if (value > _counter)
            {
                _counterDirection = 1;
            }
            else if (value < _counter)
            {
                _counterDirection = -1;
            }
            else
            {
                _counterDirection = 0;
            }
            _counter = value;
        }
    }

    public int CounterDirection()
    {
         return _counterDirection;
    }
}
Mitch Wheat
  • 280,588
  • 41
  • 444
  • 526
2
    class Program
    {
    private int _variableValue;
    private bool _isIncreasing;

    public int Variable
    {
        get
        {
            return _variableValue;
        }
        set
        {
            _isIncreasing = _variableValue <= value;
            _variableValue = value;
        }
    }

    void Main(string[] args)
    {

        Variable = 0;
        Variable = 1;
        if (_isIncreasing)
        {
            //Do Magic stuff
        }
    }
}
PCG
  • 1,189
  • 9
  • 22