473,399 Members | 3,302 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,399 software developers and data experts.

copy by reference VS copy by value

Ugh....

All classes are copy by reference, even if you use "ByVal" and NOT "ByRef"
it's still a copy by reference.
Of course, as a consequence, if you change any values of the object you
passed in, the original object is affected.
I expect this with arrays, but not with single objects being passed "ByVal"
to functions....

Is there a sane to get "ByVal" passing of parameters? (copying fields is not
so hot an idea, since they too may be class objects)
Nov 20 '05 #1
2 2659
In article <u7**************@TK2MSFTNGP11.phx.gbl>, Martin Ortiz wrote:
Ugh....

All classes are copy by reference, even if you use "ByVal" and NOT "ByRef"
it's still a copy by reference.
Of course, as a consequence, if you change any values of the object you
passed in, the original object is affected.
I expect this with arrays, but not with single objects being passed "ByVal"
to functions....

Is there a sane to get "ByVal" passing of parameters? (copying fields is not
so hot an idea, since they too may be class objects)


This is the same bahavior that existed in VB.CLASSIC as well. Objects
variables are not objects, but references to memory located on the heap.
When you pass an object ByVal, your passing it's address by value not
the object. That means that the callee can not change the reference,
but the certainly can change the values of it's properties.

Anyway, here is a little demo of a possible solution for you:

Option Strict On
Option Explicit On

Imports System.IO
Imports System.Collections
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.Binary

Module Module1

Sub Main()
Dim cm1 As New CloneMe

cm1.I = 5
cm1.S = "Bob"
cm1.List.Add(New Child(1))
cm1.List.Add(New Child(200))

Console.WriteLine("cm1.I = {0}", cm1.I)
Console.WriteLine("cm1.S = {0}", cm1.S)

Console.WriteLine("Children In List:")
For Each c As Child In cm1.List
Console.WriteLine("{0}{1}", vbTab, c.X)
Next

Console.WriteLine("cm1.Child.X = {0}", cm1.Child.X)

Console.WriteLine("============== Creating Clone =============")
Dim cm2 As CloneMe = DirectCast(cm1.Clone, CloneMe)

Console.WriteLine("cm2.I = {0}", cm2.I)
Console.WriteLine("cm2.S = {0}", cm2.S)

Console.WriteLine("Children In List:")
For Each c As Child In cm2.List
Console.WriteLine("{0}{1}", vbTab, c.X)
Next

Console.WriteLine("cm2.Child.X = {0}", cm2.Child.X)

Console.WriteLine("================= Prove that it's a clone
============")
cm2.I = 40
cm2.S = "Susan"
cm2.List.Clear()
cm2.List.Add(New Child(1000))
cm2.Child = New Child(25)

Console.WriteLine("cm1.I = {0}", cm1.I)
Console.WriteLine("cm1.S = {0}", cm1.S)

Console.WriteLine("Children In List:")
For Each c As Child In cm1.List
Console.WriteLine("{0}{1}", vbTab, c.X)
Next

Console.WriteLine("cm1.Child.X = {0}", cm1.Child.X)

Console.WriteLine()
Console.WriteLine("cm2.I = {0}", cm2.I)
Console.WriteLine("cm2.S = {0}", cm2.S)

Console.WriteLine("Children In List:")
For Each c As Child In cm2.List
Console.WriteLine("{0}{1}", vbTab, c.X)
Next

Console.WriteLine("cm2.Child.X = {0}", cm2.Child.X)
End Sub

<Serializable()> _
Private Class CloneMe
Implements ICloneable

Private m_i As Integer
Private m_s As String
Private m_a As ArrayList
Private m_c As Child

Public Sub New()
Me.m_a = New ArrayList
Me.m_c = New Child(5)
End Sub

Public Property I() As Integer
Get
Return Me.m_i
End Get
Set(ByVal Value As Integer)
Me.m_i = Value
End Set
End Property

Public Property S() As String
Get
Return Me.m_s
End Get
Set(ByVal Value As String)
Me.m_s = Value
End Set
End Property

Public ReadOnly Property List() As ArrayList
Get
Return Me.m_a
End Get
End Property

Public Property Child() As Child
Get
Return Me.m_c
End Get
Set(ByVal Value As Child)
Me.m_c = Value
End Set
End Property

Public Function Clone() As Object Implements
System.ICloneable.Clone
Dim bf As New BinaryFormatter
Dim ms As New MemoryStream
Dim nc As CloneMe

bf.Serialize(ms, Me)
ms.Seek(0, SeekOrigin.Begin)
nc = DirectCast(bf.Deserialize(ms), CloneMe)
ms.Close()

Return nc
End Function
End Class

<Serializable()> _
Private Class Child
Private m_x As Integer

Public Sub New(ByVal x As Integer)
Me.m_x = x
End Sub

Public ReadOnly Property X() As Integer
Get
Return Me.m_x
End Get
End Property
End Class
End Module

Now, this is pretty sloppy since I threw it together - but it does what
you want. It creates a deep copy of your object. The gotchas are that
all members have to be serializable or you end up just implmenting the
ISerializable interfact manually. And that leads to the memeber by
member copy.

But you can use this method to create a temporary object to be passed to
routines you don't want to modify your object.

--
Tom Shelton
MVP [Visual Basic]
Nov 20 '05 #2
Hi Martin,

Tom's shown you how to do the deep copy which will copy objects referred
to by the object being passed. If you <know> that there aren't any, or that
these members won't be touched, you create a copy using MemberwiseClose and
pass that instead.

Foo (oMan.MemberwiseClone)
'Needs casting if Option Strict is on.

Another way would be to implement the class with a flag which sets it
read-only.

Lol. There are more ideas but they're getting wackier. ;-)

Regards,
Fergus
Nov 20 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

42
by: Edward Diener | last post by:
Coming from the C++ world I can not understand the reason why copy constructors are not used in the .NET framework. A copy constructor creates an object from a copy of another object of the same...
5
by: I wish | last post by:
I wrote some program #include <iostream> class A { public: A() {} A( const A& t ) { std::cout << "Good" << std::endl; } }; A f()
5
by: Tony Johansson | last post by:
Hello! I'm reading in a book about C++ and that is something that sound strange. It says "Pointers have reference-assignment semantics similar to those in Java. For example, after the...
12
by: Andrew Schepler | last post by:
When compiled with Visual C++ .NET 2003 (only), the program below aborts as though no matching catch clause is present. If the copy constructor of A is made public, it successfully catches the...
1
by: blangela | last post by:
3.0 Advanced Topic Addendum There are a few cases where the C++ compiler cannot provide an overloaded assignment operator for your class. If your class contains a const member or/and a...
10
by: JurgenvonOerthel | last post by:
Consider the classes Base, Derived1 and Derived2. Both Derived1 and Derived2 derive publicly from Base. Given a 'const Base &input' I want to initialize a 'const Derived1 &output'. If the...
6
by: Tim Zych | last post by:
' Declare a new parameter object Dim param() As SqlParameter = New SqlParameter(0) {} ' Set this to null and make it an InputOutput parameter param(0) = New SqlParameter("@Something, DBNull.Value)...
22
by: clicwar | last post by:
A simple program with operator overloading and copy constructor: #include <iostream> #include <string> using namespace std; class Vector { private: float x,y; public: Vector(float u, float...
6
by: Peng Yu | last post by:
Hi, I'm wondering if the following assignment is lazy copy or not? Thanks, Peng std::vector<intv. v.push_back(1); v.push_back(2);
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.