Question

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.

Was it helpful?

Solution

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;
    }
}

OTHER TIPS

    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
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top