Search code examples
c#clonetransactional

Transactions on Data within Instances?


I have a class with lots of data in it which allows some complex operations on the data within the class. The class also has some member functions which allow retrieving some data, i.e. to retrieve reference to object instances contained in the class. All the data is kept in the RAM (there is no DB which supports transactions in the background).

Now I would like to implement a kind of transaction concept, i.e. I would like to add a StartTransaction() method and a Rollback() method. And this is where my problem starts: How can I restore the data within a class to a previous state without altering any object references (as they might be used outside the class).

All cloning concepts are therefore not useful.

Is there a solution for this approach, or is the approach so weird that I should not follow it. What would be alternatives?


Solution

  • You can still use cloning, but your code requires a new level of indirection:

    Old:

    class Data { int SomeValue; }
    
    class DataInternal { int SomeValue; }
    class Data { DataInternal internal; int SomeValue { get { return internal.SomeValue; } }
    

    That allows you to decouple external interface (Data) from storage (DataInternal). You can clone and restore internal however you want without anyone noticing.