Adding a clone of an object to a list in c# (prevent modification from outside)
c#, pass-by-reference, reference
Solution
The C# language does not support cloning of objects. Therefore, if `obj1` is not a value object (i.e. a struct), you cannot do that. Note: there is the possibility of implementing `ICloneable`, however, its use is not advised.
One approach I use in another project is to use AutoMapper to create a copy of the object before inserting into the list. Example:
MyType copy = Mapper.DynamicMap(obj1);
list.Add(copy);
Please use that approach for value holder types only, especially not for types that implement `IDisposable` or something similar.
Problem
I have an object like `'obj1'` which I want to add to a list. I can add it by just `list1.add(obj1)` .Now once I update `obj1`, the object in my list is also updating! (I understand that I am dealing with references here) My requirement demands modifying the `obj1` and add it to the list again! Instead of having two different objects, I have only one, because for both of them, the reference is the same - `obj1`. Is there any way I can modify this `obj1` and add it to the list and still not lose the old one? Any workarounds would be extremely helpful! Thanks in Advance!