473,800 Members | 2,518 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

copying an object

Hi

prolly a simple solution...how do i make a "copy" of an existing object

eg

object obj1 = new object();
object obj2 = obj1;

if i change a property in obj2, it also changes obj1, since its a reference
correct?

how do i make a copy...?

Thanks
Jason
Nov 16 '05 #1
3 3810
"Jason" <c_*******@migh ty.co.za> wrote in
news:#h******** ******@TK2MSFTN GP09.phx.gbl:
Hi

prolly a simple solution...how do i make a "copy" of an existing
object

eg

object obj1 = new object();
object obj2 = obj1;

if i change a property in obj2, it also changes obj1, since its a
reference correct?

how do i make a copy...?


Look at ICloneable support. If the object in question doesn't implement
ICloneable, look at Object.Memberwi seCopy. If that doesn't work, build a
method to create a new object and copy over the data you need.

--
Lasse Vågsæther Karlsen
la***@vkarlsen. no
PGP KeyID: 0x0270466B
Nov 16 '05 #2
Hi,
There is no built in copy function in .NET objects. There we have a object.Clone() method that creates another object with the same properties and state of the original one, but if the original class has some reference to other typed objects
the object.Clone() method does not create new sub objects for the new clone. It just passes references to the new clone. If what Lasse tells do not work try this..

If you have a base class everything is easy but you should add some
code to all of your inherited classes;
1. Add the code below to your base class:
using System.Runtime. Serialization;
using System.Runtime. Serialization.F ormatters.Binar y;
2. Add attribute to base and all of your inherited classes:
[Serializable]
public class MyBase
{...}
[Serializable]
public class MyChildClass01
{...}
[Serializable]
public class MyChildClass02
{...}
3.In your base class add the function below:
[Serializable]
public class MyBase
{
....

public MyBase GetACopy()
{
MyBase retval = null;
IFormatter formatter = new BinaryFormatter ();
Stream stream = new System.IO.Memor yStream();
formatter.Seria lize(stream, this);
stream.Seek(0,S ystem.IO.SeekOr igin.Begin);
retval = ((MyBase)(forma tter.Deserializ e(stream)));
return retval;
}
}

4. Use the GetACopy() function by casting
public class UserClass
{
public void SampleMethod()
{
//Create Original
MyChildClass01 chOriginal = new MyChildClass01( );

//Set Properties of Original Class
chOriginal.Name = "Original" ... etc.

//Create A Copy
MyChildClass01 chCopy = (MyChildClass01 ) (chOriginal.Get ACopy());
}
}

5. You should write property accessors for all the variables in your
inherited class to be copied exactly.

6. Only the serializable sub classes will be copied; this may be a
DataSet for instance; it implements ISerializable interface

Good Luck,
-------
Dincer Ozturan
"Jason" wrote:
Hi

prolly a simple solution...how do i make a "copy" of an existing object

eg

object obj1 = new object();
object obj2 = obj1;

if i change a property in obj2, it also changes obj1, since its a reference
correct?

how do i make a copy...?

Thanks
Jason

Nov 16 '05 #3
Hi,
There is no built in copy function in .NET objects. There we have a object.Clone() method that creates another object with the same properties and state of the original one, but if the original class has some reference to other typed objects
the object.Clone() method does not create new sub objects for the new clone. It just passes references to the new clone. If what Lasse tells do not work try this..

If you have a base class everything is easy but you should add some
code to all of your inherited classes;
1. Add the code below to your base class:
using System.Runtime. Serialization;
using System.Runtime. Serialization.F ormatters.Binar y;
2. Add attribute to base and all of your inherited classes:
[Serializable]
public class MyBase
{...}
[Serializable]
public class MyChildClass01
{...}
[Serializable]
public class MyChildClass02
{...}
3.In your base class add the function below:
[Serializable]
public class MyBase
{
....

public MyBase GetACopy()
{
MyBase retval = null;
IFormatter formatter = new BinaryFormatter ();
Stream stream = new System.IO.Memor yStream();
formatter.Seria lize(stream, this);
stream.Seek(0,S ystem.IO.SeekOr igin.Begin);
retval = ((MyBase)(forma tter.Deserializ e(stream)));
return retval;
}
}

