Joy
Joy

Reputation: 73

How to copy array of an object into the array of another object in c#?

I have defined 2 classes and some objects like these:

public class MyClass
{
public int[] numbers { get; set; }
//some other properties
}

public class DemoClass
{
//some other properties
public int[] numbers { get; set; }
//some other properties
}

var myObject= new MyClass();
var sourceObject= new DemoClass{
                       numbers={1,2,3}
                       //other properties 
                      }

Now, I want to copy the array of sourceObject into the array of myObject. What is the best approach?

myObject.numbers= sourceObject.numbers;

or

myObject.numbers= (int[])sourceObject.numbers.Clone();

Upvotes: -1

Views: 500

Answers (1)

Enigmativity
Enigmativity

Reputation: 117064

I would use this:

myObject.numbers = sourceObject.numbers.ToArray();

Since sourceObject.numbers is an int[] then, under the hood, LINQ uses Array.Copy anyway.

Upvotes: 0

Related Questions