Reputation: 1347
I have the following code and In RT when mappingObject is updated oldObjToDel is updated accordingly, but my question is :
Is there a way to keep the oldObjToDel with the first reference without changing it like it happens after calling to the updateReferance method ? I want oldObjToDel to keep the object before changing it in UpdateReferance...
private bool UpdateMapping(out MappingFields oldObjToDel)
{
MappingFields mappingObject = GetMappingLabelObject(textbox.Name);
oldObjToDel = mappingObject;
isAdded = UpdateReferance( mappingObject);
}
internal class MappingFields
{
public string Type { get; set; }
public string Property1 { get; set; }
public string Property2 { get; set; }
public bool isFound { get; set; }
}
Upvotes: 0
Views: 240
Reputation: 5369
You could use AutoMapper to create a clone of the original object easily. I guess this post could give some idea on how to do it. You could also check AutoMapper getting started page.
Hope I helped!
Upvotes: 1
Reputation: 437376
There is no way to do this automatically in the general case. You need to make a copy (clone) of the object, which would be independent of its "source".
If your object only has scalar fields then you can utilize object.MemberwiseClone
; otherwise, you should consider implementing ICloneable
and supply an implementation of Clone
with appropriate semantics. The documentation for MemberwiseClone
also lists several alternatives:
There are numerous ways to implement a deep copy operation if the shallow copy operation performed by the MemberwiseClone method does not meet your needs. These include the following:
- Call a class constructor of the object to be copied to create a second object with property values taken from the first object. This assumes that the values of an object are entirely defined by its class constructor.
- Call the MemberwiseClone method to create a shallow copy of an object, and then assign new objects whose values are the same as the original object to any properties or fields whose values are reference types. The DeepCopy method in the example illustrates this approach.
- Serialize the object to be deep copied, and then restore the serialized data to a different object variable.
- Use reflection with recursion to perform the deep copy operation.
Update:
Since your implementation of MappingFields
only uses string and boolean fields, MemberwiseClone
will do the job. First expose a Clone
method:
internal class MappingFields : ICloneable
{
public string Type { get; set; }
public string Property1 { get; set; }
public string Property2 { get; set; }
public bool isFound { get; set; }
public object Clone()
{
return this.MemberwiseClone();
}
}
and then call it:
oldObjToDel = (MappingFields)mappingObject.Clone();
Upvotes: 3