2

I am new to C#, and I want to copy the value of one property to another. The following is the sample code I wrote:

public class MyObject
{
    private MyObject()
    {
       intArray = new int[3]{1,2,3}
       int1 = 1;
       SaveCopy();
    }

    private void SaveCopy()
    {
       intArray_Copy = intArray;
       int1_Copy = int1;
    }

    public int[] intArray { get; set; }
    public int int1 { get; set; }
    public int[] intArray_Copy { get; set; }
    public int int1_Copy { get; set; }
}

I am writing a SaveCopy() function to save the value of intArray and int1. I understand that using "=" makes a reference to the original property, once the value of the original property changes, the copy will also change. How do I make a copy that is different from the original property?

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
JJChow
  • 23
  • 4
  • Does your code work? In C# you should use type of variable when declaring them. Also read MSDN documentation. If you copy number you copy the value just by the assign. – PatNowak Dec 03 '15 at 10:07

1 Answers1

6

Once the value of the original property changes, the copy will also change

That is the case when talking about reference types. For example, int, which is a value type, will create a copy of itself on assignment to a new variable.

When dealing with various reference types other than array, for example, one will need to implement a "deep clone" mechanism. There is a great question which describes how to do that on SO: Deep cloning objects

For your int[], you can use Array.Copy:

public void Copy()
{
    Array.Copy(sourceArray, destArray, sourceArray.Length);
}
Community
  • 1
  • 1
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
  • Also to note, as far as I'm aware, for regular objects, there is no built-in functionality to do a deep copy, you'd need a library for that (correct me if I'm wrong?) – Rob Dec 03 '15 at 10:07
  • @Rob Yes, there is no deep copying OOTB for reference types. You'll have to implement it yourself / use a thirdparty. – Yuval Itzchakov Dec 03 '15 at 10:08