473,659 Members | 2,526 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to NOT reference the same object??

Hi All,
Just got started in C#...

Here's some C# code:

public MyClass

{

private MyThingy m_Thingy;

public SetThingy(MyThi ngy thingy)

{

m_Thingy = thingy;

}

}

I just found out that MyClass.m_Thing y will actually be referencing the same
MyThingy object that the caller passed in. Similar code in C++ would have
invoked the implied = operator and just copied the contents giving me a
separate, independent object with values initialized to what the passed in
object has. This is what I need, but I don't know how to make C# do the
same. How is this accomplished in C#?? I could always write a Copy
Constructor for MyThingy and do m_Thingy = new MyThingy(thingy ) but I was
hoping there was another way so I don't have to write the copy constructor
in cases like this.

Thanks for any help,

Wayne


Nov 15 '05 #1
6 1466
WayneD wrote:
Thanks for any help,


You might consider implementing the ICloneable interface in your
MyThingy class. Then you can create a copy like so:

MyThingy newThingy = oldThingy.Clone ();

If your class has any member variables that are themselves reference
types, you'll need to make sure you copy those objects as well or
they'll be referenced by both instances.

--
There are 10 kinds of people. Those who understand binary and those who
don't.

http://code.acadx.com
(Pull the pin to reply)
Nov 15 '05 #2
You can create a shallow copy this way:

class MyThingy
{
...
public MyThingy Copy()
{
return (MyThingy)this. MemberwiseClone ();
}
}

"WayneD" <Wa***@Wayconso ftware.com> wrote in message
news:OQ******** *****@TK2MSFTNG P10.phx.gbl...
Hi All,
Just got started in C#...

Here's some C# code:

public MyClass

{

private MyThingy m_Thingy;

public SetThingy(MyThi ngy thingy)

{

m_Thingy = thingy;

}

}

I just found out that MyClass.m_Thing y will actually be referencing the same MyThingy object that the caller passed in. Similar code in C++ would have
invoked the implied = operator and just copied the contents giving me a
separate, independent object with values initialized to what the passed in
object has. This is what I need, but I don't know how to make C# do the
same. How is this accomplished in C#?? I could always write a Copy
Constructor for MyThingy and do m_Thingy = new MyThingy(thingy ) but I was
hoping there was another way so I don't have to write the copy constructor
in cases like this.

Thanks for any help,

Wayne

Nov 15 '05 #3
Chris R wrote:
You can create a shallow copy this way:


A shallow copy leads to exactly the same issue: reference types in both
copies point to the same objects.

--
There are 10 kinds of people. Those who understand binary and those who
don't.

http://code.acadx.com
(Pull the pin to reply)
Nov 15 '05 #4
A shallow copy creates a new instance of the same type as the original
object, and then copies the nonstatic fields of the original object. If the
field is a value type, a bit-by-bit copy of the field is performed. If the
field is a reference type, the reference is copied but the referred object
is not; therefore, the reference in the original object and the reference in
the clone point to the same object. In contrast, a deep copy of an object
duplicates everything directly or indirectly referenced by the fields in the
object.
A shallow copy leads to exactly the same issue: reference types in both
copies point to the same objects.
He didn't indicate whether the fields would be reference types. I would
consider this "an issue", but "exactly the same issue"; the original
poster's problem was with regard to the host object itself referencing the
same object, and in the case of a shallow clone that is not the situation.

Jon
"Frank Oquendo" <fr*******@acad x.com> wrote in message
news:ep******** ******@TK2MSFTN GP10.phx.gbl... Chris R wrote:
You can create a shallow copy this way:


A shallow copy leads to exactly the same issue: reference types in both
copies point to the same objects.

--
There are 10 kinds of people. Those who understand binary and those who
don't.

http://code.acadx.com
(Pull the pin to reply)

Nov 15 '05 #5
People have covered the other issues. A quick and cheap way to clone an
entire class' object graph would be to serialize the object and deserialize
it back into an instance. So long as every referred-to object is
serializable, you will get a true deep copy.

If you just want a shallow copy you can do the MemberwiseClone () as
previously suggested, or if value semantics are more appropriate for your
"MyThingy" type, you can define it instead as a struct, which will make a
copy (shallow) on assignment.

