Array.Copy and Array.ConstrainedCopy - C #

I read the source code for Array.cs when I read that Array.Copy() does not guarantee that the copy will succeed and may even damage the original instance (correct me if I am wrong here). To ensure peace of mind, ConstrainedCopy () seems to achieve the same.

My question is:
1> Why would someone use Array.Copy() if it doesn’t seem to guarantee a successful data transfer and possibly damage the original instance? Infact, all collection classes use Array.Copy() to increase the size of their instance. Why not use ConstrainedCopy() here

2> How much will it cost to use ConstrainedCopy () all the time? I assume that more logic will be added to ConstrainedCopy () ?

+6
source share
3 answers

ConstraintedCopy () does not guarantee success. The first line of the MSDN document says:

Copies a series of elements from an array, starting at the specified source index, and pastes them into another array, starting at the specified target index. Ensures that all changes are undone if the copy fails completely.

In particular, the second line:

Ensures that all changes are undone if the copy fails completely.

An exception can still be thrown in very extreme circumstances. However, these circumstances are exceptional and you do not need to worry about them in most scenarios.

In short, just stick with Array.Copy ().

+4
source
 Object[] objArray = { "Anakin", "Skywalker", 666 }; String[] stringArray = new String[3]; 
  • Array.Copy(objArray, stringArray , 3);

    This throws an invalid exception. Even after the exception (if you swallow it), the first two objArray elements are copied to stringArray.

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

    This throws a System.ArrayTypeMismatchException exception and will not copy any elements to the target array (stringArray).

+15
source

See this question: C # is the fastest way to change an array

ConstrainedCopy is a bit slower but not significantly

+1
source

Source: https://habr.com/ru/post/895554/


All Articles