[Resolved] - Duplicate Int[]
I want to duplicate an array of int[] into another one.
(If the array is NULL, then have the new array be NULL, if it contain X elements, then have the new array contain X elements also)
Is there a build in function to do that?
I've try copyTo and Clone without success.
Thks
Re: [Resolved] - Duplicate Int[]
Why would you not just use CopyTo? Just create another array of the same length and type and then call:
Code:
arr1.CopyTo(arr2, 0)
Re: [Resolved] - Duplicate Int[]
That's the problem, I don't know in advance what will be the size of the source array. And it could be a null one. So using myArray.Length to create a new array could end up with an error.
Re: [Resolved] - Duplicate Int[]
Code:
int[] arr1;
int[] arr2;
if (arr1 == null)
{
arr2 = null;
}
else
{
arr2 = Array.CreatInstance(typeOf(Int32), arr1.Length);
arr1.CopyTo(arr2, 0);
}
Re: [Resolved] - Duplicate Int[]
And if I was to use if to detect the presence of null array each time I need to copy an array it would be a very unbeautiful code. Now I have only one line of code to copy an entire array. Not quite rapid but it doesn't matter for this kind of project.
Re: [Resolved] - Duplicate Int[]
Aahahha you post what I was writing to avoid at that time!
That's definitely what I don't want. I must copy quite a few array. I want also to reduce redundancy of my code.
Re: [Resolved] - Duplicate Int[]
OK I missed that bit earlier, but you should still use that code or something similar in a function of your own that you can then call from anywhere.
Re: [Resolved] - Duplicate Int[]
I guess the copyTo don't create the array, it must already be created. I prefer using built-in code which often result in a more efficient, more beautiful and a less error prone code.
Quote:
Aahahha you post what I was writing to avoid at that time!
Just a coincidence that both of use wrote a reply at the same time and not knowing that the other was doing the same. This remind me kind of bug you can have with a dabatase ehhehe
Re: [Resolved] - Duplicate Int[]
Well, there is also the Clone method, but that's an instance member so you can't use it if your original array is a null reference. You could do this though I guess:
Code:
int[] newArray = (oldArray == null ? null : oldArray.Clone());
Re: [Resolved] - Duplicate Int[]
Yes it's becoming more and more elegant :)
I didn't though of that one, pretty nice
Quote:
int[] newArray = (oldArray == null ? null : oldArray.Clone());
Re: [Resolved] - Duplicate Int[]
You would probably have to cast the return value of Clone as int[] also.