Richard

--
Veuillez m'excuser, mon Français est très pauvre. Cependant, si vous voyez
mauvais C #, c'est mon défaut!
"WayneD" <Wa***@Wayconso ftware.com> wrote in message
news:OQ******** *****@TK2MSFTNG P10.phx.gbl...
Hi All,
Just got started in C#...

Here's some C# code:

public MyClass

{

private MyThingy m_Thingy;

public SetThingy(MyThi ngy thingy)

{

m_Thingy = thingy;

}

}

I just found out that MyClass.m_Thing y will actually be referencing the same MyThingy object that the caller passed in. Similar code in C++ would have
invoked the implied = operator and just copied the contents giving me a
separate, independent object with values initialized to what the passed in
object has. This is what I need, but I don't know how to make C# do the
same. How is this accomplished in C#?? I could always write a Copy
Constructor for MyThingy and do m_Thingy = new MyThingy(thingy ) but I was
hoping there was another way so I don't have to write the copy constructor
in cases like this.

Thanks for any help,

Wayne

Nov 15 '05 #6
Just for the record, a shallow copy using MemberwiseClone will behave
identically to functionality that the default operator= will in C++. A
referenced object in the original object will also be referenced in the
copied object. So, if different behavior is desired, a method would need to
be created for either C# or for C++.

Thus, the original poster's question is answered as far as it went.

Chris R.

"Frank Oquendo" <fr*******@acad x.com> wrote in message
news:ep******** ******@TK2MSFTN GP10.phx.gbl...
Chris R wrote:
You can create a shallow copy this way:


A shallow copy leads to exactly the same issue: reference types in both
copies point to the same objects.

--
There are 10 kinds of people. Those who understand binary and those who
don't.

http://code.acadx.com
(Pull the pin to reply)

Nov 15 '05 #7

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

Similar topics

5
9488
by: Jan Pieter Kunst | last post by:
(apologies if this message is a duplicate -- my news server seems to have problems) Greetings, When using PHP 4, this: // ex. 1 class A { function A(&$obj) {
6
2250
by: Chris S. | last post by:
I'm trying to make a graphical editor and browser for Pickled files. One aspect I'm not sure about is how to detect multiple references to the same data. For instance, say I had the Pickled data: a= b= c= d=
4
3400
by: z_learning_tester | last post by:
I'm reading the MS press C# book and there seems to be a contradiction. Please tell me which one is correct, 1 or 2. Thanks! Jeff 1. First it gives the code below saying that it prints 0 then 42. They say that 42 is printed the second time since the value was wrapped in a class and therefore became passed by reference. (sorry for any typos I am a newbie here ;-)
3
4212
by: Adam | last post by:
We have a web site that uses .vb for the web pages and .cs for a class module. We are getting the error in .NET 2.0 and VS 2005 beta 2. It does work with .NET 1.1. When trying to access a page that needs the class module I get an error on web site: Object reference not set to an instance of an object Here is where the error is:
12
2677
by: Andrew Bullock | last post by:
Hi, I have two classes, A and B, B takes an A as an argument in its constructor: A a1 = new A(); B b = new B(a1);
51
4434
by: Kuku | last post by:
What is the difference between a reference and a pointer?
8
2396
by: toton | last post by:
HI, One more small doubt from today's mail. I have certain function which returns a pointer (sometimes a const pointer from a const member function). And certain member function needs reference (or better a const reference). for eg, const PointRange* points = cc.points(ptAligned);
68
4600
by: Jim Langston | last post by:
I remember there was a thread a while back that was talking about using the return value of a function as a reference where I had thought the reference would become invalidated because it was a temporary but it was stated that it would not. This has come up in an irc channel but I can not find the original thread, nor can I get any code to work. Foo& Bar( int Val ) { return Foo( Val ); }
275
12247
by: Astley Le Jasper | last post by:
Sorry for the numpty question ... How do you find the reference name of an object? So if i have this bob = modulename.objectname() how do i find that the name is 'bob'
0
8851
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8751
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8539
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8630
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7360
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5650
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4342
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2759
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1739
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.