Chris Chris - 7 months ago 39 Question

VB net copying classes and changing values

I have a class defined, with many values defined in it. I want to make a copy of it and then change 1 variable. However when I do this it also changes the variable in my original class.

The code I'm using is shown below. Any ideas what I'm doing wrong?

Dim NewClass As MyClass = PreviousClass(i)
NewClass.Value1 = NewVal


This looks to be because when you Dim your NewClass object, this is simply creating another reference to the PreviousClass object. The variable names NewClass and PreviousClass therefore refer to exactly the same object, which is why NewClass.Value1 = NewVal also affects PreviousClass.

As JaydipJ suggests, you may need a deep copy of the object, these two answers look they might be useful for you -

Create a “clone” of this object, not point to it

copy one object to another