DEV Community

loading...

Copying array of Objects is not that straightforward

iamdoctorj profile image Jyotirmaya Sahu ・2 min read

So, you want to copy an array to create another new array, and not just copying the array reference to another variable. In C#, there are several ways to achieve this.
Some of the ways are:

  • Array.CopyTo()
  • Array.ConstrainedCopy()
  • Array.Clone()

These ways provide you with a new array that is different from the original array and not just two variables with the same reference.

But, any object when created, is created in the heap and it's address is assigned to the reference variable.

For example:
Student s1 = new Student()

Here, new Student() is the creation of an Student object in the heap, and s1 holds its address.

Same happens in an array. An array of objects or any complex type consists of reference variables holding the addresses of the actual objects present in the heap.

Alt Text

As, we can see from the image, we can now understand that when we copy a similar array, we end up with a new array but with the elements holding addresses, or references to the same objects.

Now, if we want a new set of objects with the same data, we may need to recreate the objects linearly. We can use the Array.ConvertAll() method for that purpose.

Refer to this article by Peter Mbanugo for more details on the methods mentioned in this article.

Note: This only applies to array of complex types. Array of primitive types will contain values as opposed to complex types which have references. So copying an array of primitive types will have no issues to deal with.

Discussion (0)

pic
Editor guide