I am attempting to copy a number of arrays in c# using the Array.Copy() method. This method is supposed to automatically type-convert, however I am wondering if it will convert user-defined types if I were to define a constructor like so:
OldType(){
int param1;
String param2;
}
NewType(OldType old){
setParam1(old.param1);
setParam2(old.param2);
}
OldType oldArray[];
NewType newArray[];
//will this automatically convert???
Array.Copy(oldArray, newArray);
This is for use in converting from a legacy object to a new object. The content is exactly the same, the names are just different.
There’s an easy way to make this conversion without leaving yourself or anybody reading your code in doubt: use LINQ.
As the documentation here (pointed out by M.Babcock in the comments) says,
Array.Copyis an O(n) operation. Likewise, the LINQ code I wrote above is an O(n) operation, so there is no asymptotic performance hit (actual performance in wall clock time is dependent on a host of factors, so I can’t compare the runtime of the two solutions without profiling) and you know that this code is correct.Also from the MSDN docs:
So no, Array.Copy won’t “automatically convert” i.e. actually create new objects of type
NewTypeduring the copy, but will simply copy references to the objects of typeOldTypeand put those references innewArray.