views:

147

answers:

1

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?

A: 

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();
Johannes Rudolph
I tried that with newClone.EntityStorageID = new Guid()but it still update this.EntityStorageID. I'll try null.
Jeff
Nope null ( newClone.EntityStorageID = null;) failed to as it is a non nullable type. My solution will likely be to do the entire clone by hand (one property at a time) but I'm still curious on how I'd set an object by reference.
Jeff
If you made the GUID a type of GUID? (Nullable<GUID> in VB), this will allow you to pass null. GUID is a value type, whereas nullable types, string, and classes are reference types and will experience the issue you are talking about. So you could create a nullable class or a wrapper class that has a GUID property.
Brian
you can always use default(Type), will return 0 for ints, null for objects, etc.
Johannes Rudolph