4. Use the GetACopy() function by casting
public class UserClass
{
public void SampleMethod()
{
//Create Original
MyChildClass01 chOriginal = new MyChildClass01( );

//Set Properties of Original Class
chOriginal.Name = "Original" ... etc.

//Create A Copy
MyChildClass01 chCopy = (MyChildClass01 ) (chOriginal.Get ACopy());
}
}

5. You should write property accessors for all the variables in your
inherited class to be copied exactly.

6. Only the serializable sub classes will be copied; this may be a
DataSet for instance; it implements ISerializable interface

Good Luck,
-------
Dincer Ozturan
"Jason" wrote:
Hi

prolly a simple solution...how do i make a "copy" of an existing object

eg

object obj1 = new object();
object obj2 = obj1;

if i change a property in obj2, it also changes obj1, since its a reference
correct?

how do i make a copy...?

Thanks
Jason

Nov 16 '05 #4

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

Similar topics

3
3657
by: Robert Tarantino | last post by:
Hello, I am trying to find a way to create a scheduled task or service that will copy my local profile folders under "Documents and settings" to a network drive. This would allow me to restore my settings if my profile became tampered with or corrupt. Is there any sample code available out there? -Robert
2
1833
by: Marijn | last post by:
Say i have an object that represents or holds a resource like an open file, a block of memory on the heap, or an openGL texture object. The constructor acquires the resource, and the destructor releases it. I want to implement efficient copying and assignment for this object - the copy constructor passes on the 'handle' (file pointer, memory pointer, or opengl texture id) to the new object, and invalidates the old object. I guess this is...
21
3942
by: Matteo Settenvini | last post by:
Ok, I'm quite a newbie, so this question may appear silly. I'm using g++ 3.3.x. I had been taught that an array isn't a lot different from a pointer (in fact you can use the pointer arithmetics to "browse" it). So I expected that when I run this program, I get both c1.A and c2.A pointing to the same address, and changing c1.A means that also c2.A changes too. ----- BEGIN example CODE -----------
22
6969
by: Matt | last post by:
When browsing a web page a user has the ability to highlight content on a page (by holding down the left mouse button and dragging the mouse over the desired content). Is there a way to disable this option? I assume there isn't but I have to try.
5
17657
by: Roy Hills | last post by:
When I'm reading from or writing to a network socket, I want to use a struct to represent the structured data, but must use an unsigned char buffer for the call to sendto() or recvfrom(). I have two questions: 1. Is it generally safe to "overlay" the structure on the buffer, e.g.: unsigned char buffer;
5
3120
by: Steve - DND | last post by:
Is there any way to easily deep copy an entire object? Maybe something with unsafe code to make a full and completely duplicated copy of an object with no reference ties to the original? I want everything copied, public, private, internal, events, etc... Thanks, Steve
6
2566
by: solex | last post by:
Hello, I am trying to use serialization to copy objects. The object in question "Institution" inherits from a parent object "Party" both are marked as <Serializable()>. Initially I can copy an empty Institution to another empty Institution, using the following routine: Private Sub CopyObject(ByRef FromObject As Object, ByRef ToObject As Object) Dim m As New MemoryStream Dim b As New BinaryFormatter
1
2353
by: chris.atlee | last post by:
I'm writing a program in python that creates tar files of a certain maximum size (to fit onto CD/DVD). One of the problems I'm running into is that when using compression, it's pretty much impossible to determine if a file, once added to an archive, will cause the archive size to exceed the maximum size. I believe that to do this properly, you need to copy the state of tar file (basically the current file offset as well as the state of...
6
4997
by: kimiraikkonen | last post by:
Hi, I use system.io.file class to copy files but i have a difficulty about implementing a basic / XP-like progress bar indicator during copying process. My code is this with no progress bar, or i couldn't find sth which give totalbytes/written bytes class. And does system.io.file class provide awaring of the chunks / bytes of the files bytes which are written?
2
2818
by: raylopez99 | last post by:
Beware newbies: I spent a day before I figured this out: copying a bitmap (image) file to file is not quite like copying a text file--you have to do some tricks (see below), like using a "Graphics" object to wrap around the image (!). It's not so simple as shown in most examples (where they have a simple image file and hard copy it into a harddrive along the lines of : image.Save(@"C:\\temp\\myimage.pgn"); That will work, but it's a...
0
9690
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9550
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10501
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...
1
10250
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
9085
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...
1
7574
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5603
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4149
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
3764
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.