1

The microsoft docs show that C#'s Array.Clone() method returns type object:

public object Clone ();

and indeed the example they give includes a cast.

eg

int[] myClone1 =        (new int[2]).Clone();   // Type error
int[] myClone2 = (int[])(new int[2]).Clone();   // All good

Why does Clone() return object instead of the expected type ?

4
  • 8
    Because the method predates generics and returns an object, simple as that really. You can achieve the same with ToArray() which will not need to be cast Commented Jan 27, 2021 at 1:20
  • that was fast! that sounds plausible. thanks. cheers for the ToArray() tip as well, I'd missed that. Commented Jan 27, 2021 at 1:22
  • 2
    Also this method works on an array with any dimensions, which are a little trickier to deal with (for historical reason) Commented Jan 27, 2021 at 1:25
  • 2
    including arrays with non-zero bounds :) (stackoverflow.com/questions/56446/net-arrays-with-lower-bound-0) Commented Jan 27, 2021 at 1:26

3 Answers 3

0

Because .Clone() returns an object not an int. Therefore it needs a cast to be of type int.

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

2 Comments

My real question is why the language is designed so that Clone() returns object rather than (in this case) int[].
I honestly have no idea.
0

.Clone() is an implementation of ICloneable.Clone, then it must return an Object. Microsoft docs mentioned refer to it in "Implements".

Comments

0

A shallow copy of an Array copies only the elements of the Array, whether they are reference types or value types, but it does not copy the objects that the references refer to. The references in the new Array point to the same objects that the references in the original Array point to.

In contrast, a deep copy of an Array copies the elements and everything directly or indirectly referenced by the elements.

The clone is of the same Type as the original Array.

int[] array = new int[2] { 12, 13 };
int[] arrClone = (int[])array.Clone();

//or
object arrClone1 = array.Clone();

//or
object arrClone2 = array;
foreach(var item in (IEnumerable<int>)arrClone2)
{
    int x = item;
}

2 Comments

Thanks. My question is not about deep vs. shallow copies. It's about why the language is designed such that the return type of Clone() is awkward.
see this link:c-sharpcorner.com/interview-question/…. This link provides a comprehensive explanation that was very useful to me.

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.