public class CustomModel : ICloneable { private int _age; public int Age { get { return this._age;} set { this._age=value;} } public override object Clone() { return this.MemberwiseClone(); } } public class SafeClass { private CustomModel _model; public SafeClass(CustomModel model) { // version 1 this._model = model; // version 2 this._model = (CustomModel)model.Clone(); } }
CustomModel cm = new CustomModel(); cm.Age = 20; SafeClass sc = new SafeClass(cm); cm.Age = 40; //==> here, we can temper with internal data of sc object ! It lacks encapsulation !
SafeClas sc = new SafeClass((CustomModel)cm.Clone());