locked
make a duplicate of an object instance RRS feed

  • Question

  • User-1055821083 posted

    I am trying to make a duplicate of b. But when I do a=b, changing a's properties changes b's. How can I make a duplicate copy of b? Thanks in advance.

    Dim
    a As New Test1

    Dim b As New Test1

    Response.Write("a=" & a.Name) 'a= something

    Response.Write("b=" & b.Name) 'b=something

    a = b

    a.Name = "Nothing"

    Response.Write("a=" & a.Name) 'a=nothing

    Response.Write("b=" & b.Name) 'b=nothing

    Thursday, December 11, 2008 1:20 PM

Answers

  • User1439985827 posted

    For the case of a string, you need to call the Copy() method:

    http://msdn.microsoft.com/en-us/library/system.string.copy.aspx

    Not all objects support this though.

    There is no universal way to do it in .NET, however some people use hacks like serializing and deserializing it again like in this article: http://www.codeproject.com/KB/cs/CloneManager.aspx

    Some objects implement the interface IClonable, which when calling "Clone" will either produce a shallow or deep copy of the instance.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, December 11, 2008 1:40 PM

All replies

  • User1439985827 posted

    For the case of a string, you need to call the Copy() method:

    http://msdn.microsoft.com/en-us/library/system.string.copy.aspx

    Not all objects support this though.

    There is no universal way to do it in .NET, however some people use hacks like serializing and deserializing it again like in this article: http://www.codeproject.com/KB/cs/CloneManager.aspx

    Some objects implement the interface IClonable, which when calling "Clone" will either produce a shallow or deep copy of the instance.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, December 11, 2008 1:40 PM
  • User-990694832 posted

    Another way to acomplish this is to use a function or sub and pass a by value and b by reference setting b = a in the function.

    Hope this helps

    DK

    Friday, December 12, 2008 8:43 AM