开发者

Array.Copy and Array.ConstrainedCopy - C#

开发者 https://www.devze.com 2023-03-29 13:06 出处:网络
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 (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 开发者_JAVA百科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];
  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).


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


See this question: C# quickest way to shift array

ConstrainedCopy is slightly slower, but not significantly

0

精彩评论

暂无评论...
验证码 换一张
取 消