I was using list of (T) in vb.net and face an unusual problem when i add same object twice even instantiating them them under different names and if i change any value in one the other gets changed as well.
So what was the problem? actually i was copying the object which had the pointer pointing to the old object location and was changing the value as we change the value of the other.
To resolve this we need to clone the object and then we can easily play around with the new object. To clone you can create the class as IClonable
For eg:
Public Class person Implements ICloneable Public Function Clone() As Object Implements System.ICloneable.Clone Return MyBase.MemberwiseClone() End Function Private iID As Integer Public Property ID As Integer Get Return iID End Get Set(ByVal value As Integer) iID = value End Set End Property End Class ' Now outside the class you can do following to copy the object Dim per1 As New person per1.ID = 1 Dim per2 As New person per2 = per1.Clone()
So if you do per2.id = 3 then it will not change the value in per1 so that mean you have distinctly independent object to work around.
So what was the problem? actually i was copying the object which had the pointer pointing to the old object location and was changing the value as we change the value of the other.
To resolve this we need to clone the object and then we can easily play around with the new object. To clone you can create the class as IClonable
For eg:
Public Class person Implements ICloneable Public Function Clone() As Object Implements System.ICloneable.Clone Return MyBase.MemberwiseClone() End Function Private iID As Integer Public Property ID As Integer Get Return iID End Get Set(ByVal value As Integer) iID = value End Set End Property End Class ' Now outside the class you can do following to copy the object Dim per1 As New person per1.ID = 1 Dim per2 As New person per2 = per1.Clone()
So if you do per2.id = 3 then it will not change the value in per1 so that mean you have distinctly independent object to work around.
Read more!