0

I know to perform a shallow copy in C# we could use MemberwiseClone() function but I have an object inside a function and I want to take a copy of this object, so when I added to a list it won't refer to the same object when the object is changed here is my code

public void Do(object undoState)
    {
        _index += 1;
        if (_buffer.Count > _index)
            _buffer.RemoveRange(_index, _buffer.Count - _index);
        _buffer.Add(undoState);
    }

I want to copy the UndoState object to a new object and added to the buffer

thank you

jprbest
  • 717
  • 6
  • 15
  • 32
  • 1
    See http://stackoverflow.com/a/1031062/939213 – ispiro Jan 11 '12 at 14:00
  • What you have stated here "take a copy of this object, so when I added to a list it won't refer to the same object" is a Deep copy wherein you do not simply create a copy of the reference to the Object but create a new object and copy the underlying values. – Lloyd Jan 11 '12 at 14:25

1 Answers1

2

implement the ICloneable interface, and add your copy logic into it. Now instead of receiving an object in your Do method, use ICloneable.

dowhilefor
  • 10,971
  • 3
  • 28
  • 45