Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy C# object along with reference [duplicate]

Tags:

c#

object

Possible Duplicate:
Cloning objects in C#

I have an object created in c# say Object1. I need to temporarily back up this object to another object say ObjectOriginal.

However if I do ObjectOriginal = Object1, any changes to Object 1 affect ObjectOriginal. How do I go about this?

like image 472
Mini Avatar asked Feb 26 '10 09:02

Mini


People also ask

What is copy function C?

C strcpy() The strcpy() function copies the string pointed by source (including the null character) to the destination. The strcpy() function also returns the copied string.

What is strcpy () in C?

strcpy() is a standard library function in C/C++ and is used to copy one string to another. In C it is present in string. h header file and in C++ it is present in cstring header file. Syntax: char* strcpy(char* dest, const char* src);

Why do we need strcpy?

The strcpy() function is used to copy the source string to destination string. If the buffer size of dest string is more than src string, then copy the src string to dest string with terminating NULL character.

What does strcpy s1 s2 do?

In the C Programming Language, the strcpy function copies the string pointed to by s2 into the object pointed to by s1. It returns a pointer to the destination.


1 Answers

It all depends on what Object1 actually is, i.e. is it a DataTable, a String, or something else entirely?

By writing:

object Object1 = new Thing();
object Object2 = Object1;

You get a second reference to the object you instantiated in the first line. What you need to do is look at "Thing" and see if it has a Copy, Clone or similarly named method and use that:

object Object1 = new Thing();
object Object2 = Object1.Copy();

For example, DataTable offers both Copy and Clone methods, where Copy duplicates both the structure of the DataTable and the data and Clone only duplicates the structure.

like image 132
Rob Avatar answered Oct 15 '22 02:10

Rob