Saturday, May 7, 2011

Cloning objects in C# to achieve pseudo byval with ICloneable

I came across this little nugget recently and while the ability to do this has been around for quite some time in c# I found it to be very handy and wanted to share. If you have an object (class) in C# where you’d like to clone an entire reference object to another without transferring id/hash, basically achieving a by value transfer. The approach is to use the ICloneable interface on your class. Here is my base entity class which most all entity’s in my application inherit from.

public class EntityBase : IEntityBase, ICloneable
public Guid Id { get; set; }

public EntityBase()
Id = Guid.NewGuid();

public object Clone()
return MemberwiseClone();

Take note of the Clone() method, this is a required member of using ICloneable and it brings us to the usage for the object cloning.

MyObject origObj = querySomeRepo.FindOne<MyObject>(f => f.Id == Guid.Parse(id));
MyObject newObj = (MyObject)familyOrig.Clone();

That’s it and newObj is now a clone of the original retaining all property values without being the exact same object.


No comments:

Post a Comment