-1

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();
4
  • 2
    I'd use .ToArray()... But really it mostly taste choice... and a bit of whether you actually need a "copy" (as the title says) or the same reference as the sample code in the post shows. Commented Sep 8, 2022 at 4:44
  • 1
    Note that your first option does not create a copy at all, but rather keep a reference to the same array from sourceObject.numbers. Commented Sep 8, 2022 at 4:51
  • @wohlstad yeah I know that, and actually I think it is not a good one... Commented Sep 8, 2022 at 4:53
  • 1
    This is not opinion-based as one option does and one doesn't actually create a copy of the data. I'd go for myObject.numbers= sourceObject.numbers.ToArray(); , too. Commented Sep 8, 2022 at 5:52

1 Answer 1

0

I would use this:

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

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.