Mike Makarov
Mike Makarov

Reputation: 1356

Is there a class in .Net to store a value and a previous value?

I need to store a current value of an object and its previous value. I came up with something like this:

struct TwoStepHistory<T>
{
    private T _v0;

    public T Value
    {
        get
        {
            return _v0;
        }
        set
        {
            OldValue = _v0;
            _v0 = value;
        }
    }

    public T OldValue { get; private set; }
}

But it looks so obvious and simple that I thought there must be something in BCL or elsewhere in dotnet doing the same. Don't want to reinvent a bicycle, you know. Does anyone know about a similar structure?

There were some comments whether this is usable for reference type, and here is an example, everything works, not sure why people get confused. https://dotnetfiddle.net/BSm1Pz, v2 with target object mutation: https://dotnetfiddle.net/DGkAgv

Upvotes: 4

Views: 484

Answers (1)

Jamiec
Jamiec

Reputation: 136154

No, there is nothing in the BCL to support this. It is an implementation detail better left to application developers than the base library.

A couple of notes:

  1. Structs should be immutable
  2. You might want to consider storing a copy of the old item, rather than a reference to it - which can be changed from elsewhere (see: https://dotnetfiddle.net/HOqLuq)

Upvotes: 2

Related Questions