Search code examples
c#referenceclone

C# Reset a property


I'm writing a Clone function for a non serializeable object.For most objects I don't care if they are shallow copied as I won't be making any changes to them.

I start with a MemberwiseClone and this copies all the values and few objects like configuration dictionary over just fine but they are pointers.

EAVEntity newClone = (EAVEntity) this.MemberwiseClone();
newClone.EntityStorageID = Guid.NewGuid();
newClone.Controls.Clear();

So how do I reset a pointer so I can make them not point at the same location?


Solution

  • To be precise, you are not working with "pointers" in their true sense but rather with objects that are reference types. Quite a difference.

    If you want the property of your copied object not to point to the same other object, you could either set it to null, a new or any other object for that matter:

    newClone.SomeProperty = null;
    
    newClone.SomeProperty = new WhatEverTypeSomePropertyIs();