Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.Copy and Array.ConstrainedCopy - C#

Tags:

arrays

c#

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 () ?

like image 253
name_masked Avatar asked Aug 22 '11 03:08

name_masked


2 Answers

Object[] objArray = { "Anakin", "Skywalker", 666 };
String[] stringArray = new String[3];
  1. 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.

  2. Array.ConstrainedCopy(objArray, 0, stringArray, 0, 3);

    This throws an System.ArrayTypeMismatchException and won't copy any elements to the destination array (stringArray).

like image 76
Apurv Avatar answered Oct 05 '22 13:10

Apurv


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().

like image 25
BentOnCoding Avatar answered Oct 05 '22 12:10

BentOnCoding