dotnet / dotnet/dotnet-api-docs
`Array.ConstrainedCopy` explanation is misleading and has incorrect exception specifications
- Dominant language
- C#
- Stars
- 949
- Forks
- 1.7k
- Avg merge
- 3d 27m
- Merged PRs (30d)
- 49
Description
### Type of issue
Other (describe below)
### Description
`Array.ConstrainedCopy` says:
> 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.
The meaning of "Guarantees that all changes are undone if the copy does not succeed completely.", if interpreted naturally, is as follows.
> It tries to do the same as `Array.Copy`, and if an exception is thrown during this copying, it undoes all the changes.
This interpretation is reasonable due to the use of present indicative in both the condition and the consequence. Moreover, it suggests two things:
1. If both arrays are primitive integral types and the representable range of the source array's element type is not larger than that for the destination, then the copy succeeds. For example, constrained-copying `int[]` into `long[]` would appear to always succeed.
2. It will use an intermediate array to avoid corrupting the destination.
Of course, the method does neither of the above. It just checks the types before starting copying. So it's not "undo changes if not succeeding completely", but "not doing any changes unless provably safe". The message exception for `ArrayTypeMismatchException` is more accurate.
Suggested rewording:
```diff
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.
+The method does not start copying unless the arrays' element types are provably
+compatible, so it guarantees the array is not modified if it throws an exception.
```
Maybe add the compatibility rules (see comments)?
---
`Array.ConstrainedCopy` is documented that it may throw `InvalidCastException`. It will never throw this exception, instead it's always the `ArrayTypeMismatchException` if the element types are not provable compatible.
`InvalidCastException` should be removed from the list of possible exceptions in `Array.ConstrainedCopy`.
---
This applies retroactively to all .NET versions since .NET Framework 2.0.
### Page URL
https://learn.microsoft.com/en-us/dotnet/api/system.array.constrainedcopy?view=net-10.0
### Content source URL
https://github.com/dotnet/dotnet-api-docs/blob/main/xml/System/Array.xml
### Document Version Independent Id
8f1a7f9e-41e5-6fcb-aab3-b102bac80a5f
### Platform Id
4b343d8d-ec07-df04-21c1-3976ef5b6f43
### Article author
@dotnet-bot
Contributor guide
Assessment
This issue has not been assessed yet.