I was going through the source code for Array.cs
when I read that Array.Copy()
does not provide a guarantee that a copy would be successful and infact even possibly corrupting the original instance (Correct me if I am wrong here). To provide peace of mind, ConstrainedCopy ()
seems to achieve the same.
My question is:
1> Why would anyone use Array.Copy()
if it doesn't seem to guarantee a successful transfer of data and going on to possibly hurt the original instance? Infact, all collection classes seem to use Array.Copy()
to increase their instance size. Why not use ConstrainedCopy()
here
2> How much would be the cost of using ConstrainedCopy ()
all the time then? I am assuming there would be more logic added to ConstrainedCopy ()
?
Object[] objArray = { "Anakin", "Skywalker", 666 };
String[] stringArray = new String[3];
Array.Copy(objArray, stringArray , 3);
This throws an invalid cast exception. Even after the exception is thrown (if you swallow it), the first two elements of the objArray are copied to the stringArray.
Array.ConstrainedCopy(objArray, 0, stringArray, 0, 3);
This throws an System.ArrayTypeMismatchException and won't copy any elements to the destination array (stringArray).
ConstraintedCopy() does not guarantee success. The first line of the MSDN Docs states:
Copies a range of elements from an Array starting at the specified source index and pastes them to another Array starting at the specified destination index. Guarantees that all changes are undone if the copy does not succeed completely.
More specifically the second line :
Guarantees that all changes are undone if the copy does not succeed completely.
An exception can still be thrown in very extreme circumstances.However those circumstances are exceptional and you shouldn't have to worry about them in most scenarios.
In short, just stick with Array.Copy().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With