From bd9e4a3ce5799326817334c4162f4fd00f8b1a02 Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Thu, 8 Dec 2022 22:52:59 -0500 Subject: [PATCH 1/4] Use ArgumentOutOfRangeException.Throw helpers in more places --- .../src/System/Array.CoreCLR.cs | 11 +- .../EmptyReadOnlyDictionaryInternal.cs | 3 +- .../src/System/GC.CoreCLR.cs | 55 ++------ .../Reflection/Emit/DynamicILGenerator.cs | 10 +- .../src/System/Text/StringBuilder.CoreCLR.cs | 9 +- .../src/System/Threading/Monitor.CoreCLR.cs | 3 +- .../src/System/GC.NativeAot.cs | 64 ++------- .../src/Interop/FreeBSD/Interop.Process.cs | 5 +- .../OSX/Interop.libproc.GetProcessInfoById.cs | 5 +- .../Common/src/Interop/OSX/Interop.libproc.cs | 25 +--- .../Globalization/FormatProvider.Number.cs | 6 +- .../Common/src/System/Net/SocketAddress.cs | 5 +- .../Common/src/System/Text/DBCSDecoder.cs | 28 ++-- .../Common/src/System/Text/OSEncoder.cs | 27 ++-- .../src/System/Text/OSEncoding.Windows.cs | 26 ++-- .../src/Resources/Strings.resx | 3 - .../Concurrent/BlockingCollection.cs | 8 +- .../Collections/Concurrent/ConcurrentBag.cs | 6 +- .../Concurrent/ConcurrentDictionary.cs | 21 +-- .../Collections/Concurrent/ConcurrentStack.cs | 13 +- .../Concurrent/PartitionerStatic.cs | 31 ++--- .../src/Resources/Strings.resx | 6 - .../src/System/Collections/Queue.cs | 10 +- .../src/System/Collections/SortedList.cs | 6 +- .../src/System/Collections/Stack.cs | 6 +- .../src/Resources/Strings.resx | 6 - .../Collections/Specialized/BitVector32.cs | 5 +- .../Collections/Specialized/ListDictionary.cs | 6 +- .../Specialized/NameObjectCollectionBase.cs | 10 +- .../Specialized/NameValueCollection.cs | 5 +- .../Specialized/OrderedDictionary.cs | 15 +- .../src/Resources/Strings.resx | 3 - .../src/System/Collections/BitArray.cs | 23 +--- .../System/Collections/Generic/LinkedList.cs | 10 +- .../Collections/Generic/PriorityQueue.cs | 11 +- .../Collections/Generic/SortedDictionary.cs | 20 +-- .../System/Collections/Generic/SortedList.cs | 3 +- .../System/Collections/Generic/SortedSet.cs | 15 +- .../src/System/Collections/Generic/Stack.cs | 8 +- .../DataAnnotations/Schema/ColumnAttribute.cs | 5 +- .../Design/Serialization/ContextStack.cs | 5 +- .../ComponentModel/MaskedTextProvider.cs | 15 -- .../System.Console/src/Resources/Strings.resx | 6 - .../System.Console/src/System/Console.cs | 36 +---- .../src/System/ConsolePal.Windows.cs | 3 +- .../src/System/IO/SyncTextReader.cs | 8 +- .../src/System/Data/SQLTypes/SQLBytes.cs | 56 ++++---- .../src/System/Data/SQLTypes/SQLChars.cs | 36 +++-- .../src/Resources/Strings.resx | 3 - .../Diagnostics/ProcessManager.FreeBSD.cs | 5 +- .../System/Diagnostics/ProcessManager.OSX.cs | 5 +- .../src/System/Formats/Tar/GnuTarEntry.cs | 10 +- .../src/System/Formats/Tar/TarEntry.cs | 5 +- .../src/Resources/Strings.resx | 3 - .../src/Resources/Strings.resx | 3 - .../src/Resources/Strings.resx | 3 - .../IO/MemoryMappedFiles/MemoryMappedFile.cs | 10 +- .../MemoryMappedView.Unix.cs | 12 +- .../MemoryMappedViewStream.cs | 5 +- .../src/Resources/Strings.resx | 6 - .../System/IO/Pipes/NamedPipeServerStream.cs | 10 +- .../src/System/IO/Pipes/PipeStream.cs | 10 +- .../src/System/Dynamic/Utils/ContractUtils.cs | 7 +- .../ReadOnlyCollectionBuilder.cs | 21 +-- .../src/System/Linq/ParallelEnumerable.cs | 4 +- .../src/Resources/Strings.resx | 6 - .../Http/Headers/ContentRangeHeaderValue.cs | 33 ++--- .../src/System/Net/Http/HttpClient.cs | 5 +- .../Net/Http/HttpClientHandler.AnyMobile.cs | 5 +- .../src/System/Net/Http/HttpClientHandler.cs | 5 +- .../src/System/Net/Http/MultipartContent.cs | 5 +- .../SocketsHttpHandler/SocketsHttpHandler.cs | 10 +- .../src/System/Net/Http/StreamContent.cs | 6 +- .../Net/Windows/WebSockets/WebSocketBuffer.cs | 5 +- .../src/System/Net/Mail/SmtpClient.cs | 15 +- .../System/Net/Mime/QuotedPrintableStream.cs | 5 +- .../src/System/Net/NetworkInformation/Ping.cs | 5 +- .../Net/NetworkInformation/PingOptions.cs | 10 +- .../src/System/Net/Cookie.cs | 5 +- .../src/System/Net/CookieContainer.cs | 5 +- .../src/System/Net/CredentialCache.cs | 10 +- .../src/System/Net/FtpWebRequest.cs | 5 +- .../src/System/Net/TimerThread.cs | 5 +- .../src/System/Net/ServicePoint.cs | 30 +--- .../src/System/Net/ServicePointManager.cs | 25 +--- .../src/Resources/Strings.resx | 5 +- .../src/System/Net/Sockets/NetworkStream.cs | 5 +- .../System/Net/Sockets/SendPacketsElement.cs | 20 +-- .../src/System/Net/Sockets/Socket.cs | 35 +---- .../src/System/Net/Sockets/TCPListener.cs | 5 +- .../Net/WebSockets/WebSocketReceiveResult.cs | 5 +- .../src/Resources/Strings.resx | 5 +- .../System/Collections/CollectionHelpers.cs | 6 +- .../src/Resources/Strings.resx | 24 ---- .../src/System/Collections/ArrayList.cs | 94 ++++++------- .../src/System/Collections/Generic/HashSet.cs | 14 +- .../src/System/Collections/Generic/Queue.cs | 8 +- .../src/System/Collections/Hashtable.cs | 12 +- .../Collections/ListDictionaryInternal.cs | 6 +- .../ObjectModel/CollectionHelpers.cs | 6 +- .../Diagnostics/Tracing/EventDescriptor.cs | 10 +- .../src/System/Globalization/Calendar.cs | 5 +- .../src/System/Globalization/CompareInfo.cs | 12 +- .../src/System/Globalization/CultureInfo.cs | 10 +- .../EastAsianLunisolarCalendar.cs | 8 +- .../System/Globalization/GregorianCalendar.cs | 13 +- .../Globalization/GregorianCalendarHelper.cs | 6 +- .../System/Globalization/HebrewCalendar.cs | 5 +- .../src/System/Globalization/HijriCalendar.cs | 5 +- .../src/System/Globalization/IdnMapping.cs | 8 +- .../System/Globalization/JapaneseCalendar.cs | 13 +- .../System/Globalization/JulianCalendar.cs | 7 +- .../System/Globalization/KoreanCalendar.cs | 5 +- .../System/Globalization/PersianCalendar.cs | 5 +- .../System/Globalization/TaiwanCalendar.cs | 13 +- .../Globalization/ThaiBuddhistCalendar.cs | 5 +- .../System/Globalization/UmAlQuraCalendar.cs | 5 +- .../src/System/IO/BinaryReader.cs | 25 +--- .../src/System/IO/BinaryWriter.cs | 6 +- .../src/System/IO/EnumerationOptions.cs | 5 +- .../src/System/IO/FileStreamOptions.cs | 12 +- .../src/System/IO/MemoryStream.cs | 13 +- .../src/System/IO/Stream.cs | 5 +- .../src/System/IO/StreamReader.cs | 34 ++--- .../src/System/IO/StreamWriter.cs | 41 ++---- .../src/System/IO/StringReader.cs | 22 +-- .../src/System/IO/StringWriter.cs | 10 +- .../src/System/IO/TextReader.cs | 24 ++-- .../src/System/IO/TextWriter.cs | 10 +- .../src/System/IO/UnmanagedMemoryAccessor.cs | 61 ++------ .../System/IO/UnmanagedMemoryStreamWrapper.cs | 3 +- .../src/System/Random.cs | 23 +--- .../System/Runtime/InteropServices/Marshal.cs | 21 +-- .../Runtime/InteropServices/SafeBuffer.cs | 12 +- .../src/System/Runtime/MemoryFailPoint.cs | 3 +- .../src/System/Security/SecureString.cs | 10 +- .../src/System/String.Manipulation.cs | 9 +- .../src/System/String.cs | 10 +- .../src/System/Text/ASCIIEncoding.cs | 8 +- .../src/System/Text/Decoder.cs | 24 ++-- .../src/System/Text/DecoderNLS.cs | 34 ++--- .../src/System/Text/Encoder.cs | 22 ++- .../src/System/Text/EncoderNLS.cs | 34 ++--- .../src/System/Text/Encoding.cs | 17 +-- .../src/System/Text/StringBuilder.cs | 130 ++++-------------- .../src/System/Text/UTF32Encoding.cs | 46 +++---- .../src/System/Text/UTF7Encoding.cs | 46 +++---- .../src/System/Text/UnicodeEncoding.cs | 46 +++---- .../src/System/Threading/Semaphore.cs | 10 +- .../src/System/Threading/SpinWait.cs | 5 +- .../src/System/Threading/Thread.cs | 13 +- .../System/Threading/ThreadPoolWorkQueue.cs | 34 ++--- .../src/System/Threading/Timer.cs | 49 +++---- .../src/System/Threading/WaitHandle.cs | 25 +--- .../System.Private.CoreLib/src/System/Type.cs | 7 +- .../src/System/Version.cs | 6 +- .../src/System/Xml/Linq/XNodeReader.cs | 7 +- .../src/System/Xml/Base64Decoder.cs | 30 +--- .../src/System/Xml/Base64Encoder.cs | 15 +- .../src/System/Xml/BinHexDecoder.cs | 30 +--- .../src/System/Xml/BinHexEncoder.cs | 15 +- .../Xml/Core/ReadContentAsBinaryHelper.cs | 60 ++------ .../System/Xml/Core/XmlCharCheckingReader.cs | 30 +--- .../System/Xml/Core/XmlCharCheckingWriter.cs | 15 +- .../Xml/Core/XmlCharCheckingWriterAsync.cs | 15 +- .../src/System/Xml/Core/XmlSubtreeReader.cs | 15 +- .../src/System/Xml/Core/XmlTextEncoder.cs | 34 +---- .../src/System/Xml/Core/XmlTextReaderImpl.cs | 75 ++-------- .../System/Xml/Core/XmlTextReaderImplAsync.cs | 75 ++-------- .../System/Xml/Core/XmlWellFormedWriter.cs | 45 ++---- .../Xml/Core/XmlWellFormedWriterAsync.cs | 45 ++---- .../src/System/Xml/Dom/XmlText.cs | 3 +- .../src/System/Xml/NameTable.cs | 5 +- .../Xml/Resolvers/XmlPreloadedResolver.cs | 15 +- .../System/Xml/Schema/XmlSchemaCollection.cs | 6 +- .../System/Xml/Schema/XmlSchemaObjectTable.cs | 6 +- .../src/System/Xml/Schema/XsdDuration.cs | 12 +- .../Xml/Xsl/Runtime/XmlQuerySequence.cs | 9 +- .../src/Resources/Strings.resx | 5 +- .../src/System/Security/AccessControl/ACE.cs | 18 +-- .../src/System/Security/AccessControl/ACL.cs | 23 +--- .../AccessControl/SecurityDescriptor.cs | 16 +-- .../src/Resources/Strings.resx | 3 - .../Security/Cryptography/CryptoStream.cs | 3 +- .../DSACryptoServiceProvider.Unix.cs | 3 +- .../DSACryptoServiceProvider.Windows.cs | 3 +- .../src/System/Security/Cryptography/HKDF.cs | 6 +- .../Security/Cryptography/HashAlgorithm.cs | 6 +- .../Security/Cryptography/HashProvider.cs | 6 +- .../Security/Cryptography/IncrementalHash.cs | 7 +- .../Cryptography/PasswordDeriveBytes.cs | 3 +- .../Security/Cryptography/PbeParameters.cs | 8 +- .../Security/Cryptography/PemEncoding.cs | 6 +- .../RSACryptoServiceProvider.Unix.cs | 3 +- .../RSACryptoServiceProvider.Windows.cs | 5 +- .../Cryptography/RandomNumberGenerator.cs | 12 +- .../Rfc2898DeriveBytes.OneShot.cs | 18 +-- .../Cryptography/Rfc2898DeriveBytes.cs | 15 +- .../Cryptography/SymmetricAlgorithm.cs | 11 +- .../Cryptography/UniversalCryptoTransform.cs | 21 +-- .../CertificateRevocationListBuilder.Build.cs | 6 +- .../X509BasicConstraintsExtension.cs | 6 +- .../src/Resources/Strings.resx | 3 - .../src/System/Security/Principal/SID.cs | 5 +- .../System/Transactions/TransactionManager.cs | 10 +- .../System/Transactions/TransactionScope.cs | 5 +- .../src/System/Array.Mono.cs | 3 +- .../src/System/GC.Mono.cs | 30 ++-- .../System/Reflection/Emit/DynamicILInfo.cs | 3 +- .../src/System/Threading/Thread.Mono.cs | 3 +- 210 files changed, 855 insertions(+), 2306 deletions(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs index 3d33da1beb928f..a473169d0dccdc 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs @@ -94,17 +94,16 @@ private static unsafe void Copy(Array sourceArray, int sourceIndex, Array destin if (sourceArray.GetType() != destinationArray.GetType() && sourceArray.Rank != destinationArray.Rank) throw new RankException(SR.Rank_MustMatch); - if (length < 0) - throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(length); int srcLB = sourceArray.GetLowerBound(0); - if (sourceIndex < srcLB || sourceIndex - srcLB < 0) - throw new ArgumentOutOfRangeException(nameof(sourceIndex), SR.ArgumentOutOfRange_ArrayLB); + ArgumentOutOfRangeException.ThrowIfLessThan(sourceIndex, srcLB); + ArgumentOutOfRangeException.ThrowIfNegative(sourceIndex - srcLB, nameof(sourceIndex)); sourceIndex -= srcLB; int dstLB = destinationArray.GetLowerBound(0); - if (destinationIndex < dstLB || destinationIndex - dstLB < 0) - throw new ArgumentOutOfRangeException(nameof(destinationIndex), SR.ArgumentOutOfRange_ArrayLB); + ArgumentOutOfRangeException.ThrowIfLessThan(destinationIndex, dstLB); + ArgumentOutOfRangeException.ThrowIfNegative(destinationIndex - dstLB, nameof(destinationIndex)); destinationIndex -= dstLB; if ((uint)(sourceIndex + length) > sourceArray.NativeLength) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Collections/EmptyReadOnlyDictionaryInternal.cs b/src/coreclr/System.Private.CoreLib/src/System/Collections/EmptyReadOnlyDictionaryInternal.cs index aac36f4f69123c..9ade6db3557e56 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Collections/EmptyReadOnlyDictionaryInternal.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Collections/EmptyReadOnlyDictionaryInternal.cs @@ -40,8 +40,7 @@ public void CopyTo(Array array, int index) if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); if (array.Length - index < this.Count) throw new ArgumentException(SR.ArgumentOutOfRange_IndexMustBeLessOrEqual, nameof(index)); diff --git a/src/coreclr/System.Private.CoreLib/src/System/GC.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/GC.CoreCLR.cs index 25445726f2900f..a5ae6622ded853 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/GC.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/GC.CoreCLR.cs @@ -136,16 +136,10 @@ internal enum GC_ALLOC_FLAGS public static void AddMemoryPressure(long bytesAllocated) { - if (bytesAllocated <= 0) + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(bytesAllocated); + if (IntPtr.Size == 4) { - throw new ArgumentOutOfRangeException(nameof(bytesAllocated), - SR.ArgumentOutOfRange_NeedPosNum); - } - - if ((4 == IntPtr.Size) && (bytesAllocated > int.MaxValue)) - { - throw new ArgumentOutOfRangeException(nameof(bytesAllocated), - SR.ArgumentOutOfRange_MustBeNonNegInt32); + ArgumentOutOfRangeException.ThrowIfGreaterThan(bytesAllocated, int.MaxValue); } _AddMemoryPressure((ulong)bytesAllocated); @@ -153,16 +147,10 @@ public static void AddMemoryPressure(long bytesAllocated) public static void RemoveMemoryPressure(long bytesAllocated) { - if (bytesAllocated <= 0) - { - throw new ArgumentOutOfRangeException(nameof(bytesAllocated), - SR.ArgumentOutOfRange_NeedPosNum); - } - - if ((4 == IntPtr.Size) && (bytesAllocated > int.MaxValue)) + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(bytesAllocated); + if (IntPtr.Size == 4) { - throw new ArgumentOutOfRangeException(nameof(bytesAllocated), - SR.ArgumentOutOfRange_MustBeNonNegInt32); + ArgumentOutOfRangeException.ThrowIfGreaterThan(bytesAllocated, int.MaxValue); } _RemoveMemoryPressure((ulong)bytesAllocated); @@ -202,10 +190,7 @@ public static void Collect(int generation, GCCollectionMode mode, bool blocking) public static void Collect(int generation, GCCollectionMode mode, bool blocking, bool compacting) { - if (generation < 0) - { - throw new ArgumentOutOfRangeException(nameof(generation), SR.ArgumentOutOfRange_GenericPositive); - } + ArgumentOutOfRangeException.ThrowIfNegative(generation); if ((mode < GCCollectionMode.Default) || (mode > GCCollectionMode.Aggressive)) { @@ -253,10 +238,7 @@ public static void Collect(int generation, GCCollectionMode mode, bool blocking, public static int CollectionCount(int generation) { - if (generation < 0) - { - throw new ArgumentOutOfRangeException(nameof(generation), SR.ArgumentOutOfRange_GenericPositive); - } + ArgumentOutOfRangeException.ThrowIfNegative(generation); return _CollectionCount(generation, 0); } @@ -447,8 +429,7 @@ public static GCNotificationStatus WaitForFullGCApproach() public static GCNotificationStatus WaitForFullGCApproach(int millisecondsTimeout) { - if (millisecondsTimeout < -1) - throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); + ArgumentOutOfRangeException.ThrowIfLessThan(millisecondsTimeout, -1); return (GCNotificationStatus)_WaitForFullGCApproach(millisecondsTimeout); } @@ -460,8 +441,7 @@ public static GCNotificationStatus WaitForFullGCComplete() public static GCNotificationStatus WaitForFullGCComplete(int millisecondsTimeout) { - if (millisecondsTimeout < -1) - throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); + ArgumentOutOfRangeException.ThrowIfLessThan(millisecondsTimeout, -1); return (GCNotificationStatus)_WaitForFullGCComplete(millisecondsTimeout); } @@ -483,22 +463,13 @@ private enum EndNoGCRegionStatus private static bool StartNoGCRegionWorker(long totalSize, bool hasLohSize, long lohSize, bool disallowFullBlockingGC) { - if (totalSize <= 0) - { - throw new ArgumentOutOfRangeException(nameof(totalSize), SR.ArgumentOutOfRange_MustBePositive); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(totalSize); if (hasLohSize) { - if (lohSize <= 0) - { - throw new ArgumentOutOfRangeException(nameof(lohSize), SR.ArgumentOutOfRange_MustBePositive); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(lohSize); - if (lohSize > totalSize) - { - throw new ArgumentOutOfRangeException(nameof(lohSize), SR.ArgumentOutOfRange_NoGCLohSizeGreaterTotalSize); - } + ArgumentOutOfRangeException.ThrowIfGreaterThan(lohSize, totalSize); } StartNoGCRegionStatus status = (StartNoGCRegionStatus)_StartNoGCRegion(totalSize, hasLohSize, lohSize, disallowFullBlockingGC); diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/DynamicILGenerator.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/DynamicILGenerator.cs index 4e0f0dc8f5d00c..958d69a47bed84 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/DynamicILGenerator.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/DynamicILGenerator.cs @@ -907,8 +907,7 @@ public void SetCode(byte[]? code, int maxStackSize) [CLSCompliant(false)] public unsafe void SetCode(byte* code, int codeSize, int maxStackSize) { - if (codeSize < 0) - throw new ArgumentOutOfRangeException(nameof(codeSize), SR.ArgumentOutOfRange_GenericPositive); + ArgumentOutOfRangeException.ThrowIfNegative(codeSize); if (codeSize > 0) ArgumentNullException.ThrowIfNull(code); @@ -924,8 +923,7 @@ public void SetExceptions(byte[]? exceptions) [CLSCompliant(false)] public unsafe void SetExceptions(byte* exceptions, int exceptionsSize) { - if (exceptionsSize < 0) - throw new ArgumentOutOfRangeException(nameof(exceptionsSize), SR.ArgumentOutOfRange_GenericPositive); + ArgumentOutOfRangeException.ThrowIfNegative(exceptionsSize); if (exceptionsSize > 0) ArgumentNullException.ThrowIfNull(exceptions); @@ -941,9 +939,7 @@ public void SetLocalSignature(byte[]? localSignature) [CLSCompliant(false)] public unsafe void SetLocalSignature(byte* localSignature, int signatureSize) { - if (signatureSize < 0) - throw new ArgumentOutOfRangeException(nameof(signatureSize), SR.ArgumentOutOfRange_GenericPositive); - + ArgumentOutOfRangeException.ThrowIfNegative(signatureSize); if (signatureSize > 0) ArgumentNullException.ThrowIfNull(localSignature); diff --git a/src/coreclr/System.Private.CoreLib/src/System/Text/StringBuilder.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Text/StringBuilder.CoreCLR.cs index 93775554ab35d3..40973d0e30e950 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Text/StringBuilder.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Text/StringBuilder.CoreCLR.cs @@ -26,8 +26,7 @@ private int GetReplaceBufferCapacity(int requiredCapacity) internal unsafe void ReplaceBufferInternal(char* newBuffer, int newLength) { - if (newLength > m_MaxCapacity) - throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_Capacity); + ArgumentOutOfRangeException.ThrowIfGreaterThan(newLength, m_MaxCapacity, "capacity"); if (newLength > m_ChunkChars.Length) { @@ -42,8 +41,7 @@ internal unsafe void ReplaceBufferInternal(char* newBuffer, int newLength) internal void ReplaceBufferUtf8Internal(ReadOnlySpan source) { - if (source.Length > m_MaxCapacity) - throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_Capacity); + ArgumentOutOfRangeException.ThrowIfGreaterThan(source.Length, m_MaxCapacity, "capacity"); int numChars = Encoding.UTF8.GetCharCount(source); if (numChars > m_ChunkChars.Length) @@ -58,8 +56,7 @@ internal void ReplaceBufferUtf8Internal(ReadOnlySpan source) internal unsafe void ReplaceBufferAnsiInternal(sbyte* newBuffer, int newLength) { - if (newLength > m_MaxCapacity) - throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_Capacity); + ArgumentOutOfRangeException.ThrowIfGreaterThan(newLength, m_MaxCapacity, "capacity"); if (newLength > m_ChunkChars.Length) { diff --git a/src/coreclr/System.Private.CoreLib/src/System/Threading/Monitor.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Threading/Monitor.CoreCLR.cs index b55bf1f17baff7..9fd823ba175708 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Threading/Monitor.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Threading/Monitor.CoreCLR.cs @@ -151,8 +151,7 @@ public static bool IsEntered(object obj) public static bool Wait(object obj, int millisecondsTimeout) { ArgumentNullException.ThrowIfNull(obj); - if (millisecondsTimeout < -1) - throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); + ArgumentOutOfRangeException.ThrowIfLessThan(millisecondsTimeout, -1); return ObjWait(millisecondsTimeout, obj); } diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/GC.NativeAot.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/GC.NativeAot.cs index 6153784b66fbf7..4554c37ec0a654 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/GC.NativeAot.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/GC.NativeAot.cs @@ -122,10 +122,7 @@ public static void Collect(int generation, GCCollectionMode mode, bool blocking) public static void Collect(int generation, GCCollectionMode mode, bool blocking, bool compacting) { - if (generation < 0) - { - throw new ArgumentOutOfRangeException(nameof(generation), SR.ArgumentOutOfRange_GenericPositive); - } + ArgumentOutOfRangeException.ThrowIfNegative(generation); if ((mode < GCCollectionMode.Default) || (mode > GCCollectionMode.Aggressive)) { @@ -224,12 +221,7 @@ public static GCNotificationStatus WaitForFullGCApproach() /// The status of a registered full GC notification public static GCNotificationStatus WaitForFullGCApproach(int millisecondsTimeout) { - if (millisecondsTimeout < -1) - { - throw new ArgumentOutOfRangeException( - nameof(millisecondsTimeout), - SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - } + ArgumentOutOfRangeException.ThrowIfLessThan(millisecondsTimeout, -1); return (GCNotificationStatus)RuntimeImports.RhWaitForFullGCApproach(millisecondsTimeout); } @@ -252,12 +244,7 @@ public static GCNotificationStatus WaitForFullGCComplete() /// public static GCNotificationStatus WaitForFullGCComplete(int millisecondsTimeout) { - if (millisecondsTimeout < -1) - { - throw new ArgumentOutOfRangeException( - nameof(millisecondsTimeout), - SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - } + ArgumentOutOfRangeException.ThrowIfLessThan(millisecondsTimeout, -1); return (GCNotificationStatus)RuntimeImports.RhWaitForFullGCComplete(millisecondsTimeout); } @@ -341,22 +328,10 @@ public static bool TryStartNoGCRegion(long totalSize, long lohSize, bool disallo private static bool StartNoGCRegionWorker(long totalSize, bool hasLohSize, long lohSize, bool disallowFullBlockingGC) { - if (totalSize <= 0) - { - throw new ArgumentOutOfRangeException( - nameof(totalSize), - SR.Format(SR.ArgumentOutOfRange_MustBePositive, nameof(totalSize))); - } - + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(totalSize); if (hasLohSize) { - if (lohSize <= 0) - { - throw new ArgumentOutOfRangeException( - nameof(lohSize), - SR.Format(SR.ArgumentOutOfRange_MustBePositive, nameof(lohSize))); - } - + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(lohSize); if (lohSize > totalSize) { throw new ArgumentOutOfRangeException(nameof(lohSize), SR.ArgumentOutOfRange_NoGCLohSizeGreaterTotalSize); @@ -445,8 +420,7 @@ public static int MaxGeneration public static int CollectionCount(int generation) { - if (generation < 0) - throw new ArgumentOutOfRangeException(nameof(generation), SR.ArgumentOutOfRange_GenericPositive); + ArgumentOutOfRangeException.ThrowIfNegative(generation); return RuntimeImports.RhGetGcCollectionCount(generation, false); } @@ -527,18 +501,9 @@ private static long InterlockedAddMemoryPressure(ref long pAugend, long addend) /// public static void AddMemoryPressure(long bytesAllocated) { - if (bytesAllocated <= 0) - { - throw new ArgumentOutOfRangeException(nameof(bytesAllocated), - SR.ArgumentOutOfRange_NeedPosNum); - } - + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(bytesAllocated); #if !TARGET_64BIT - if (bytesAllocated > int.MaxValue) - { - throw new ArgumentOutOfRangeException(nameof(bytesAllocated), - SR.ArgumentOutOfRange_MustBeNonNegInt32); - } + ArgumentOutOfRangeException.ThrowIfGreaterThan(bytesAllocated, int.MaxValue); #endif CheckCollectionCount(); @@ -654,18 +619,9 @@ public static unsafe IReadOnlyDictionary GetConfigurationVariabl public static void RemoveMemoryPressure(long bytesAllocated) { - if (bytesAllocated <= 0) - { - throw new ArgumentOutOfRangeException(nameof(bytesAllocated), - SR.ArgumentOutOfRange_NeedPosNum); - } - + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(bytesAllocated); #if !TARGET_64BIT - if (bytesAllocated > int.MaxValue) - { - throw new ArgumentOutOfRangeException(nameof(bytesAllocated), - SR.ArgumentOutOfRange_MustBeNonNegInt32); - } + ArgumentOutOfRangeException.ThrowIfGreaterThan(bytesAllocated, int.MaxValue); #endif CheckCollectionCount(); diff --git a/src/libraries/Common/src/Interop/FreeBSD/Interop.Process.cs b/src/libraries/Common/src/Interop/FreeBSD/Interop.Process.cs index e61abfa46cc398..837f3a1896386a 100644 --- a/src/libraries/Common/src/Interop/FreeBSD/Interop.Process.cs +++ b/src/libraries/Common/src/Interop/FreeBSD/Interop.Process.cs @@ -103,10 +103,7 @@ public static unsafe string GetProcPath(int pid) public static unsafe ProcessInfo GetProcessInfoById(int pid) { // Negative PIDs are invalid - if (pid < 0) - { - throw new ArgumentOutOfRangeException(nameof(pid)); - } + ArgumentOutOfRangeException.ThrowIfNegative(pid); ProcessInfo info; diff --git a/src/libraries/Common/src/Interop/OSX/Interop.libproc.GetProcessInfoById.cs b/src/libraries/Common/src/Interop/OSX/Interop.libproc.GetProcessInfoById.cs index f337eb45c9a93a..d3eaeabf0cc319 100644 --- a/src/libraries/Common/src/Interop/OSX/Interop.libproc.GetProcessInfoById.cs +++ b/src/libraries/Common/src/Interop/OSX/Interop.libproc.GetProcessInfoById.cs @@ -108,10 +108,7 @@ private static unsafe partial int proc_pidinfo( internal static unsafe proc_taskallinfo? GetProcessInfoById(int pid) { // Negative PIDs are invalid - if (pid < 0) - { - throw new ArgumentOutOfRangeException(nameof(pid)); - } + ArgumentOutOfRangeException.ThrowIfNegative(pid); // Get the process information for the specified pid int size = sizeof(proc_taskallinfo); diff --git a/src/libraries/Common/src/Interop/OSX/Interop.libproc.cs b/src/libraries/Common/src/Interop/OSX/Interop.libproc.cs index dbb7fcc7e6368a..fe0f7df5f76681 100644 --- a/src/libraries/Common/src/Interop/OSX/Interop.libproc.cs +++ b/src/libraries/Common/src/Interop/OSX/Interop.libproc.cs @@ -238,16 +238,10 @@ private static unsafe partial int proc_pidinfo( internal static unsafe proc_threadinfo? GetThreadInfoById(int pid, ulong thread) { // Negative PIDs are invalid - if (pid < 0) - { - throw new ArgumentOutOfRangeException(nameof(pid)); - } + ArgumentOutOfRangeException.ThrowIfNegative(pid); // Negative TIDs are invalid - if (thread < 0) - { - throw new ArgumentOutOfRangeException(nameof(thread)); - } + ArgumentOutOfRangeException.ThrowIfNegative(thread); // Get the thread information for the specified thread in the specified process int size = sizeof(proc_threadinfo); @@ -259,10 +253,7 @@ private static unsafe partial int proc_pidinfo( internal static unsafe List> GetAllThreadsInProcess(int pid) { // Negative PIDs are invalid - if (pid < 0) - { - throw new ArgumentOutOfRangeException(nameof(pid)); - } + ArgumentOutOfRangeException.ThrowIfNegative(pid); int result = 0; int size = 20; // start assuming 20 threads is enough @@ -331,10 +322,7 @@ private static unsafe partial int proc_pidpath( internal static unsafe string proc_pidpath(int pid) { // Negative PIDs are invalid - if (pid < 0) - { - throw new ArgumentOutOfRangeException(nameof(pid), SR.NegativePidNotSupported); - } + ArgumentOutOfRangeException.ThrowIfNegative(pid); // The path is a fixed buffer size, so use that and trim it after int result = 0; @@ -372,10 +360,7 @@ private static unsafe partial int proc_pid_rusage( internal static unsafe rusage_info_v3 proc_pid_rusage(int pid) { // Negative PIDs are invalid - if (pid < 0) - { - throw new ArgumentOutOfRangeException(nameof(pid), SR.NegativePidNotSupported); - } + ArgumentOutOfRangeException.ThrowIfNegative(pid); rusage_info_v3 info = default; diff --git a/src/libraries/Common/src/System/Globalization/FormatProvider.Number.cs b/src/libraries/Common/src/System/Globalization/FormatProvider.Number.cs index a630552a064e3d..0a7a7a4a89536c 100644 --- a/src/libraries/Common/src/System/Globalization/FormatProvider.Number.cs +++ b/src/libraries/Common/src/System/Globalization/FormatProvider.Number.cs @@ -964,10 +964,8 @@ private static unsafe void FormatFixed(ref ValueStringBuilder sb, scoped ref Num } groupSizeCount += groupDigits[groupSizeIndex]; - if (groupSizeCount < 0 || bufferSize < 0) - { - throw new ArgumentOutOfRangeException(); // If we overflow - } + ArgumentOutOfRangeException.ThrowIfNegative(groupSizeCount); // If we overflow + ArgumentOutOfRangeException.ThrowIfNegative(bufferSize); } if (groupSizeCount == 0) // If you passed in an array with one entry as 0, groupSizeCount == 0 diff --git a/src/libraries/Common/src/System/Net/SocketAddress.cs b/src/libraries/Common/src/System/Net/SocketAddress.cs index 54b53db8296893..07e533f518e632 100644 --- a/src/libraries/Common/src/System/Net/SocketAddress.cs +++ b/src/libraries/Common/src/System/Net/SocketAddress.cs @@ -86,10 +86,7 @@ public SocketAddress(AddressFamily family) : this(family, MaxSize) public SocketAddress(AddressFamily family, int size) { - if (size < MinSize) - { - throw new ArgumentOutOfRangeException(nameof(size)); - } + ArgumentOutOfRangeException.ThrowIfLessThan(size, MinSize); InternalSize = size; Buffer = new byte[(size / IntPtr.Size + 2) * IntPtr.Size]; diff --git a/src/libraries/Common/src/System/Text/DBCSDecoder.cs b/src/libraries/Common/src/System/Text/DBCSDecoder.cs index 5be9b0cef17463..daf78fc064362f 100644 --- a/src/libraries/Common/src/System/Text/DBCSDecoder.cs +++ b/src/libraries/Common/src/System/Text/DBCSDecoder.cs @@ -49,9 +49,8 @@ public override unsafe int GetCharCount(byte[] bytes, int index, int count, bool { ArgumentNullException.ThrowIfNull(bytes); - if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); - + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); @@ -97,8 +96,7 @@ public override unsafe int GetCharCount(byte* bytes, int count, bool flush) { ArgumentNullException.ThrowIfNull(bytes); - if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(count); bool excludeLastByte = count > 0 && !flush && IsLastByteALeadByte(bytes, count); @@ -131,8 +129,8 @@ public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, ArgumentNullException.ThrowIfNull(bytes); ArgumentNullException.ThrowIfNull(chars); - if (byteIndex < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(byteIndex); + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); @@ -161,8 +159,8 @@ public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int ArgumentNullException.ThrowIfNull(bytes); ArgumentNullException.ThrowIfNull(chars); - if (byteCount < 0 || charCount < 0) - throw new ArgumentOutOfRangeException(byteCount < 0 ? nameof(byteCount) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); if (charCount == 0) return 0; @@ -201,11 +199,11 @@ public override unsafe void Convert(byte[] bytes, int byteIndex, int byteCount, ArgumentNullException.ThrowIfNull(bytes); ArgumentNullException.ThrowIfNull(chars); - if (byteIndex < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(byteIndex); + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); - if (charIndex < 0 || charCount < 0) - throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(charIndex); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); @@ -238,8 +236,8 @@ public override unsafe void Convert(byte* bytes, int byteCount, ArgumentNullException.ThrowIfNull(bytes); ArgumentNullException.ThrowIfNull(chars); - if (byteCount < 0 || charCount < 0) - throw new ArgumentOutOfRangeException(byteCount < 0 ? nameof(byteCount) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); int count = byteCount; while (count > 0) diff --git a/src/libraries/Common/src/System/Text/OSEncoder.cs b/src/libraries/Common/src/System/Text/OSEncoder.cs index b8d17780409f0f..1bc859827649f3 100644 --- a/src/libraries/Common/src/System/Text/OSEncoder.cs +++ b/src/libraries/Common/src/System/Text/OSEncoder.cs @@ -29,8 +29,8 @@ public override unsafe int GetByteCount(char[] chars, int index, int count, bool { ArgumentNullException.ThrowIfNull(chars); - if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (chars.Length - index < count) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); @@ -76,8 +76,7 @@ public override unsafe int GetByteCount(char* chars, int count, bool flush) { ArgumentNullException.ThrowIfNull(chars); - if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(count); bool excludeLastChar = count > 0 && !flush && char.IsHighSurrogate(chars[count - 1]); @@ -105,8 +104,8 @@ public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, ArgumentNullException.ThrowIfNull(chars); ArgumentNullException.ThrowIfNull(bytes); - if (charIndex < 0 || charCount < 0) - throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(charIndex); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); @@ -135,8 +134,8 @@ public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int ArgumentNullException.ThrowIfNull(chars); ArgumentNullException.ThrowIfNull(bytes); - if (byteCount < 0 || charCount < 0) - throw new ArgumentOutOfRangeException(byteCount < 0 ? nameof(byteCount) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); if (byteCount == 0) return 0; @@ -175,11 +174,11 @@ public override unsafe void Convert(char[] chars, int charIndex, int charCount, ArgumentNullException.ThrowIfNull(chars); ArgumentNullException.ThrowIfNull(bytes); - if (charIndex < 0 || charCount < 0) - throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(charIndex); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); - if (byteIndex < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(byteIndex); + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); @@ -212,8 +211,8 @@ public override unsafe void Convert(char* chars, int charCount, ArgumentNullException.ThrowIfNull(chars); ArgumentNullException.ThrowIfNull(bytes); - if (charCount < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); int count = charCount; while (count > 0) diff --git a/src/libraries/Common/src/System/Text/OSEncoding.Windows.cs b/src/libraries/Common/src/System/Text/OSEncoding.Windows.cs index 4b1c5207308325..c7ead4c54e3dd7 100644 --- a/src/libraries/Common/src/System/Text/OSEncoding.Windows.cs +++ b/src/libraries/Common/src/System/Text/OSEncoding.Windows.cs @@ -21,8 +21,8 @@ public override unsafe int GetByteCount(char[] chars, int index, int count) { ArgumentNullException.ThrowIfNull(chars); - if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (chars.Length - index < count) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); @@ -54,8 +54,8 @@ public override unsafe int GetBytes(string s, int charIndex, int charCount, byte ArgumentNullException.ThrowIfNull(s); ArgumentNullException.ThrowIfNull(bytes); - if (charIndex < 0 || charCount < 0) - throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(charIndex); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); if (s.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(s), SR.ArgumentOutOfRange_IndexCount); @@ -83,8 +83,8 @@ public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, ArgumentNullException.ThrowIfNull(chars); ArgumentNullException.ThrowIfNull(bytes); - if (charIndex < 0 || charCount < 0) - throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(charIndex); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); @@ -111,8 +111,8 @@ public override unsafe int GetCharCount(byte[] bytes, int index, int count) { ArgumentNullException.ThrowIfNull(bytes); - if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); @@ -131,8 +131,8 @@ public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, ArgumentNullException.ThrowIfNull(bytes); ArgumentNullException.ThrowIfNull(chars); - if (byteIndex < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(byteIndex); + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); @@ -155,8 +155,7 @@ public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, public override int GetMaxByteCount(int charCount) { - if (charCount < 0) - throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); long byteCount = (long)charCount * 14; // Max possible value for all encodings if (byteCount > 0x7fffffff) @@ -167,8 +166,7 @@ public override int GetMaxByteCount(int charCount) public override int GetMaxCharCount(int byteCount) { - if (byteCount < 0) - throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); long charCount = byteCount * 4; // Max possible value for all encodings diff --git a/src/libraries/System.Collections.Concurrent/src/Resources/Strings.resx b/src/libraries/System.Collections.Concurrent/src/Resources/Strings.resx index 147fef7d0c0aca..981b795ca11628 100644 --- a/src/libraries/System.Collections.Concurrent/src/Resources/Strings.resx +++ b/src/libraries/System.Collections.Concurrent/src/Resources/Strings.resx @@ -87,9 +87,6 @@ The number of elements in the collection is greater than the available space from index to the end of the destination array. - - The boundedCapacity argument must be positive. - The collection argument contains more items than are allowed by the boundedCapacity. diff --git a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/BlockingCollection.cs b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/BlockingCollection.cs index ec3e26c82d812b..7de95f63b4ad88 100644 --- a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/BlockingCollection.cs +++ b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/BlockingCollection.cs @@ -176,13 +176,7 @@ public BlockingCollection(int boundedCapacity) public BlockingCollection(IProducerConsumerCollection collection, int boundedCapacity) { ArgumentNullException.ThrowIfNull(collection); - - if (boundedCapacity < 1) - { - throw new ArgumentOutOfRangeException( - nameof(boundedCapacity), boundedCapacity, - SR.BlockingCollection_ctor_BoundedCapacityRange); - } + ArgumentOutOfRangeException.ThrowIfLessThan(boundedCapacity, 1); int count = collection.Count; if (count > boundedCapacity) diff --git a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentBag.cs b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentBag.cs index 966cdc5cff0979..6f96523cf279b3 100644 --- a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentBag.cs +++ b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentBag.cs @@ -277,11 +277,7 @@ private static bool TryStealFromTo(WorkStealingQueue? startInclusive, WorkSteali public void CopyTo(T[] array, int index) { ArgumentNullException.ThrowIfNull(array); - - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index), SR.Collection_CopyTo_ArgumentOutOfRangeException); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); // Short path if the bag is empty if (_workStealingQueues == null) diff --git a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentDictionary.cs b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentDictionary.cs index 8ad537cde47855..c73a68ce85d4e1 100644 --- a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentDictionary.cs +++ b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentDictionary.cs @@ -169,14 +169,8 @@ public ConcurrentDictionary(int concurrencyLevel, int capacity, IEqualityCompare internal ConcurrentDictionary(int concurrencyLevel, int capacity, bool growLockArray, IEqualityComparer? comparer) { - if (concurrencyLevel < 1) - { - throw new ArgumentOutOfRangeException(nameof(concurrencyLevel), SR.ConcurrentDictionary_ConcurrencyLevelMustBePositive); - } - if (capacity < 0) - { - throw new ArgumentOutOfRangeException(nameof(capacity), SR.ConcurrentDictionary_CapacityMustNotBeNegative); - } + ArgumentOutOfRangeException.ThrowIfLessThan(concurrencyLevel, 1); + ArgumentOutOfRangeException.ThrowIfNegative(capacity); // The capacity should be at least as large as the concurrency level. Otherwise, we would have locks that don't guard // any buckets. @@ -639,10 +633,7 @@ void ICollection>.CopyTo(KeyValuePair[] { ArgumentNullException.ThrowIfNull(array); - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index), SR.ConcurrentDictionary_IndexIsNegative); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); int locksAcquired = 0; try @@ -1767,11 +1758,7 @@ private static void ThrowIfInvalidObjectValue(object? value) void ICollection.CopyTo(Array array, int index) { ArgumentNullException.ThrowIfNull(array); - - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index), SR.ConcurrentDictionary_IndexIsNegative); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); int locksAcquired = 0; try diff --git a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentStack.cs b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentStack.cs index 1dd85720f0358e..ef3c9ffcaad61d 100644 --- a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentStack.cs +++ b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentStack.cs @@ -391,15 +391,12 @@ private static void ValidatePushPopRangeInput(T[] items, int startIndex, int cou { ArgumentNullException.ThrowIfNull(items); - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count), SR.ConcurrentStack_PushPopRange_CountOutOfRange); - } + ArgumentOutOfRangeException.ThrowIfNegative(count); + int length = items.Length; - if (startIndex > length || startIndex < 0) - { - throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ConcurrentStack_PushPopRange_StartOutOfRange); - } + ArgumentOutOfRangeException.ThrowIfGreaterThan(startIndex, length); + ArgumentOutOfRangeException.ThrowIfNegative(startIndex); + if (length - count < startIndex) //instead of (startIndex + count > items.Length) to prevent overflow { throw new ArgumentException(SR.ConcurrentStack_PushPopRange_InvalidCount); diff --git a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/PartitionerStatic.cs b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/PartitionerStatic.cs index 4305aa57fa4ce5..52d2bf7e5d361d 100644 --- a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/PartitionerStatic.cs +++ b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/PartitionerStatic.cs @@ -181,7 +181,7 @@ public static OrderablePartitioner Create(IEnumerable /// if ProcessorCount == 1, for correct rangeSize calculation the const CoreOversubscriptionRate must be > 1 (avoid division by 1) public static OrderablePartitioner> Create(long fromInclusive, long toExclusive) { - if (toExclusive <= fromInclusive) throw new ArgumentOutOfRangeException(nameof(toExclusive)); + ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(toExclusive, fromInclusive); decimal range = (decimal)toExclusive - fromInclusive; long rangeSize = (long)(range / (Environment.ProcessorCount * CoreOversubscriptionRate)); if (rangeSize == 0) rangeSize = 1; @@ -199,8 +199,8 @@ public static OrderablePartitioner> Create(long fromInclusive, /// less than or equal to 0. public static OrderablePartitioner> Create(long fromInclusive, long toExclusive, long rangeSize) { - if (toExclusive <= fromInclusive) throw new ArgumentOutOfRangeException(nameof(toExclusive)); - if (rangeSize <= 0) throw new ArgumentOutOfRangeException(nameof(rangeSize)); + ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(toExclusive, fromInclusive); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(rangeSize); return Partitioner.Create(CreateRanges(fromInclusive, toExclusive, rangeSize), EnumerablePartitionerOptions.NoBuffering); // chunk one range at a time } @@ -235,7 +235,7 @@ private static IEnumerable> CreateRanges(long fromInclusive, l /// and the same issue could occur with rangeSize == -1 when fromInclusive = int.MinValue and toExclusive = int.MaxValue. public static OrderablePartitioner> Create(int fromInclusive, int toExclusive) { - if (toExclusive <= fromInclusive) throw new ArgumentOutOfRangeException(nameof(toExclusive)); + ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(toExclusive, fromInclusive); long range = (long)toExclusive - fromInclusive; int rangeSize = (int)(range / (Environment.ProcessorCount * CoreOversubscriptionRate)); if (rangeSize == 0) rangeSize = 1; @@ -253,8 +253,8 @@ public static OrderablePartitioner> Create(int fromInclusive, in /// less than or equal to 0. public static OrderablePartitioner> Create(int fromInclusive, int toExclusive, int rangeSize) { - if (toExclusive <= fromInclusive) throw new ArgumentOutOfRangeException(nameof(toExclusive)); - if (rangeSize <= 0) throw new ArgumentOutOfRangeException(nameof(rangeSize)); + ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(toExclusive, fromInclusive); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(rangeSize); return Partitioner.Create(CreateRanges(fromInclusive, toExclusive, rangeSize), EnumerablePartitionerOptions.NoBuffering); // chunk one range at a time } @@ -500,10 +500,7 @@ internal DynamicPartitionerForIEnumerable(IEnumerable source, Enumerabl /// A list containing enumerators. public override IList>> GetOrderablePartitions(int partitionCount) { - if (partitionCount <= 0) - { - throw new ArgumentOutOfRangeException(nameof(partitionCount)); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(partitionCount); IEnumerator>[] partitions = new IEnumerator>[partitionCount]; @@ -1012,10 +1009,7 @@ protected DynamicPartitionerForIndexRange_Abstract(TCollection data) /// A list containing enumerators. public override IList>> GetOrderablePartitions(int partitionCount) { - if (partitionCount <= 0) - { - throw new ArgumentOutOfRangeException(nameof(partitionCount)); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(partitionCount); IEnumerator>[] partitions = new IEnumerator>[partitionCount]; IEnumerable> partitionEnumerable = GetOrderableDynamicPartitions_Factory(_data); @@ -1371,14 +1365,9 @@ protected StaticIndexRangePartitioner() /// a list of partitions public override IList>> GetOrderablePartitions(int partitionCount) { - if (partitionCount <= 0) - { - throw new ArgumentOutOfRangeException(nameof(partitionCount)); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(partitionCount); - int quotient, remainder; - quotient = SourceCount / partitionCount; - remainder = SourceCount % partitionCount; + (int quotient, int remainder) = Math.DivRem(SourceCount, partitionCount); IEnumerator>[] partitions = new IEnumerator>[partitionCount]; int lastEndIndex = -1; diff --git a/src/libraries/System.Collections.NonGeneric/src/Resources/Strings.resx b/src/libraries/System.Collections.NonGeneric/src/Resources/Strings.resx index 52690112804189..034dc81547d17d 100644 --- a/src/libraries/System.Collections.NonGeneric/src/Resources/Strings.resx +++ b/src/libraries/System.Collections.NonGeneric/src/Resources/Strings.resx @@ -78,15 +78,9 @@ Index was out of range. Must be non-negative and less than or equal to the size of the collection. - - Non-negative number required. - capacity was less than the current size. - - Queue grow factor must be between {0} and {1}. - Queue empty. diff --git a/src/libraries/System.Collections.NonGeneric/src/System/Collections/Queue.cs b/src/libraries/System.Collections.NonGeneric/src/System/Collections/Queue.cs index ced966d3aac51c..c44e57fd475862 100644 --- a/src/libraries/System.Collections.NonGeneric/src/System/Collections/Queue.cs +++ b/src/libraries/System.Collections.NonGeneric/src/System/Collections/Queue.cs @@ -51,10 +51,9 @@ public Queue(int capacity) // public Queue(int capacity, float growFactor) { - if (capacity < 0) - throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NeedNonNegNum); - if (!(growFactor >= 1.0 && growFactor <= 10.0)) - throw new ArgumentOutOfRangeException(nameof(growFactor), SR.Format(SR.ArgumentOutOfRange_QueueGrowFactor, 1, 10)); + ArgumentOutOfRangeException.ThrowIfNegative(capacity); + ArgumentOutOfRangeException.ThrowIfLessThan(growFactor, 1.0f); + ArgumentOutOfRangeException.ThrowIfGreaterThan(growFactor, 10.0f); _array = new object[capacity]; _head = 0; @@ -132,8 +131,7 @@ public virtual void CopyTo(Array array, int index) if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexMustBeLess); + ArgumentOutOfRangeException.ThrowIfNegative(index); int arrayLen = array.Length; if (arrayLen - index < _size) diff --git a/src/libraries/System.Collections.NonGeneric/src/System/Collections/SortedList.cs b/src/libraries/System.Collections.NonGeneric/src/System/Collections/SortedList.cs index c047eac7c4d502..720c1fd7a83869 100644 --- a/src/libraries/System.Collections.NonGeneric/src/System/Collections/SortedList.cs +++ b/src/libraries/System.Collections.NonGeneric/src/System/Collections/SortedList.cs @@ -93,8 +93,7 @@ public SortedList() // public SortedList(int initialCapacity) { - if (initialCapacity < 0) - throw new ArgumentOutOfRangeException(nameof(initialCapacity), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(initialCapacity); keys = new object[initialCapacity]; values = new object[initialCapacity]; @@ -337,8 +336,7 @@ public virtual void CopyTo(Array array, int arrayIndex) if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); - if (arrayIndex < 0) - throw new ArgumentOutOfRangeException(nameof(arrayIndex), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(arrayIndex); if (array.Length - arrayIndex < Count) throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); diff --git a/src/libraries/System.Collections.NonGeneric/src/System/Collections/Stack.cs b/src/libraries/System.Collections.NonGeneric/src/System/Collections/Stack.cs index 3ea4ef1126d694..e0572986c33fd3 100644 --- a/src/libraries/System.Collections.NonGeneric/src/System/Collections/Stack.cs +++ b/src/libraries/System.Collections.NonGeneric/src/System/Collections/Stack.cs @@ -40,8 +40,7 @@ public Stack() // must be a non-negative number. public Stack(int initialCapacity) { - if (initialCapacity < 0) - throw new ArgumentOutOfRangeException(nameof(initialCapacity), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(initialCapacity); if (initialCapacity < _defaultCapacity) initialCapacity = _defaultCapacity; // Simplify doubling logic in Push. @@ -118,8 +117,7 @@ public virtual void CopyTo(Array array, int index) if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); if (array.Length - index < _size) throw new ArgumentException(SR.Argument_InvalidOffLen); diff --git a/src/libraries/System.Collections.Specialized/src/Resources/Strings.resx b/src/libraries/System.Collections.Specialized/src/Resources/Strings.resx index c2d3c45d408e6a..e15dabc11d8e5e 100644 --- a/src/libraries/System.Collections.Specialized/src/Resources/Strings.resx +++ b/src/libraries/System.Collections.Specialized/src/Resources/Strings.resx @@ -60,12 +60,6 @@ An item with the same key has already been added. Key: {0} - - Argument {0} should be larger than {1}. - - - Index is less than zero. - Collection was modified after the enumerator was instantiated. diff --git a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/BitVector32.cs b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/BitVector32.cs index 60a2580cfb6fd0..7060b7c91d9deb 100644 --- a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/BitVector32.cs +++ b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/BitVector32.cs @@ -136,10 +136,7 @@ public static Section CreateSection(short maxValue, Section previous) private static Section CreateSectionHelper(short maxValue, short priorMask, short priorOffset) { - if (maxValue < 1) - { - throw new ArgumentException(SR.Format(SR.Argument_InvalidValue_TooSmall, nameof(maxValue), 1), nameof(maxValue)); - } + ArgumentOutOfRangeException.ThrowIfLessThan(maxValue, 1); short offset = (short)(priorOffset + BitOperations.PopCount((uint)(ushort)priorMask)); if (offset >= 32) diff --git a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/ListDictionary.cs b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/ListDictionary.cs index 278d8884d96100..540985d1196cd6 100644 --- a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/ListDictionary.cs +++ b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/ListDictionary.cs @@ -208,8 +208,7 @@ public void CopyTo(Array array, int index) { ArgumentNullException.ThrowIfNull(array); - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum_Index); + ArgumentOutOfRangeException.ThrowIfNegative(index); if (array.Length - index < count) throw new ArgumentException(SR.Arg_InsufficientSpace); @@ -367,8 +366,7 @@ void ICollection.CopyTo(Array array, int index) { ArgumentNullException.ThrowIfNull(array); - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum_Index); + ArgumentOutOfRangeException.ThrowIfNegative(index); for (DictionaryNode? node = _list.head; node != null; node = node.next) { diff --git a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/NameObjectCollectionBase.cs b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/NameObjectCollectionBase.cs index 82a136e8a20871..0d979fce371016 100644 --- a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/NameObjectCollectionBase.cs +++ b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/NameObjectCollectionBase.cs @@ -372,10 +372,7 @@ void ICollection.CopyTo(Array array, int index) throw new ArgumentException(SR.Arg_MultiRank, nameof(array)); } - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum_Index); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); if (array.Length - index < _entriesArray.Count) { @@ -599,10 +596,7 @@ void ICollection.CopyTo(Array array, int index) throw new ArgumentException(SR.Arg_MultiRank, nameof(array)); } - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum_Index); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); if (array.Length - index < _coll.Count) { diff --git a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/NameValueCollection.cs b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/NameValueCollection.cs index 5bb2723b95c628..cb8814663043fa 100644 --- a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/NameValueCollection.cs +++ b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/NameValueCollection.cs @@ -199,10 +199,7 @@ public void CopyTo(Array dest, int index) throw new ArgumentException(SR.Arg_MultiRank, nameof(dest)); } - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum_Index); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); if (dest.Length - index < Count) { diff --git a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/OrderedDictionary.cs b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/OrderedDictionary.cs index b116fef6df53e5..82a0c188c6bff7 100644 --- a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/OrderedDictionary.cs +++ b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/OrderedDictionary.cs @@ -310,10 +310,8 @@ public void Insert(int index, object key, object? value) { throw new NotSupportedException(SR.OrderedDictionary_ReadOnly); } - if (index > Count || index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } + ArgumentOutOfRangeException.ThrowIfGreaterThan(index, Count); + ArgumentOutOfRangeException.ThrowIfNegative(index); Hashtable objectsTable = EnsureObjectsTable(); ArrayList objectsArray = EnsureObjectsArray(); objectsTable.Add(key, value); @@ -329,10 +327,8 @@ public void RemoveAt(int index) { throw new NotSupportedException(SR.OrderedDictionary_ReadOnly); } - if (index >= Count || index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(index, Count); + ArgumentOutOfRangeException.ThrowIfNegative(index); Hashtable objectsTable = EnsureObjectsTable(); ArrayList objectsArray = EnsureObjectsArray(); object key = ((DictionaryEntry)objectsArray[index]!).Key; @@ -556,8 +552,7 @@ void ICollection.CopyTo(Array array, int index) { ArgumentNullException.ThrowIfNull(array); - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum_Index); + ArgumentOutOfRangeException.ThrowIfNegative(index); foreach (object? o in _objects) { Debug.Assert(o != null); diff --git a/src/libraries/System.Collections/src/Resources/Strings.resx b/src/libraries/System.Collections/src/Resources/Strings.resx index 37569a0b07de5c..1e6e014ed65502 100644 --- a/src/libraries/System.Collections/src/Resources/Strings.resx +++ b/src/libraries/System.Collections/src/Resources/Strings.resx @@ -66,9 +66,6 @@ Destination array is not long enough to copy all the items in the collection. Check array index and length. - - Non-negative number required. - capacity was less than the current size. diff --git a/src/libraries/System.Collections/src/System/Collections/BitArray.cs b/src/libraries/System.Collections/src/System/Collections/BitArray.cs index 1c6240f4311319..3a20f2ac63e408 100644 --- a/src/libraries/System.Collections/src/System/Collections/BitArray.cs +++ b/src/libraries/System.Collections/src/System/Collections/BitArray.cs @@ -42,10 +42,7 @@ public BitArray(int length) =========================================================================*/ public BitArray(int length, bool defaultValue) { - if (length < 0) - { - throw new ArgumentOutOfRangeException(nameof(length), length, SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(length); m_array = new int[GetInt32ArrayLengthFromBitLength(length)]; m_length = length; @@ -568,10 +565,7 @@ public BitArray RightShift(int count) { if (count <= 0) { - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(count); _version++; return this; @@ -635,10 +629,7 @@ public BitArray LeftShift(int count) { if (count <= 0) { - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(count); _version++; return this; @@ -690,10 +681,7 @@ public int Length } set { - if (value < 0) - { - throw new ArgumentOutOfRangeException(nameof(value), value, SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(value); int newints = GetInt32ArrayLengthFromBitLength(value); if (newints > m_array.Length || newints + _ShrinkThreshold < m_array.Length) @@ -725,8 +713,7 @@ public unsafe void CopyTo(Array array, int index) { ArgumentNullException.ThrowIfNull(array); - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/LinkedList.cs b/src/libraries/System.Collections/src/System/Collections/Generic/LinkedList.cs index 7c41bb8875ef09..0e99312eba2895 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/LinkedList.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/LinkedList.cs @@ -192,10 +192,7 @@ public void CopyTo(T[] array, int index) { ArgumentNullException.ThrowIfNull(array); - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); if (index > array.Length) { @@ -460,10 +457,7 @@ void ICollection.CopyTo(Array array, int index) throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array)); } - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); if (array.Length - index < Count) { diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/PriorityQueue.cs b/src/libraries/System.Collections/src/System/Collections/Generic/PriorityQueue.cs index 6792c4922a4491..67f2ae3c176d13 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/PriorityQueue.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/PriorityQueue.cs @@ -113,11 +113,7 @@ public PriorityQueue(IComparer? comparer) /// public PriorityQueue(int initialCapacity, IComparer? comparer) { - if (initialCapacity < 0) - { - throw new ArgumentOutOfRangeException( - nameof(initialCapacity), initialCapacity, SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(initialCapacity); _nodes = new (TElement, TPriority)[initialCapacity]; _comparer = InitializeComparer(comparer); @@ -531,10 +527,7 @@ public void Clear() /// The current capacity of the . public int EnsureCapacity(int capacity) { - if (capacity < 0) - { - throw new ArgumentOutOfRangeException(nameof(capacity), capacity, SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(capacity); if (_nodes.Length < capacity) { diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/SortedDictionary.cs b/src/libraries/System.Collections/src/System/Collections/Generic/SortedDictionary.cs index 3c23ba2d07ec08..629916ea90468f 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/SortedDictionary.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/SortedDictionary.cs @@ -562,10 +562,7 @@ public void CopyTo(TKey[] array, int index) { ArgumentNullException.ThrowIfNull(array); - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); if (array.Length - index < Count) { @@ -589,10 +586,7 @@ void ICollection.CopyTo(Array array, int index) throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array)); } - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); if (array.Length - index < _dictionary.Count) { @@ -736,10 +730,7 @@ public void CopyTo(TValue[] array, int index) { ArgumentNullException.ThrowIfNull(array); - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); if (array.Length - index < Count) { @@ -763,10 +754,7 @@ void ICollection.CopyTo(Array array, int index) throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array)); } - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); if (array.Length - index < _dictionary.Count) { diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/SortedList.cs b/src/libraries/System.Collections/src/System/Collections/Generic/SortedList.cs index 4588556af29328..3204094bf71ecd 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/SortedList.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/SortedList.cs @@ -87,8 +87,7 @@ public SortedList() // public SortedList(int capacity) { - if (capacity < 0) - throw new ArgumentOutOfRangeException(nameof(capacity), capacity, SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(capacity); keys = new TKey[capacity]; values = new TValue[capacity]; comparer = Comparer.Default; diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.cs b/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.cs index a298779f293ff3..57f3ed24e596ef 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.cs @@ -511,15 +511,9 @@ public void CopyTo(T[] array, int index, int count) { ArgumentNullException.ThrowIfNull(array); - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(count); if (count > array.Length - index) { @@ -554,10 +548,7 @@ void ICollection.CopyTo(Array array, int index) throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array)); } - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); if (array.Length - index < Count) { diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/Stack.cs b/src/libraries/System.Collections/src/System/Collections/Generic/Stack.cs index 3c3938c60d88b9..181a619a514327 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/Stack.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/Stack.cs @@ -41,8 +41,7 @@ public Stack() // must be a non-negative number. public Stack(int capacity) { - if (capacity < 0) - throw new ArgumentOutOfRangeException(nameof(capacity), capacity, SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(capacity); _array = new T[capacity]; } @@ -292,10 +291,7 @@ private void PushWithResize(T item) /// The new capacity of this stack. public int EnsureCapacity(int capacity) { - if (capacity < 0) - { - throw new ArgumentOutOfRangeException(nameof(capacity), capacity, SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(capacity); if (_array.Length < capacity) { diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Schema/ColumnAttribute.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Schema/ColumnAttribute.cs index f871d3d5c09819..66a112ef8b45d7 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Schema/ColumnAttribute.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Schema/ColumnAttribute.cs @@ -49,10 +49,7 @@ public int Order get => _order; set { - if (value < 0) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } + ArgumentOutOfRangeException.ThrowIfNegative(value); _order = value; } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/ContextStack.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/ContextStack.cs index dd62aa67ab8bd1..b0579d8fbc232e 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/ContextStack.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/ContextStack.cs @@ -49,10 +49,7 @@ public object? this[int level] { get { - if (level < 0) - { - throw new ArgumentOutOfRangeException(nameof(level)); - } + ArgumentOutOfRangeException.ThrowIfNegative(level); if (_contextStack != null && level < _contextStack.Count) { return _contextStack[_contextStack.Count - 1 - level]; diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MaskedTextProvider.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MaskedTextProvider.cs index 20c083f9ff1527..6f62c5fce4b896 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MaskedTextProvider.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MaskedTextProvider.cs @@ -1212,7 +1212,6 @@ public bool InsertAt(char input, int position) if (position < 0 || position >= _testString.Length) { return false; - //throw new ArgumentOutOfRangeException("position"); } return InsertAt(input.ToString(), position); @@ -1258,7 +1257,6 @@ public bool InsertAt(string input, int position, out int testPosition, out Maske testPosition = position; resultHint = MaskedTextResultHint.PositionOutOfRange; return false; - //throw new ArgumentOutOfRangeException("position"); } return InsertAtInt(input, position, out testPosition, out resultHint, false); @@ -1406,7 +1404,6 @@ public bool IsAvailablePosition(int position) if (position < 0 || position >= _testString.Length) { return false; - //throw new ArgumentOutOfRangeException("position"); } CharDescriptor chDex = _stringDescriptor[position]; @@ -1421,7 +1418,6 @@ public bool IsEditPosition(int position) if (position < 0 || position >= _testString.Length) { return false; - //throw new ArgumentOutOfRangeException("position"); } CharDescriptor chDex = _stringDescriptor[position]; @@ -1542,7 +1538,6 @@ public bool RemoveAt(int startPosition, int endPosition, out int testPosition, o testPosition = endPosition; resultHint = MaskedTextResultHint.PositionOutOfRange; return false; - //throw new ArgumentOutOfRangeException("endPosition"); } if (startPosition < 0 || startPosition > endPosition) @@ -1550,7 +1545,6 @@ public bool RemoveAt(int startPosition, int endPosition, out int testPosition, o testPosition = startPosition; resultHint = MaskedTextResultHint.PositionOutOfRange; return false; - //throw new ArgumentOutOfRangeException("startPosition"); } return RemoveAtInt(startPosition, endPosition, out testPosition, out resultHint, /*testOnly*/ false); @@ -1706,7 +1700,6 @@ public bool Replace(char input, int position, out int testPosition, out MaskedTe testPosition = position; resultHint = MaskedTextResultHint.PositionOutOfRange; return false; - //throw new ArgumentOutOfRangeException("position"); } testPosition = position; @@ -1751,7 +1744,6 @@ public bool Replace(char input, int startPosition, int endPosition, out int test testPosition = endPosition; resultHint = MaskedTextResultHint.PositionOutOfRange; return false; - //throw new ArgumentOutOfRangeException("endPosition"); } if (startPosition < 0 || startPosition > endPosition) @@ -1759,7 +1751,6 @@ public bool Replace(char input, int startPosition, int endPosition, out int test testPosition = startPosition; resultHint = MaskedTextResultHint.PositionOutOfRange; return false; - //throw new ArgumentOutOfRangeException("startPosition"); } if (startPosition == endPosition) @@ -1800,7 +1791,6 @@ public bool Replace(string input, int position, out int testPosition, out Masked testPosition = position; resultHint = MaskedTextResultHint.PositionOutOfRange; return false; - //throw new ArgumentOutOfRangeException("position"); } if (input.Length == 0) // remove the character at position. @@ -1836,7 +1826,6 @@ public bool Replace(string input, int startPosition, int endPosition, out int te testPosition = endPosition; resultHint = MaskedTextResultHint.PositionOutOfRange; return false; - //throw new ArgumentOutOfRangeException("endPosition"); } if (startPosition < 0 || startPosition > endPosition) @@ -1844,7 +1833,6 @@ public bool Replace(string input, int startPosition, int endPosition, out int te testPosition = startPosition; resultHint = MaskedTextResultHint.PositionOutOfRange; return false; - //throw new ArgumentOutOfRangeException("startPosition"); } if (input.Length == 0) // remove character at position. @@ -2592,13 +2580,11 @@ public string ToString(bool ignorePasswordChar, bool includePrompt, bool include if (startPosition < 0) { startPosition = 0; - //throw new ArgumentOutOfRangeException("startPosition"); } if (startPosition >= _testString.Length) { return string.Empty; - //throw new ArgumentOutOfRangeException("startPosition"); } int maxLength = _testString.Length - startPosition; @@ -2606,7 +2592,6 @@ public string ToString(bool ignorePasswordChar, bool includePrompt, bool include if (length > maxLength) { length = maxLength; - //throw new ArgumentOutOfRangeException("length"); } if (!IsPassword || ignorePasswordChar) // we may not need to format the text... diff --git a/src/libraries/System.Console/src/Resources/Strings.resx b/src/libraries/System.Console/src/Resources/Strings.resx index 980613c28a5ffd..af0720ca50d09a 100644 --- a/src/libraries/System.Console/src/Resources/Strings.resx +++ b/src/libraries/System.Console/src/Resources/Strings.resx @@ -122,12 +122,6 @@ The new console window size would force the console buffer size to be too large. - - Non-negative number required. - - - Positive number required. - Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection. diff --git a/src/libraries/System.Console/src/System/Console.cs b/src/libraries/System.Console/src/System/Console.cs index 1c9b3a28aea94a..cecef0a7e5b1fa 100644 --- a/src/libraries/System.Console/src/System/Console.cs +++ b/src/libraries/System.Console/src/System/Console.cs @@ -406,10 +406,7 @@ public static int WindowWidth throw new IOException(SR.InvalidOperation_SetWindowSize); } - if (value <= 0) - { - throw new ArgumentOutOfRangeException(nameof(value), value, SR.ArgumentOutOfRange_NeedPosNum); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(value); ConsolePal.WindowWidth = value; } @@ -429,10 +426,7 @@ public static int WindowHeight throw new IOException(SR.InvalidOperation_SetWindowSize); } - if (value <= 0) - { - throw new ArgumentOutOfRangeException(nameof(value), value, SR.ArgumentOutOfRange_NeedPosNum); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(value); ConsolePal.WindowHeight = value; } @@ -455,15 +449,8 @@ public static void SetWindowSize(int width, int height) throw new IOException(SR.InvalidOperation_SetWindowSize); } - if (width <= 0) - { - throw new ArgumentOutOfRangeException(nameof(width), width, SR.ArgumentOutOfRange_NeedPosNum); - } - - if (height <= 0) - { - throw new ArgumentOutOfRangeException(nameof(height), height, SR.ArgumentOutOfRange_NeedPosNum); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); ConsolePal.SetWindowSize(width, height); } @@ -662,10 +649,7 @@ public static Stream OpenStandardInput() public static Stream OpenStandardInput(int bufferSize) { // bufferSize is ignored, other than in argument validation, even in the .NET Framework - if (bufferSize < 0) - { - throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(bufferSize); return ConsolePal.OpenStandardInput(); } @@ -677,10 +661,7 @@ public static Stream OpenStandardOutput() public static Stream OpenStandardOutput(int bufferSize) { // bufferSize is ignored, other than in argument validation, even in the .NET Framework - if (bufferSize < 0) - { - throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(bufferSize); return ConsolePal.OpenStandardOutput(); } @@ -692,10 +673,7 @@ public static Stream OpenStandardError() public static Stream OpenStandardError(int bufferSize) { // bufferSize is ignored, other than in argument validation, even in the .NET Framework - if (bufferSize < 0) - { - throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(bufferSize); return ConsolePal.OpenStandardError(); } diff --git a/src/libraries/System.Console/src/System/ConsolePal.Windows.cs b/src/libraries/System.Console/src/System/ConsolePal.Windows.cs index d8e43d55a9cce1..820e2fc3991025 100644 --- a/src/libraries/System.Console/src/System/ConsolePal.Windows.cs +++ b/src/libraries/System.Console/src/System/ConsolePal.Windows.cs @@ -651,8 +651,7 @@ public static void Beep(int frequency, int duration) if (frequency < MinBeepFrequency || frequency > MaxBeepFrequency) throw new ArgumentOutOfRangeException(nameof(frequency), frequency, SR.Format(SR.ArgumentOutOfRange_BeepFrequency, MinBeepFrequency, MaxBeepFrequency)); - if (duration <= 0) - throw new ArgumentOutOfRangeException(nameof(duration), duration, SR.ArgumentOutOfRange_NeedPosNum); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(duration); Interop.Kernel32.Beep(frequency, duration); } diff --git a/src/libraries/System.Console/src/System/IO/SyncTextReader.cs b/src/libraries/System.Console/src/System/IO/SyncTextReader.cs index aa9fe7f2264621..359f7ac5b9d90e 100644 --- a/src/libraries/System.Console/src/System/IO/SyncTextReader.cs +++ b/src/libraries/System.Console/src/System/IO/SyncTextReader.cs @@ -119,8 +119,8 @@ public override Task ReadBlockAsync(char[] buffer, int index, int count) { ArgumentNullException.ThrowIfNull(buffer); - if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (buffer.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); @@ -131,8 +131,8 @@ public override Task ReadAsync(char[] buffer, int index, int count) { ArgumentNullException.ThrowIfNull(buffer); - if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (buffer.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBytes.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBytes.cs index ff1e6eb150c91d..1aa58f5da51c52 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBytes.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBytes.cs @@ -197,8 +197,8 @@ public byte this[long offset] { get { - if (offset < 0 || offset >= Length) - throw new ArgumentOutOfRangeException(nameof(offset)); + ArgumentOutOfRangeException.ThrowIfNegative(offset); + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(offset, Length); _rgbWorkBuf ??= new byte[1]; @@ -260,8 +260,7 @@ public void SetNull() // If the SqlBytes is Null, setLength will make it non-Null. public void SetLength(long value) { - if (value < 0) - throw new ArgumentOutOfRangeException(nameof(value)); + ArgumentOutOfRangeException.ThrowIfNegative(value); if (FStream()) { @@ -276,13 +275,14 @@ public void SetLength(long value) if (null == _rgbBuf) throw new SqlTypeException(SR.SqlMisc_NoBufferMessage); - if (value > _rgbBuf.Length) - throw new ArgumentOutOfRangeException(nameof(value)); + ArgumentOutOfRangeException.ThrowIfGreaterThan(value, _rgbBuf.Length); - else if (IsNull) + if (IsNull) + { // At this point we know that value is small enough // Go back in buffer mode _state = SqlBytesCharsState.Buffer; + } _lCurLen = value; } @@ -299,14 +299,14 @@ public long Read(long offset, byte[] buffer, int offsetInBuffer, int count) // Validate the arguments ArgumentNullException.ThrowIfNull(buffer); - if (offset > Length || offset < 0) - throw new ArgumentOutOfRangeException(nameof(offset)); + ArgumentOutOfRangeException.ThrowIfGreaterThan(offset, Length); + ArgumentOutOfRangeException.ThrowIfNegative(offset); - if (offsetInBuffer > buffer.Length || offsetInBuffer < 0) - throw new ArgumentOutOfRangeException(nameof(offsetInBuffer)); + ArgumentOutOfRangeException.ThrowIfGreaterThan(offsetInBuffer, Length); + ArgumentOutOfRangeException.ThrowIfNegative(offsetInBuffer); - if (count < 0 || count > buffer.Length - offsetInBuffer) - throw new ArgumentOutOfRangeException(nameof(count)); + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfGreaterThan(count, buffer.Length - offsetInBuffer); // Adjust count based on data length if (count > Length - offset) @@ -347,16 +347,15 @@ public void Write(long offset, byte[] buffer, int offsetInBuffer, int count) if (_rgbBuf == null) throw new SqlTypeException(SR.SqlMisc_NoBufferMessage); - if (offset < 0) - throw new ArgumentOutOfRangeException(nameof(offset)); + ArgumentOutOfRangeException.ThrowIfNegative(offset); if (offset > _rgbBuf.Length) throw new SqlTypeException(SR.SqlMisc_BufferInsufficientMessage); - if (offsetInBuffer < 0 || offsetInBuffer > buffer.Length) - throw new ArgumentOutOfRangeException(nameof(offsetInBuffer)); + ArgumentOutOfRangeException.ThrowIfNegative(offsetInBuffer); + ArgumentOutOfRangeException.ThrowIfGreaterThan(offsetInBuffer, buffer.Length); - if (count < 0 || count > buffer.Length - offsetInBuffer) - throw new ArgumentOutOfRangeException(nameof(count)); + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfGreaterThan(count, buffer.Length - offsetInBuffer); if (count > _rgbBuf.Length - offset) throw new SqlTypeException(SR.SqlMisc_BufferInsufficientMessage); @@ -642,10 +641,9 @@ public override long Position set { CheckIfStreamClosed("set_Position"); - if (value < 0 || value > _sb.Length) - throw new ArgumentOutOfRangeException(nameof(value)); - else - _lPosition = value; + ArgumentOutOfRangeException.ThrowIfNegative(value); + ArgumentOutOfRangeException.ThrowIfGreaterThan(value, _sb.Length); + _lPosition = value; } } @@ -662,22 +660,22 @@ public override long Seek(long offset, SeekOrigin origin) switch (origin) { case SeekOrigin.Begin: - if (offset < 0 || offset > _sb.Length) - throw new ArgumentOutOfRangeException(nameof(offset)); + ArgumentOutOfRangeException.ThrowIfNegative(offset); + ArgumentOutOfRangeException.ThrowIfGreaterThan(offset, _sb.Length); _lPosition = offset; break; case SeekOrigin.Current: lPosition = _lPosition + offset; - if (lPosition < 0 || lPosition > _sb.Length) - throw new ArgumentOutOfRangeException(nameof(offset)); + ArgumentOutOfRangeException.ThrowIfNegative(lPosition, nameof(offset)); + ArgumentOutOfRangeException.ThrowIfGreaterThan(lPosition, _sb.Length, nameof(offset)); _lPosition = lPosition; break; case SeekOrigin.End: lPosition = _sb.Length + offset; - if (lPosition < 0 || lPosition > _sb.Length) - throw new ArgumentOutOfRangeException(nameof(offset)); + ArgumentOutOfRangeException.ThrowIfNegative(lPosition, nameof(offset)); + ArgumentOutOfRangeException.ThrowIfGreaterThan(lPosition, _sb.Length, nameof(offset)); _lPosition = lPosition; break; diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLChars.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLChars.cs index 848c847f4d4483..85fcf731ec69a6 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLChars.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLChars.cs @@ -192,8 +192,8 @@ public char this[long offset] { get { - if (offset < 0 || offset >= Length) - throw new ArgumentOutOfRangeException(nameof(offset)); + ArgumentOutOfRangeException.ThrowIfNegative(offset); + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(offset, Length); _rgchWorkBuf ??= new char[1]; @@ -256,8 +256,7 @@ public void SetNull() // If the SqlChars is Null, setLength will make it non-Null. public void SetLength(long value) { - if (value < 0) - throw new ArgumentOutOfRangeException(nameof(value)); + ArgumentOutOfRangeException.ThrowIfNegative(value); if (FStream()) { @@ -272,10 +271,9 @@ public void SetLength(long value) if (null == _rgchBuf) throw new SqlTypeException(SR.SqlMisc_NoBufferMessage); - if (value > _rgchBuf.Length) - throw new ArgumentOutOfRangeException(nameof(value)); + ArgumentOutOfRangeException.ThrowIfGreaterThan(value, _rgchBuf.Length); - else if (IsNull) + if (IsNull) // At this point we know that value is small enough // Go back in buffer mode _state = SqlBytesCharsState.Buffer; @@ -296,14 +294,14 @@ public long Read(long offset, char[] buffer, int offsetInBuffer, int count) // Validate the arguments ArgumentNullException.ThrowIfNull(buffer); - if (offset > Length || offset < 0) - throw new ArgumentOutOfRangeException(nameof(offset)); + ArgumentOutOfRangeException.ThrowIfGreaterThan(offset, Length); + ArgumentOutOfRangeException.ThrowIfNegative(offset); - if (offsetInBuffer > buffer.Length || offsetInBuffer < 0) - throw new ArgumentOutOfRangeException(nameof(offsetInBuffer)); + ArgumentOutOfRangeException.ThrowIfGreaterThan(offsetInBuffer, buffer.Length); + ArgumentOutOfRangeException.ThrowIfNegative(offsetInBuffer); - if (count < 0 || count > buffer.Length - offsetInBuffer) - throw new ArgumentOutOfRangeException(nameof(count)); + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfGreaterThan(count, buffer.Length - offsetInBuffer); // Adjust count based on data length if (count > Length - offset) @@ -345,16 +343,16 @@ public void Write(long offset, char[] buffer, int offsetInBuffer, int count) if (_rgchBuf == null) throw new SqlTypeException(SR.SqlMisc_NoBufferMessage); - if (offset < 0) - throw new ArgumentOutOfRangeException(nameof(offset)); + ArgumentOutOfRangeException.ThrowIfNegative(offset); + if (offset > _rgchBuf.Length) throw new SqlTypeException(SR.SqlMisc_BufferInsufficientMessage); - if (offsetInBuffer < 0 || offsetInBuffer > buffer.Length) - throw new ArgumentOutOfRangeException(nameof(offsetInBuffer)); + ArgumentOutOfRangeException.ThrowIfNegative(offsetInBuffer); + ArgumentOutOfRangeException.ThrowIfGreaterThan(offsetInBuffer, buffer.Length); - if (count < 0 || count > buffer.Length - offsetInBuffer) - throw new ArgumentOutOfRangeException(nameof(count)); + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfGreaterThan(count, buffer.Length - offsetInBuffer); if (count > _rgchBuf.Length - offset) throw new SqlTypeException(SR.SqlMisc_BufferInsufficientMessage); diff --git a/src/libraries/System.Diagnostics.Process/src/Resources/Strings.resx b/src/libraries/System.Diagnostics.Process/src/Resources/Strings.resx index 35798057fc6df7..08a17e891e065f 100644 --- a/src/libraries/System.Diagnostics.Process/src/Resources/Strings.resx +++ b/src/libraries/System.Diagnostics.Process/src/Resources/Strings.resx @@ -296,9 +296,6 @@ String contains invalid Unicode code points. - - Non-negative number required. - The Process object must have the UseShellExecute property set to false in order to start a process as a user. diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.FreeBSD.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.FreeBSD.cs index 566ff748e2d4b0..a1b9583cebc41e 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.FreeBSD.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.FreeBSD.cs @@ -23,10 +23,7 @@ internal static string GetProcPath(int processId) internal static ProcessInfo? CreateProcessInfo(int pid, string? processNameFilter = null) { // Negative PIDs aren't valid - if (pid < 0) - { - throw new ArgumentOutOfRangeException(nameof(pid)); - } + ArgumentOutOfRangeException.ThrowIfNegative(pid); // Try to get the task info. This can fail if the user permissions don't permit // this user context to query the specified process diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.OSX.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.OSX.cs index 621546e891abfd..92c16de7217abd 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.OSX.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.OSX.cs @@ -23,10 +23,7 @@ private static string GetProcPath(int processId) internal static ProcessInfo? CreateProcessInfo(int pid, string? processNameFilter = null) { // Negative PIDs aren't valid - if (pid < 0) - { - throw new ArgumentOutOfRangeException(nameof(pid)); - } + ArgumentOutOfRangeException.ThrowIfNegative(pid); ProcessInfo procInfo; diff --git a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/GnuTarEntry.cs b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/GnuTarEntry.cs index 11e3b77c5f8f2d..e8acadd9fcf4ba 100644 --- a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/GnuTarEntry.cs +++ b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/GnuTarEntry.cs @@ -98,10 +98,7 @@ public DateTimeOffset AccessTime get => _header._aTime; set { - if (value < DateTimeOffset.UnixEpoch) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } + ArgumentOutOfRangeException.ThrowIfLessThan(value, DateTimeOffset.UnixEpoch); _header._aTime = value; } } @@ -115,10 +112,7 @@ public DateTimeOffset ChangeTime get => _header._cTime; set { - if (value < DateTimeOffset.UnixEpoch) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } + ArgumentOutOfRangeException.ThrowIfLessThan(value, DateTimeOffset.UnixEpoch); _header._cTime = value; } } diff --git a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarEntry.cs b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarEntry.cs index e7d6761c592c8b..89b214d91dc738 100644 --- a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarEntry.cs +++ b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarEntry.cs @@ -98,10 +98,7 @@ public DateTimeOffset ModificationTime get => _header._mTime; set { - if (value < DateTimeOffset.UnixEpoch) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } + ArgumentOutOfRangeException.ThrowIfLessThan(value, DateTimeOffset.UnixEpoch); _header._mTime = value; } } diff --git a/src/libraries/System.IO.Compression/src/Resources/Strings.resx b/src/libraries/System.IO.Compression/src/Resources/Strings.resx index 66113dec492eb3..9de1d9498c76b6 100644 --- a/src/libraries/System.IO.Compression/src/Resources/Strings.resx +++ b/src/libraries/System.IO.Compression/src/Resources/Strings.resx @@ -119,9 +119,6 @@ Enum value was out of legal range. - - Positive number required. - Reading from the compression stream is not supported. diff --git a/src/libraries/System.IO.IsolatedStorage/src/Resources/Strings.resx b/src/libraries/System.IO.IsolatedStorage/src/Resources/Strings.resx index 4a82720401dc57..dd57494745f39b 100644 --- a/src/libraries/System.IO.IsolatedStorage/src/Resources/Strings.resx +++ b/src/libraries/System.IO.IsolatedStorage/src/Resources/Strings.resx @@ -94,9 +94,6 @@ The Site scope is currently not supported. - - Non-negative number required. - Could not find a part of the path '{0}'. diff --git a/src/libraries/System.IO.MemoryMappedFiles/src/Resources/Strings.resx b/src/libraries/System.IO.MemoryMappedFiles/src/Resources/Strings.resx index a6c978a3c4977a..93968ec15100aa 100644 --- a/src/libraries/System.IO.MemoryMappedFiles/src/Resources/Strings.resx +++ b/src/libraries/System.IO.MemoryMappedFiles/src/Resources/Strings.resx @@ -117,9 +117,6 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - Non-negative number required. - Unable to find the specified file. diff --git a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.cs b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.cs index 7945d8e741ddf9..ade6cb8b75a362 100644 --- a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.cs +++ b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.cs @@ -374,10 +374,7 @@ public MemoryMappedViewStream CreateViewStream(long offset, long size) public MemoryMappedViewStream CreateViewStream(long offset, long size, MemoryMappedFileAccess access) { - if (offset < 0) - { - throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(offset); if (size < 0) { @@ -411,10 +408,7 @@ public MemoryMappedViewAccessor CreateViewAccessor(long offset, long size) public MemoryMappedViewAccessor CreateViewAccessor(long offset, long size, MemoryMappedFileAccess access) { - if (offset < 0) - { - throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(offset); if (size < 0) { diff --git a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.Unix.cs b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.Unix.cs index 917058aee933d8..f3f0df8b022386 100644 --- a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.Unix.cs +++ b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.Unix.cs @@ -12,10 +12,7 @@ public static MemoryMappedView CreateView( SafeMemoryMappedFileHandle memMappedFileHandle, MemoryMappedFileAccess access, long requestedOffset, long requestedSize) { - if (requestedOffset > memMappedFileHandle._capacity) - { - throw new ArgumentOutOfRangeException("offset"); - } + ArgumentOutOfRangeException.ThrowIfGreaterThan(requestedOffset, memMappedFileHandle._capacity, "offset"); if (requestedSize > MaxProcessAddressSpace) { throw new IOException(SR.ArgumentOutOfRange_CapacityLargerThanLogicalAddressSpaceNotAllowed); @@ -24,10 +21,7 @@ public static MemoryMappedView CreateView( { throw new UnauthorizedAccessException(); } - if (memMappedFileHandle.IsClosed) - { - throw new ObjectDisposedException(nameof(MemoryMappedFile)); - } + ObjectDisposedException.ThrowIf(memMappedFileHandle.IsClosed, memMappedFileHandle); if (requestedSize == MemoryMappedFile.DefaultSize) { @@ -83,7 +77,7 @@ public static MemoryMappedView CreateView( Interop.Sys.MemoryMappedProtections viewProtForCreation = GetProtections(access, forVerification: false); // Create the map - IntPtr addr = IntPtr.Zero; + IntPtr addr; if (nativeSize > 0) { addr = Interop.Sys.MMap( diff --git a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedViewStream.cs b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedViewStream.cs index 522e784d81520b..6085562fbb030a 100644 --- a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedViewStream.cs +++ b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedViewStream.cs @@ -24,10 +24,7 @@ internal MemoryMappedViewStream(MemoryMappedView view) public override void SetLength(long value) { - if (value < 0) - { - throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(value); throw new NotSupportedException(SR.NotSupported_MMViewStreamsFixedLength); } diff --git a/src/libraries/System.IO.Pipes/src/Resources/Strings.resx b/src/libraries/System.IO.Pipes/src/Resources/Strings.resx index 4d2752edab8b07..1dacf223fda743 100644 --- a/src/libraries/System.IO.Pipes/src/Resources/Strings.resx +++ b/src/libraries/System.IO.Pipes/src/Resources/Strings.resx @@ -117,9 +117,6 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - Non-negative number required. - Invalid PipeAccessRights value. @@ -159,9 +156,6 @@ maxNumberOfServerInstances must either be a value between 1 and 254, or NamedPipeServerStream.MaxAllowedServerInstances (to obtain the maximum number allowed by system resources). - - Positive number required. - Pipe hasn't been connected yet. diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.cs index bca963410f9103..a0652e73673fee 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.cs @@ -107,14 +107,8 @@ private void ValidateParameters( { throw new ArgumentOutOfRangeException(nameof(options), SR.ArgumentOutOfRange_OptionsInvalid); } - if (inBufferSize < 0) - { - throw new ArgumentOutOfRangeException(nameof(inBufferSize), SR.ArgumentOutOfRange_NeedNonNegNum); - } - if (outBufferSize < 0) - { - throw new ArgumentOutOfRangeException(nameof(outBufferSize), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(inBufferSize); + ArgumentOutOfRangeException.ThrowIfNegative(outBufferSize); if ((maxNumberOfServerInstances < 1 || maxNumberOfServerInstances > 254) && (maxNumberOfServerInstances != MaxAllowedServerInstances)) { // win32 allows fixed values of 1-254 or 255 to mean max allowed by system. We expose 255 as -1 (unlimited) diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.cs index 6df150682be21b..8e7790d463a314 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.cs @@ -34,10 +34,7 @@ protected PipeStream(PipeDirection direction, int bufferSize) { throw new ArgumentOutOfRangeException(nameof(direction), SR.ArgumentOutOfRange_DirectionModeInOutOrInOut); } - if (bufferSize < 0) - { - throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(bufferSize); Init(direction, PipeTransmissionMode.Byte, (uint)bufferSize); } @@ -52,10 +49,7 @@ protected PipeStream(PipeDirection direction, PipeTransmissionMode transmissionM { throw new ArgumentOutOfRangeException(nameof(transmissionMode), SR.ArgumentOutOfRange_TransmissionModeByteOrMsg); } - if (outBufferSize < 0) - { - throw new ArgumentOutOfRangeException(nameof(outBufferSize), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(outBufferSize); Init(direction, transmissionMode, (uint)outBufferSize); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/ContractUtils.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/ContractUtils.cs index d0288f7736342f..a0a6adc2491114 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/ContractUtils.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/ContractUtils.cs @@ -138,10 +138,9 @@ public static void RequiresArrayRange(IList array, int offset, int count, Debug.Assert(!string.IsNullOrEmpty(countName)); Debug.Assert(array != null); - if (count < 0) - throw new ArgumentOutOfRangeException(countName); - if (offset < 0 || array.Count - offset < count) - throw new ArgumentOutOfRangeException(offsetName); + ArgumentOutOfRangeException.ThrowIfNegative(count, countName); + ArgumentOutOfRangeException.ThrowIfNegative(offset, offsetName); + ArgumentOutOfRangeException.ThrowIfLessThan(array.Count - offset, count, offsetName); } } } diff --git a/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/ReadOnlyCollectionBuilder.cs b/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/ReadOnlyCollectionBuilder.cs index 3ca5ed06a59c96..fb57a88b3da88a 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/ReadOnlyCollectionBuilder.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/ReadOnlyCollectionBuilder.cs @@ -36,8 +36,7 @@ public ReadOnlyCollectionBuilder() /// Initial capacity of the builder. public ReadOnlyCollectionBuilder(int capacity) { - if (capacity < 0) - throw new ArgumentOutOfRangeException(nameof(capacity)); + ArgumentOutOfRangeException.ThrowIfNegative(capacity); _items = new T[capacity]; } @@ -80,8 +79,7 @@ public int Capacity get { return _items.Length; } set { - if (value < _size) - throw new ArgumentOutOfRangeException(nameof(value)); + ArgumentOutOfRangeException.ThrowIfLessThan(value, _size); if (value != _items.Length) { @@ -126,8 +124,7 @@ public int IndexOf(T item) /// The object to insert into the . public void Insert(int index, T item) { - if (index > _size) - throw new ArgumentOutOfRangeException(nameof(index)); + ArgumentOutOfRangeException.ThrowIfGreaterThan(index, _size); if (_size == _items.Length) { @@ -169,15 +166,13 @@ public T this[int index] { get { - if (index >= _size) - throw new ArgumentOutOfRangeException(nameof(index)); + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(index, _size); return _items[index]; } set { - if (index >= _size) - throw new ArgumentOutOfRangeException(nameof(index)); + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(index, _size); _items[index] = value; _version++; @@ -384,10 +379,8 @@ public void Reverse() /// The number of elements in the range to reverse. public void Reverse(int index, int count) { - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index)); - if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count)); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); Array.Reverse(_items, index, count); _version++; diff --git a/src/libraries/System.Linq.Parallel/src/System/Linq/ParallelEnumerable.cs b/src/libraries/System.Linq.Parallel/src/System/Linq/ParallelEnumerable.cs index 81de50225cbd8b..1b6499120fa552 100644 --- a/src/libraries/System.Linq.Parallel/src/System/Linq/ParallelEnumerable.cs +++ b/src/libraries/System.Linq.Parallel/src/System/Linq/ParallelEnumerable.cs @@ -434,7 +434,7 @@ public static ParallelQuery Range(int start, int count) /// public static ParallelQuery Repeat(TResult element, int count) { - if (count < 0) throw new ArgumentOutOfRangeException(nameof(count)); + ArgumentOutOfRangeException.ThrowIfNegative(count); return new RepeatEnumerable(element, count); } @@ -5905,7 +5905,7 @@ public static TSource ElementAt(this ParallelQuery source, int { ArgumentNullException.ThrowIfNull(source); - if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); + ArgumentOutOfRangeException.ThrowIfNegative(index); // @PERF: there are obvious optimization opportunities for indexable data sources, // since we can just seek to the element requested. diff --git a/src/libraries/System.Net.Http/src/Resources/Strings.resx b/src/libraries/System.Net.Http/src/Resources/Strings.resx index b67f971d9519e1..7b692d3f37c3f2 100644 --- a/src/libraries/System.Net.Http/src/Resources/Strings.resx +++ b/src/libraries/System.Net.Http/src/Resources/Strings.resx @@ -360,12 +360,6 @@ The HTTP response headers length exceeded the set limit of {0} bytes. - - Non-negative number required. - - - Positive number required. - Stream does not support reading. diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ContentRangeHeaderValue.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ContentRangeHeaderValue.cs index f74d5015b5fcde..5da51c151af617 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ContentRangeHeaderValue.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ContentRangeHeaderValue.cs @@ -55,18 +55,11 @@ public ContentRangeHeaderValue(long from, long to, long length) { // Scenario: "Content-Range: bytes 12-34/5678" - if (length < 0) - { - throw new ArgumentOutOfRangeException(nameof(length)); - } - if ((to < 0) || (to > length)) - { - throw new ArgumentOutOfRangeException(nameof(to)); - } - if ((from < 0) || (from > to)) - { - throw new ArgumentOutOfRangeException(nameof(from)); - } + ArgumentOutOfRangeException.ThrowIfNegative(length); + ArgumentOutOfRangeException.ThrowIfNegative(to); + ArgumentOutOfRangeException.ThrowIfGreaterThan(to, length); + ArgumentOutOfRangeException.ThrowIfNegative(from); + ArgumentOutOfRangeException.ThrowIfGreaterThan(from, to); _from = from; _to = to; @@ -78,10 +71,7 @@ public ContentRangeHeaderValue(long length) { // Scenario: "Content-Range: bytes */1234" - if (length < 0) - { - throw new ArgumentOutOfRangeException(nameof(length)); - } + ArgumentOutOfRangeException.ThrowIfNegative(length); _length = length; _unit = HeaderUtilities.BytesUnit; @@ -91,14 +81,9 @@ public ContentRangeHeaderValue(long from, long to) { // Scenario: "Content-Range: bytes 12-34/*" - if (to < 0) - { - throw new ArgumentOutOfRangeException(nameof(to)); - } - if ((from < 0) || (from > to)) - { - throw new ArgumentOutOfRangeException(nameof(from)); - } + ArgumentOutOfRangeException.ThrowIfNegative(to); + ArgumentOutOfRangeException.ThrowIfNegative(from); + ArgumentOutOfRangeException.ThrowIfGreaterThan(from, to); _from = from; _to = to; diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpClient.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpClient.cs index 83f4ab8db11660..74794b63d0c5de 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpClient.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpClient.cs @@ -116,10 +116,7 @@ public long MaxResponseContentBufferSize get => _maxResponseContentBufferSize; set { - if (value <= 0) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(value); if (value > HttpContent.MaxBufferSize) { throw new ArgumentOutOfRangeException(nameof(value), value, diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpClientHandler.AnyMobile.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpClientHandler.AnyMobile.cs index 2d9ae633df8696..be3f5170968dca 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpClientHandler.AnyMobile.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpClientHandler.AnyMobile.cs @@ -307,10 +307,7 @@ public long MaxRequestContentBufferSize set { - if (value < 0) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } + ArgumentOutOfRangeException.ThrowIfNegative(value); if (value > HttpContent.MaxBufferSize) { diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpClientHandler.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpClientHandler.cs index 1368369dcbc474..143011416e58ba 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpClientHandler.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpClientHandler.cs @@ -184,10 +184,7 @@ public long MaxRequestContentBufferSize set { - if (value < 0) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } + ArgumentOutOfRangeException.ThrowIfNegative(value); if (value > HttpContent.MaxBufferSize) { diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/MultipartContent.cs b/src/libraries/System.Net.Http/src/System/Net/Http/MultipartContent.cs index a1f7800a5716f2..49014faa89821d 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/MultipartContent.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/MultipartContent.cs @@ -576,10 +576,7 @@ public override long Position get { return _position; } set { - if (value < 0) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } + ArgumentOutOfRangeException.ThrowIfNegative(value); long previousStreamsLength = 0; for (int i = 0; i < _streams.Length; i++) diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/SocketsHttpHandler.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/SocketsHttpHandler.cs index 3553e0890552ad..a3f49ffc55255e 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/SocketsHttpHandler.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/SocketsHttpHandler.cs @@ -163,10 +163,7 @@ public int MaxResponseDrainSize get => _settings._maxResponseDrainSize; set { - if (value < 0) - { - throw new ArgumentOutOfRangeException(nameof(value), value, SR.ArgumentOutOfRange_NeedNonNegativeNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(value); CheckDisposedOrStarted(); _settings._maxResponseDrainSize = value; @@ -194,10 +191,7 @@ public int MaxResponseHeadersLength get => _settings._maxResponseHeadersLength; set { - if (value <= 0) - { - throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(value); CheckDisposedOrStarted(); _settings._maxResponseHeadersLength = value; diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/StreamContent.cs b/src/libraries/System.Net.Http/src/System/Net/Http/StreamContent.cs index c5d0366690fd65..037e55767c9417 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/StreamContent.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/StreamContent.cs @@ -28,11 +28,7 @@ public StreamContent(Stream content) public StreamContent(Stream content, int bufferSize) { ArgumentNullException.ThrowIfNull(content); - - if (bufferSize <= 0) - { - throw new ArgumentOutOfRangeException(nameof(bufferSize)); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(bufferSize); InitializeContent(content, bufferSize); } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBuffer.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBuffer.cs index 8a4998ce49da7e..245fb112d9314c 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBuffer.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBuffer.cs @@ -676,10 +676,7 @@ private sealed class PayloadReceiveResult public PayloadReceiveResult(int count, WebSocketMessageType messageType, bool endOfMessage) { - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } + ArgumentOutOfRangeException.ThrowIfNegative(count); Count = count; EndOfMessage = endOfMessage; diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs index d323c244dda87a..688ffae7483fa5 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs @@ -81,10 +81,7 @@ public SmtpClient(string? host, int port) { try { - if (port < 0) - { - throw new ArgumentOutOfRangeException(nameof(port)); - } + ArgumentOutOfRangeException.ThrowIfNegative(port); _host = host; _port = port; @@ -192,10 +189,7 @@ public int Port throw new InvalidOperationException(SR.SmtpInvalidOperationDuringSend); } - if (value <= 0) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(value); if (value != _port) { @@ -259,10 +253,7 @@ public int Timeout throw new InvalidOperationException(SR.SmtpInvalidOperationDuringSend); } - if (value < 0) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } + ArgumentOutOfRangeException.ThrowIfNegative(value); _timeout = value; } diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mime/QuotedPrintableStream.cs b/src/libraries/System.Net.Mail/src/System/Net/Mime/QuotedPrintableStream.cs index 6ce7c1cb7246f2..933ad4095f38e0 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mime/QuotedPrintableStream.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mime/QuotedPrintableStream.cs @@ -67,10 +67,7 @@ internal sealed class QuotedPrintableStream : DelegatedStream, IEncodableStream /// Preferred maximum line-length for writes internal QuotedPrintableStream(Stream stream, int lineLength) : base(stream) { - if (lineLength < 0) - { - throw new ArgumentOutOfRangeException(nameof(lineLength)); - } + ArgumentOutOfRangeException.ThrowIfNegative(lineLength); _lineLength = lineLength; } diff --git a/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.cs b/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.cs index 75572bc56f8714..dd0c77c2f5f94f 100644 --- a/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.cs +++ b/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.cs @@ -52,10 +52,7 @@ private void CheckArgs(int timeout, byte[] buffer) throw new ArgumentException(SR.net_invalidPingBufferSize, nameof(buffer)); } - if (timeout < 0) - { - throw new ArgumentOutOfRangeException(nameof(timeout)); - } + ArgumentOutOfRangeException.ThrowIfNegative(timeout); } private void CheckArgs(IPAddress address, int timeout, byte[] buffer) diff --git a/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/PingOptions.cs b/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/PingOptions.cs index 13b51cb52d63e0..70bca56b2794d7 100644 --- a/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/PingOptions.cs +++ b/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/PingOptions.cs @@ -15,10 +15,7 @@ public PingOptions() public PingOptions(int ttl, bool dontFragment) { - if (ttl <= 0) - { - throw new ArgumentOutOfRangeException(nameof(ttl)); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(ttl); _ttl = ttl; _dontFragment = dontFragment; @@ -32,10 +29,7 @@ public int Ttl } set { - if (value <= 0) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(value); // Useful to discover routes. _ttl = value; diff --git a/src/libraries/System.Net.Primitives/src/System/Net/Cookie.cs b/src/libraries/System.Net.Primitives/src/System/Net/Cookie.cs index 190fd9f4e991ad..d9186c05e42ca0 100644 --- a/src/libraries/System.Net.Primitives/src/System/Net/Cookie.cs +++ b/src/libraries/System.Net.Primitives/src/System/Net/Cookie.cs @@ -688,10 +688,7 @@ public int Version } set { - if (value < 0) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } + ArgumentOutOfRangeException.ThrowIfNegative(value); m_version = value; if (value > 0 && m_cookieVariant < CookieVariant.Rfc2109) { diff --git a/src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs b/src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs index b2b38ebfd3e268..adaaa55cd6b314 100644 --- a/src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs +++ b/src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs @@ -183,10 +183,7 @@ public int MaxCookieSize } set { - if (value <= 0) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(value); m_maxCookieSize = value; } } diff --git a/src/libraries/System.Net.Primitives/src/System/Net/CredentialCache.cs b/src/libraries/System.Net.Primitives/src/System/Net/CredentialCache.cs index 1065905ef89637..8cb88371227919 100644 --- a/src/libraries/System.Net.Primitives/src/System/Net/CredentialCache.cs +++ b/src/libraries/System.Net.Primitives/src/System/Net/CredentialCache.cs @@ -50,10 +50,7 @@ public void Add(string host, int port, string authenticationType, NetworkCredent ArgumentException.ThrowIfNullOrEmpty(host); ArgumentNullException.ThrowIfNull(authenticationType); - if (port < 0) - { - throw new ArgumentOutOfRangeException(nameof(port)); - } + ArgumentOutOfRangeException.ThrowIfNegative(port); if ((credential is SystemNetworkCredential) && !((string.Equals(authenticationType, NegotiationInfoClass.NTLM, StringComparison.OrdinalIgnoreCase)) @@ -170,10 +167,7 @@ public void Remove(string? host, int port, string? authenticationType) { ArgumentException.ThrowIfNullOrEmpty(host); ArgumentNullException.ThrowIfNull(authenticationType); - if (port < 0) - { - throw new ArgumentOutOfRangeException(nameof(port)); - } + ArgumentOutOfRangeException.ThrowIfNegative(port); if (_cacheForHosts == null) { diff --git a/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs b/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs index 4973ce3940258f..873d49add936ad 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs @@ -421,10 +421,7 @@ public long ContentOffset { throw new InvalidOperationException(SR.net_reqsubmitted); } - if (value < 0) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } + ArgumentOutOfRangeException.ThrowIfNegative(value); _contentOffset = value; } } diff --git a/src/libraries/System.Net.Requests/src/System/Net/TimerThread.cs b/src/libraries/System.Net.Requests/src/System/Net/TimerThread.cs index da9c32abc3633b..3aef8b469fded8 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/TimerThread.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/TimerThread.cs @@ -112,10 +112,7 @@ internal static Queue GetOrCreateQueue(int durationMilliseconds) return new InfiniteTimerQueue(); } - if (durationMilliseconds < 0) - { - throw new ArgumentOutOfRangeException(nameof(durationMilliseconds)); - } + ArgumentOutOfRangeException.ThrowIfNegative(durationMilliseconds); TimerQueue? queue; object key = durationMilliseconds; // Box once. diff --git a/src/libraries/System.Net.ServicePoint/src/System/Net/ServicePoint.cs b/src/libraries/System.Net.ServicePoint/src/System/Net/ServicePoint.cs index 8a272bd7867aaa..cbbebc04f73d36 100644 --- a/src/libraries/System.Net.ServicePoint/src/System/Net/ServicePoint.cs +++ b/src/libraries/System.Net.ServicePoint/src/System/Net/ServicePoint.cs @@ -28,10 +28,7 @@ public int ConnectionLeaseTimeout get { return _connectionLeaseTimeout; } set { - if (value < Timeout.Infinite) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } + ArgumentOutOfRangeException.ThrowIfLessThan(value, Timeout.Infinite); _connectionLeaseTimeout = value; } } @@ -43,10 +40,7 @@ public int MaxIdleTime get { return _maxIdleTime; } set { - if (value < Timeout.Infinite) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } + ArgumentOutOfRangeException.ThrowIfLessThan(value, Timeout.Infinite); _maxIdleTime = value; } } @@ -58,10 +52,7 @@ public int ReceiveBufferSize get { return _receiveBufferSize; } set { - if (value < -1) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } + ArgumentOutOfRangeException.ThrowIfLessThan(value, -1); _receiveBufferSize = value; } } @@ -81,10 +72,7 @@ public int ConnectionLimit get { return _connectionLimit; } set { - if (value <= 0) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(value); _connectionLimit = value; } } @@ -101,14 +89,8 @@ public void SetTcpKeepAlive(bool enabled, int keepAliveTime, int keepAliveInterv { if (enabled) { - if (keepAliveTime <= 0) - { - throw new ArgumentOutOfRangeException(nameof(keepAliveTime)); - } - if (keepAliveInterval <= 0) - { - throw new ArgumentOutOfRangeException(nameof(keepAliveInterval)); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(keepAliveTime); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(keepAliveInterval); } } } diff --git a/src/libraries/System.Net.ServicePoint/src/System/Net/ServicePointManager.cs b/src/libraries/System.Net.ServicePoint/src/System/Net/ServicePointManager.cs index 1013bbcd4d2f2e..29b6f36532d09e 100644 --- a/src/libraries/System.Net.ServicePoint/src/System/Net/ServicePointManager.cs +++ b/src/libraries/System.Net.ServicePoint/src/System/Net/ServicePointManager.cs @@ -51,10 +51,7 @@ public static int MaxServicePoints get { return s_maxServicePoints; } set { - if (value < 0) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } + ArgumentOutOfRangeException.ThrowIfNegative(value); s_maxServicePoints = value; } } @@ -64,10 +61,7 @@ public static int DefaultConnectionLimit get { return s_connectionLimit; } set { - if (value <= 0) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(value); s_connectionLimit = value; } } @@ -77,10 +71,7 @@ public static int MaxServicePointIdleTime get { return s_maxServicePointIdleTime; } set { - if (value < Timeout.Infinite) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } + ArgumentOutOfRangeException.ThrowIfLessThan(value, Timeout.Infinite); s_maxServicePointIdleTime = value; } } @@ -219,14 +210,8 @@ public static void SetTcpKeepAlive(bool enabled, int keepAliveTime, int keepAliv { if (enabled) { - if (keepAliveTime <= 0) - { - throw new ArgumentOutOfRangeException(nameof(keepAliveTime)); - } - if (keepAliveInterval <= 0) - { - throw new ArgumentOutOfRangeException(nameof(keepAliveInterval)); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(keepAliveTime); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(keepAliveInterval); } } } diff --git a/src/libraries/System.Net.Sockets/src/Resources/Strings.resx b/src/libraries/System.Net.Sockets/src/Resources/Strings.resx index 57d1a94b6ae6bd..06f5aac63087ca 100644 --- a/src/libraries/System.Net.Sockets/src/Resources/Strings.resx +++ b/src/libraries/System.Net.Sockets/src/Resources/Strings.resx @@ -279,9 +279,6 @@ Cannot access a closed stream. - - Positive number required. - The path '{0}' is of an invalid length for use with domain sockets on this platform. The length must be between 1 and {1} characters, inclusive. @@ -327,4 +324,4 @@ Handle is already used by another Socket. - \ No newline at end of file + diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/NetworkStream.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/NetworkStream.cs index 50c48c08515e2a..a4bcf29fef89f2 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/NetworkStream.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/NetworkStream.cs @@ -341,10 +341,7 @@ public override unsafe void WriteByte(byte value) => /// public void Close(int timeout) { - if (timeout < -1) - { - throw new ArgumentOutOfRangeException(nameof(timeout)); - } + ArgumentOutOfRangeException.ThrowIfLessThan(timeout, -1); _closeTimeout = timeout; Dispose(); } diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SendPacketsElement.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SendPacketsElement.cs index 97a8567222ef3f..5fecdb84a15d09 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SendPacketsElement.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SendPacketsElement.cs @@ -30,14 +30,8 @@ public SendPacketsElement(string filepath, long offset, int count, bool endOfPac ArgumentNullException.ThrowIfNull(filepath); // The native API will validate the file length on send. - if (offset < 0) - { - throw new ArgumentOutOfRangeException(nameof(offset)); - } - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } + ArgumentOutOfRangeException.ThrowIfNegative(offset); + ArgumentOutOfRangeException.ThrowIfNegative(count); Initialize(filepath, null, null, null, offset, count, endOfPacket); } @@ -60,14 +54,8 @@ public SendPacketsElement(FileStream fileStream, long offset, int count, bool en throw new ArgumentException(SR.net_sockets_sendpackelement_FileStreamMustBeAsync, nameof(fileStream)); } // The native API will validate the file length on send. - if (offset < 0) - { - throw new ArgumentOutOfRangeException(nameof(offset)); - } - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } + ArgumentOutOfRangeException.ThrowIfNegative(offset); + ArgumentOutOfRangeException.ThrowIfNegative(count); Initialize(null, fileStream, null, null, offset, count, endOfPacket); } diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs index c930ebcbec0d5e..e10b2c1cdf9299 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs @@ -496,10 +496,7 @@ public int ReceiveBufferSize } set { - if (value < 0) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } + ArgumentOutOfRangeException.ThrowIfNegative(value); SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, value); } @@ -514,10 +511,7 @@ public int SendBufferSize set { - if (value < 0) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } + ArgumentOutOfRangeException.ThrowIfNegative(value); SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, value); } @@ -531,10 +525,7 @@ public int ReceiveTimeout } set { - if (value < -1) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } + ArgumentOutOfRangeException.ThrowIfLessThan(value, -1); if (value == -1) { value = 0; @@ -553,10 +544,7 @@ public int SendTimeout set { - if (value < -1) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } + ArgumentOutOfRangeException.ThrowIfLessThan(value, -1); if (value == -1) { value = 0; @@ -958,10 +946,7 @@ public void Close() public void Close(int timeout) { - if (timeout < -1) - { - throw new ArgumentOutOfRangeException(nameof(timeout)); - } + ArgumentOutOfRangeException.ThrowIfLessThan(timeout, -1); _closeTimeout = timeout; @@ -2245,10 +2230,7 @@ private static int ToTimeoutMicroseconds(TimeSpan timeout) return -1; } - if (timeout < TimeSpan.Zero) - { - throw new ArgumentOutOfRangeException(nameof(timeout)); - } + ArgumentOutOfRangeException.ThrowIfLessThan(timeout, TimeSpan.Zero); long totalMicroseconds = (long)timeout.TotalMicroseconds; if (totalMicroseconds > int.MaxValue) @@ -2538,10 +2520,7 @@ public IAsyncResult BeginAccept(AsyncCallback? callback, object? state) => // There's no direct equivalent of this in the Task APIs, so we mimic it here. private async Task<(Socket s, byte[] buffer, int bytesReceived)> AcceptAndReceiveHelperAsync(Socket? acceptSocket, int receiveSize) { - if (receiveSize < 0) - { - throw new ArgumentOutOfRangeException(nameof(receiveSize)); - } + ArgumentOutOfRangeException.ThrowIfNegative(receiveSize); Socket s = await AcceptAsync(acceptSocket).ConfigureAwait(false); diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/TCPListener.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/TCPListener.cs index d7442a44fb110b..6ee9ff7bcf8a27 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/TCPListener.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/TCPListener.cs @@ -134,10 +134,7 @@ public void Start() public void Start(int backlog) { - if (backlog < 0) - { - throw new ArgumentOutOfRangeException(nameof(backlog)); - } + ArgumentOutOfRangeException.ThrowIfNegative(backlog); // Already listening. if (_active) diff --git a/src/libraries/System.Net.WebSockets/src/System/Net/WebSockets/WebSocketReceiveResult.cs b/src/libraries/System.Net.WebSockets/src/System/Net/WebSockets/WebSocketReceiveResult.cs index 455b310926ca82..6d0d6123146c86 100644 --- a/src/libraries/System.Net.WebSockets/src/System/Net/WebSockets/WebSocketReceiveResult.cs +++ b/src/libraries/System.Net.WebSockets/src/System/Net/WebSockets/WebSocketReceiveResult.cs @@ -18,10 +18,7 @@ public WebSocketReceiveResult(int count, WebSocketCloseStatus? closeStatus, string? closeStatusDescription) { - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } + ArgumentOutOfRangeException.ThrowIfNegative(count); Count = count; EndOfMessage = endOfMessage; diff --git a/src/libraries/System.ObjectModel/src/Resources/Strings.resx b/src/libraries/System.ObjectModel/src/Resources/Strings.resx index f2a98df105a1e4..38c39844319798 100644 --- a/src/libraries/System.ObjectModel/src/Resources/Strings.resx +++ b/src/libraries/System.ObjectModel/src/Resources/Strings.resx @@ -72,9 +72,6 @@ Destination array is not long enough to copy all the items in the collection. Check array index and length. - - Non-negative number required. - Index cannot be negative. @@ -105,4 +102,4 @@ The given key '{0}' was not present in the dictionary. - \ No newline at end of file + diff --git a/src/libraries/System.ObjectModel/src/System/Collections/CollectionHelpers.cs b/src/libraries/System.ObjectModel/src/System/Collections/CollectionHelpers.cs index 7652e953b5a275..ad68b201707bff 100644 --- a/src/libraries/System.ObjectModel/src/System/Collections/CollectionHelpers.cs +++ b/src/libraries/System.ObjectModel/src/System/Collections/CollectionHelpers.cs @@ -21,10 +21,8 @@ internal static void ValidateCopyToArguments(int sourceCount, Array array, int i throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array)); } - if (index < 0 || index > array.Length) - { - throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfGreaterThan(index, array.Length); if (array.Length - index < sourceCount) { diff --git a/src/libraries/System.Private.CoreLib/src/Resources/Strings.resx b/src/libraries/System.Private.CoreLib/src/Resources/Strings.resx index 2b8bf16f6e4333..f9c3ff8b7e8f3e 100644 --- a/src/libraries/System.Private.CoreLib/src/Resources/Strings.resx +++ b/src/libraries/System.Private.CoreLib/src/Resources/Strings.resx @@ -1690,9 +1690,6 @@ Not a valid Win32 FileTime. - - Value must be positive. - Too many characters. The resulting number of bytes is larger than what can be returned as an int. @@ -1784,15 +1781,6 @@ The ID parameter must be in the range {0} through {1}. - - Capacity must be positive. - - - Count cannot be less than zero. - - - Length cannot be less than zero. - Offset and length must refer to a position in the string. @@ -1805,9 +1793,6 @@ Pointer startIndex and length do not refer to a valid string. - - Period must be less than 2^32-1. - The position may not be greater or equal to the capacity of the accessor. @@ -1823,9 +1808,6 @@ capacity was less than the current size. - - MaxCapacity must be one or greater. - StartIndex cannot be less than zero. @@ -1835,9 +1817,6 @@ Stream length must be non-negative and less than 2^31 - 1 - origin. - - Time-out interval must be less than 2^32-1. - The length of the buffer must be less than the maximum UIntPtr value for your platform. @@ -1853,9 +1832,6 @@ The sum of the BaseUtcOffset and DaylightDelta properties must within plus or minus 14.0 hours. - - Version's parameters must be greater than or equal to zero. - The Week parameter must be in the range 1 through 5. diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/ArrayList.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/ArrayList.cs index e786952f66f81f..51932ce6ab288a 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/ArrayList.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/ArrayList.cs @@ -201,10 +201,8 @@ public virtual void AddRange(ICollection c) // public virtual int BinarySearch(int index, int count, object? value, IComparer? comparer) { - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); - if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (_size - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); @@ -338,10 +336,8 @@ public virtual IEnumerator GetEnumerator() // public virtual IEnumerator GetEnumerator(int index, int count) { - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); - if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (_size - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); return new ArrayListEnumerator(this, index, count); @@ -481,8 +477,11 @@ public virtual int LastIndexOf(object? value, int startIndex) // public virtual int LastIndexOf(object? value, int startIndex, int count) { - if (Count != 0 && (startIndex < 0 || count < 0)) - throw new ArgumentOutOfRangeException(startIndex < 0 ? nameof(startIndex) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + if (Count != 0) + { + ArgumentOutOfRangeException.ThrowIfNegative(startIndex); + ArgumentOutOfRangeException.ThrowIfNegative(count); + } if (_size == 0) // Special case for an empty list return -1; @@ -541,10 +540,8 @@ public virtual void RemoveAt(int index) // public virtual void RemoveRange(int index, int count) { - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); - if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (_size - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); @@ -565,8 +562,7 @@ public virtual void RemoveRange(int index, int count) // public static ArrayList Repeat(object? value, int count) { - if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(count); ArrayList list = new ArrayList((count > _defaultCapacity) ? count : _defaultCapacity); for (int i = 0; i < count; i++) @@ -590,10 +586,8 @@ public virtual void Reverse() // public virtual void Reverse(int index, int count) { - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); - if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (_size - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); @@ -620,8 +614,8 @@ public virtual void SetRange(int index, ICollection c) public virtual ArrayList GetRange(int index, int count) { - if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (_size - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); return new Range(this, index, count); @@ -651,10 +645,8 @@ public virtual void Sort(IComparer? comparer) // public virtual void Sort(int index, int count, IComparer? comparer) { - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); - if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (_size - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); @@ -779,8 +771,8 @@ public override void AddRange(ICollection c) // Other overloads with automatically work public override int BinarySearch(int index, int count, object? value, IComparer? comparer) { - if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (Count - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); @@ -839,10 +831,9 @@ public override void CopyTo(int index, Array array, int arrayIndex, int count) { ArgumentNullException.ThrowIfNull(array); - if (index < 0 || arrayIndex < 0) - throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(arrayIndex), SR.ArgumentOutOfRange_NeedNonNegNum); - if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(arrayIndex); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (array.Length - arrayIndex < count) throw new ArgumentException(SR.Argument_InvalidOffLen); if (array.Rank != 1) @@ -862,8 +853,8 @@ public override IEnumerator GetEnumerator() public override IEnumerator GetEnumerator(int index, int count) { - if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (_list.Count - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); @@ -986,8 +977,8 @@ public override void RemoveAt(int index) public override void RemoveRange(int index, int count) { - if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (_list.Count - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); @@ -1004,8 +995,8 @@ public override void RemoveRange(int index, int count) public override void Reverse(int index, int count) { - if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (_list.Count - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); @@ -1043,8 +1034,8 @@ public override void SetRange(int index, ICollection c) public override ArrayList GetRange(int index, int count) { - if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (_list.Count - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); return new Range(this, index, count); @@ -1052,8 +1043,8 @@ public override ArrayList GetRange(int index, int count) public override void Sort(int index, int count, IComparer? comparer) { - if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (_list.Count - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); @@ -1828,8 +1819,8 @@ public override void SetRange(int index, ICollection c) public override ArrayList GetRange(int index, int count) { - if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (Count - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); @@ -2082,8 +2073,8 @@ public override void SetRange(int index, ICollection c) public override ArrayList GetRange(int index, int count) { - if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (Count - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); @@ -2234,8 +2225,8 @@ public override void AddRange(ICollection c) public override int BinarySearch(int index, int count, object? value, IComparer? comparer) { - if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (_baseSize - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); @@ -2301,8 +2292,7 @@ public override void CopyTo(Array array, int index) if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); if (array.Length - index < _baseSize) throw new ArgumentException(SR.Argument_InvalidOffLen); @@ -2316,8 +2306,8 @@ public override void CopyTo(int index, Array array, int arrayIndex, int count) if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); - if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (array.Length - arrayIndex < count) throw new ArgumentException(SR.Argument_InvalidOffLen); if (_baseSize - index < count) diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/HashSet.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/HashSet.cs index 00b99235ee4805..9a3ab8a0f922ec 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/HashSet.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/HashSet.cs @@ -3,6 +3,7 @@ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; +using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Serialization; @@ -851,17 +852,8 @@ public void CopyTo(T[] array, int arrayIndex, int count) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - // Check array index valid index into array. - if (arrayIndex < 0) - { - throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, SR.ArgumentOutOfRange_NeedNonNegNum); - } - - // Also throw if count less than 0. - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(arrayIndex); + ArgumentOutOfRangeException.ThrowIfNegative(count); // Will the array, starting at arrayIndex, be able to hold elements? Note: not // checking arrayIndex >= array.Length (consistency with list of allowing diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/Queue.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/Queue.cs index 327aa1c64a19d9..e9121fcb8e3e93 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/Queue.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/Queue.cs @@ -42,8 +42,7 @@ public Queue() // is used. public Queue(int capacity) { - if (capacity < 0) - throw new ArgumentOutOfRangeException(nameof(capacity), capacity, SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(capacity); _array = new T[capacity]; } @@ -377,10 +376,7 @@ public void TrimExcess() /// The new capacity of this queue. public int EnsureCapacity(int capacity) { - if (capacity < 0) - { - throw new ArgumentOutOfRangeException(nameof(capacity), capacity, SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(capacity); if (_array.Length < capacity) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/Hashtable.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/Hashtable.cs index d70a824f6c3bb3..11dc9e793590fe 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Hashtable.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Hashtable.cs @@ -257,8 +257,7 @@ public Hashtable(int capacity) : this(capacity, 1.0f) // public Hashtable(int capacity, float loadFactor) { - if (capacity < 0) - throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(capacity); if (!(loadFactor >= 0.1f && loadFactor <= 1.0f)) throw new ArgumentOutOfRangeException(nameof(loadFactor), SR.ArgumentOutOfRange_HashtableLoadFactor); @@ -571,8 +570,7 @@ public virtual void CopyTo(Array array, int arrayIndex) if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); - if (arrayIndex < 0) - throw new ArgumentOutOfRangeException(nameof(arrayIndex), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(arrayIndex); if (array.Length - arrayIndex < Count) throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); @@ -1191,8 +1189,7 @@ public void CopyTo(Array array, int arrayIndex) if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); - if (arrayIndex < 0) - throw new ArgumentOutOfRangeException(nameof(arrayIndex), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(arrayIndex); if (array.Length - arrayIndex < _hashtable._count) throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); _hashtable.CopyKeys(array, arrayIndex); @@ -1227,8 +1224,7 @@ public void CopyTo(Array array, int arrayIndex) if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); - if (arrayIndex < 0) - throw new ArgumentOutOfRangeException(nameof(arrayIndex), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(arrayIndex); if (array.Length - arrayIndex < _hashtable._count) throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); _hashtable.CopyValues(array, arrayIndex); diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/ListDictionaryInternal.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/ListDictionaryInternal.cs index d39a152b069c6c..73d76517931b78 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/ListDictionaryInternal.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/ListDictionaryInternal.cs @@ -156,8 +156,7 @@ public void CopyTo(Array array, int index) if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); if (array.Length - index < this.Count) throw new ArgumentException(SR.ArgumentOutOfRange_IndexMustBeLessOrEqual, nameof(index)); @@ -311,8 +310,7 @@ void ICollection.CopyTo(Array array, int index) if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); if (array.Length - index < list.Count) throw new ArgumentException(SR.ArgumentOutOfRange_IndexMustBeLessOrEqual, nameof(index)); for (DictionaryNode? node = list.head; node != null; node = node.next) diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/ObjectModel/CollectionHelpers.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/ObjectModel/CollectionHelpers.cs index d84958d4f0aaad..72ce5ec5e9f200 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/ObjectModel/CollectionHelpers.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/ObjectModel/CollectionHelpers.cs @@ -21,10 +21,8 @@ internal static void ValidateCopyToArguments(int sourceCount, Array array, int i throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array)); } - if (index < 0 || index > array.Length) - { - throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfGreaterThan(index, array.Length); if (array.Length - index < sourceCount) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventDescriptor.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventDescriptor.cs index 1ab7aaff5d28b2..8195ff23afe785 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventDescriptor.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventDescriptor.cs @@ -56,10 +56,7 @@ public EventDescriptor( long keywords ) { - if (id < 0) - { - throw new ArgumentOutOfRangeException(nameof(id), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(id); if (id > ushort.MaxValue) { @@ -74,10 +71,7 @@ long keywords m_opcode = opcode; m_keywords = keywords; - if (task < 0) - { - throw new ArgumentOutOfRangeException(nameof(task), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(task); if (task > ushort.MaxValue) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/Calendar.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/Calendar.cs index ed7a1844b3f82a..c93675537feb7c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/Calendar.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/Calendar.cs @@ -674,10 +674,7 @@ public virtual int TwoDigitYearMax /// public virtual int ToFourDigitYear(int year) { - if (year < 0) - { - throw new ArgumentOutOfRangeException(nameof(year), year, SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(year); if (year < 100) { return (TwoDigitYearMax / 100 - (year > TwoDigitYearMax % 100 ? 1 : 0)) * 100 + year; diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.cs index 3f0f6f5613bad8..f0e89f12deff9a 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.cs @@ -381,15 +381,11 @@ public int Compare(string? string1, int offset1, int length1, string? string2, i // We know a bounds check error occurred. Now we just need to figure // out the correct error message to surface. - if (length1 < 0 || length2 < 0) - { - throw new ArgumentOutOfRangeException((length1 < 0) ? nameof(length1) : nameof(length2), SR.ArgumentOutOfRange_NeedPosNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(length1); + ArgumentOutOfRangeException.ThrowIfNegative(length2); - if (offset1 < 0 || offset2 < 0) - { - throw new ArgumentOutOfRangeException((offset1 < 0) ? nameof(offset1) : nameof(offset2), SR.ArgumentOutOfRange_NeedPosNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(offset1); + ArgumentOutOfRangeException.ThrowIfNegative(offset2); if (offset1 > (string1 == null ? 0 : string1.Length) - length1) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureInfo.cs index ab72a79c966cc2..d5c1f218c81619 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureInfo.cs @@ -203,10 +203,7 @@ public CultureInfo(int culture) : this(culture, true) public CultureInfo(int culture, bool useUserOverride) { // We don't check for other invalid LCIDS here... - if (culture < 0) - { - throw new ArgumentOutOfRangeException(nameof(culture), SR.ArgumentOutOfRange_NeedPosNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(culture); switch (culture) { @@ -1020,10 +1017,7 @@ private void VerifyWritable() /// public static CultureInfo GetCultureInfo(int culture) { - if (culture <= 0) - { - throw new ArgumentOutOfRangeException(nameof(culture), SR.ArgumentOutOfRange_NeedPosNum); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(culture); Dictionary lcidTable = CachedCulturesByLcid; CultureInfo? result; diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/EastAsianLunisolarCalendar.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/EastAsianLunisolarCalendar.cs index 6e5a322c6d1cb0..0294c7c240871c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/EastAsianLunisolarCalendar.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/EastAsianLunisolarCalendar.cs @@ -676,13 +676,7 @@ public override int TwoDigitYearMax public override int ToFourDigitYear(int year) { - if (year < 0) - { - throw new ArgumentOutOfRangeException( - nameof(year), - year, - SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(year); year = base.ToFourDigitYear(year); CheckYearRange(year, CurrentEra); diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/GregorianCalendar.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/GregorianCalendar.cs index bc49fb7b37f73b..ed9bde883abd12 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/GregorianCalendar.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/GregorianCalendar.cs @@ -435,17 +435,8 @@ public override int TwoDigitYearMax public override int ToFourDigitYear(int year) { - if (year < 0) - { - throw new ArgumentOutOfRangeException(nameof(year), year, SR.ArgumentOutOfRange_NeedNonNegNum); - } - if (year > MaxYear) - { - throw new ArgumentOutOfRangeException( - nameof(year), - year, - SR.Format(SR.ArgumentOutOfRange_Range, 1, MaxYear)); - } + ArgumentOutOfRangeException.ThrowIfNegative(year); + ArgumentOutOfRangeException.ThrowIfGreaterThan(year, MaxYear); return base.ToFourDigitYear(year); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/GregorianCalendarHelper.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/GregorianCalendarHelper.cs index 2748b390db150b..4054731d261427 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/GregorianCalendarHelper.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/GregorianCalendarHelper.cs @@ -525,11 +525,7 @@ public int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDa public int ToFourDigitYear(int year, int twoDigitYearMax) { - if (year < 0) - { - throw new ArgumentOutOfRangeException(nameof(year), - SR.ArgumentOutOfRange_NeedPosNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(year); if (year < 100) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/HebrewCalendar.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/HebrewCalendar.cs index ec79399323d6d4..b36fe1324c6955 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/HebrewCalendar.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/HebrewCalendar.cs @@ -871,10 +871,7 @@ public override int TwoDigitYearMax public override int ToFourDigitYear(int year) { - if (year < 0) - { - throw new ArgumentOutOfRangeException(nameof(year), year, SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(year); if (year < 100) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/HijriCalendar.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/HijriCalendar.cs index fa1f63490195d3..3e8345929c9d3c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/HijriCalendar.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/HijriCalendar.cs @@ -446,10 +446,7 @@ public override int TwoDigitYearMax public override int ToFourDigitYear(int year) { - if (year < 0) - { - throw new ArgumentOutOfRangeException(nameof(year), year, SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(year); if (year < 100) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/IdnMapping.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/IdnMapping.cs index 80e2c4e73bdaec..041b89702d40a0 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/IdnMapping.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/IdnMapping.cs @@ -67,8 +67,8 @@ public string GetAscii(string unicode, int index, int count) { ArgumentNullException.ThrowIfNull(unicode); - if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException((index < 0) ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (index > unicode.Length) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); if (index > unicode.Length - count) @@ -114,8 +114,8 @@ public string GetUnicode(string ascii, int index, int count) { ArgumentNullException.ThrowIfNull(ascii); - if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException((index < 0) ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (index > ascii.Length) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); if (index > ascii.Length - count) diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/JapaneseCalendar.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/JapaneseCalendar.cs index ba6b3087cd82b1..cd37d6ba65292f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/JapaneseCalendar.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/JapaneseCalendar.cs @@ -193,17 +193,8 @@ public override DateTime ToDateTime(int year, int month, int day, int hour, int /// public override int ToFourDigitYear(int year) { - if (year <= 0) - { - throw new ArgumentOutOfRangeException(nameof(year), year, SR.ArgumentOutOfRange_NeedPosNum); - } - if (year > _helper.MaxYear) - { - throw new ArgumentOutOfRangeException( - nameof(year), - year, - SR.Format(SR.ArgumentOutOfRange_Range, 1, _helper.MaxYear)); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(year); + ArgumentOutOfRangeException.ThrowIfGreaterThan(year, _helper.MaxYear); return year; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/JulianCalendar.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/JulianCalendar.cs index d81f1ca00382a1..c468484b694a34 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/JulianCalendar.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/JulianCalendar.cs @@ -1,6 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Reflection; + namespace System.Globalization { /// @@ -349,10 +351,7 @@ public override int TwoDigitYearMax public override int ToFourDigitYear(int year) { - if (year < 0) - { - throw new ArgumentOutOfRangeException(nameof(year), year, SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(year); if (year > MaxYear) { throw new ArgumentOutOfRangeException( diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/KoreanCalendar.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/KoreanCalendar.cs index 7cfdcf8a33c230..cb550395ba3c81 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/KoreanCalendar.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/KoreanCalendar.cs @@ -175,10 +175,7 @@ public override int TwoDigitYearMax public override int ToFourDigitYear(int year) { - if (year < 0) - { - throw new ArgumentOutOfRangeException(nameof(year), year, SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(year); return _helper.ToFourDigitYear(year, TwoDigitYearMax); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/PersianCalendar.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/PersianCalendar.cs index a1d507dc2a3233..b69ac8e7deb1ed 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/PersianCalendar.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/PersianCalendar.cs @@ -417,10 +417,7 @@ public override int TwoDigitYearMax public override int ToFourDigitYear(int year) { - if (year < 0) - { - throw new ArgumentOutOfRangeException(nameof(year), year, SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(year); if (year < 100) { return base.ToFourDigitYear(year); diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/TaiwanCalendar.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/TaiwanCalendar.cs index 988fb1c58a8c34..8a282b12457db2 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/TaiwanCalendar.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/TaiwanCalendar.cs @@ -179,17 +179,8 @@ public override int TwoDigitYearMax public override int ToFourDigitYear(int year) { - if (year <= 0) - { - throw new ArgumentOutOfRangeException(nameof(year), year, SR.ArgumentOutOfRange_NeedPosNum); - } - if (year > _helper.MaxYear) - { - throw new ArgumentOutOfRangeException( - nameof(year), - year, - SR.Format(SR.ArgumentOutOfRange_Range, 1, _helper.MaxYear)); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(year); + ArgumentOutOfRangeException.ThrowIfGreaterThan(year, _helper.MaxYear); return year; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/ThaiBuddhistCalendar.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/ThaiBuddhistCalendar.cs index a224fff46d3fb9..4d0baa33566315 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/ThaiBuddhistCalendar.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/ThaiBuddhistCalendar.cs @@ -156,10 +156,7 @@ public override int TwoDigitYearMax public override int ToFourDigitYear(int year) { - if (year < 0) - { - throw new ArgumentOutOfRangeException(nameof(year), year, SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(year); return _helper.ToFourDigitYear(year, TwoDigitYearMax); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/UmAlQuraCalendar.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/UmAlQuraCalendar.cs index e89fb4e99ffa5c..724ecb1ed40f7e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/UmAlQuraCalendar.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/UmAlQuraCalendar.cs @@ -625,10 +625,7 @@ public override int TwoDigitYearMax public override int ToFourDigitYear(int year) { - if (year < 0) - { - throw new ArgumentOutOfRangeException(nameof(year), year, SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(year); if (year < 100) { diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/BinaryReader.cs b/src/libraries/System.Private.CoreLib/src/System/IO/BinaryReader.cs index 80ef5992629c50..e7d32817297dcf 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/BinaryReader.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/BinaryReader.cs @@ -316,14 +316,8 @@ public virtual int Read(char[] buffer, int index, int count) { ArgumentNullException.ThrowIfNull(buffer); - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); - } - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); @@ -419,10 +413,7 @@ private int InternalReadChars(Span buffer) public virtual char[] ReadChars(int count) { - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(count); ThrowIfDisposed(); if (count == 0) @@ -446,14 +437,8 @@ public virtual int Read(byte[] buffer, int index, int count) { ArgumentNullException.ThrowIfNull(buffer); - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); - } - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/BinaryWriter.cs b/src/libraries/System.Private.CoreLib/src/System/IO/BinaryWriter.cs index 12053a582cb832..b6fef2e0dadeef 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/BinaryWriter.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/BinaryWriter.cs @@ -230,10 +230,8 @@ public virtual void Write(char[] chars, int index, int count) { ArgumentNullException.ThrowIfNull(chars); - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); - if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (index > chars.Length - count) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexCount); diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/EnumerationOptions.cs b/src/libraries/System.Private.CoreLib/src/System/IO/EnumerationOptions.cs index a48d7ce4d0b17f..8a31939444be4e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/EnumerationOptions.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/EnumerationOptions.cs @@ -88,10 +88,7 @@ public int MaxRecursionDepth get => _maxRecursionDepth; set { - if (value < 0) - { - throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(value); _maxRecursionDepth = value; } diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/FileStreamOptions.cs b/src/libraries/System.Private.CoreLib/src/System/IO/FileStreamOptions.cs index 56f5c545b0ef6d..333b864c5c8d14 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/FileStreamOptions.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/FileStreamOptions.cs @@ -99,7 +99,11 @@ public FileOptions Options public long PreallocationSize { get => _preallocationSize; - set => _preallocationSize = value >= 0 ? value : throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum); + set + { + ArgumentOutOfRangeException.ThrowIfNegative(value); + _preallocationSize = value; + } } /// @@ -110,7 +114,11 @@ public long PreallocationSize public int BufferSize { get => _bufferSize; - set => _bufferSize = value >= 0 ? value : throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum); + set + { + ArgumentOutOfRangeException.ThrowIfNegative(value); + _bufferSize = value; + } } /// diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/MemoryStream.cs b/src/libraries/System.Private.CoreLib/src/System/IO/MemoryStream.cs index 2ca3983a20e991..3b9e0455146e45 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/MemoryStream.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/MemoryStream.cs @@ -43,8 +43,7 @@ public MemoryStream() public MemoryStream(int capacity) { - if (capacity < 0) - throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NegativeCapacity); + ArgumentOutOfRangeException.ThrowIfNegative(capacity); _buffer = capacity != 0 ? new byte[capacity] : Array.Empty(); _capacity = capacity; @@ -83,10 +82,8 @@ public MemoryStream(byte[] buffer, int index, int count, bool writable, bool pub { ArgumentNullException.ThrowIfNull(buffer); - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); - if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (buffer.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); @@ -310,9 +307,7 @@ public override long Position } set { - if (value < 0) - throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum); - + ArgumentOutOfRangeException.ThrowIfNegative(value); EnsureNotClosed(); if (value > MemStreamMaxLength) diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/Stream.cs b/src/libraries/System.Private.CoreLib/src/System/IO/Stream.cs index 5f9a0915ec1547..f3b723b1f56509 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/Stream.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/Stream.cs @@ -997,10 +997,7 @@ protected static void ValidateCopyToArguments(Stream destination, int bufferSize { ArgumentNullException.ThrowIfNull(destination); - if (bufferSize <= 0) - { - throw new ArgumentOutOfRangeException(nameof(bufferSize), bufferSize, SR.ArgumentOutOfRange_NeedPosNum); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(bufferSize); if (!destination.CanWrite) { diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/StreamReader.cs b/src/libraries/System.Private.CoreLib/src/System/IO/StreamReader.cs index 472e0c4f91060b..d07f668f3eca0d 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/StreamReader.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/StreamReader.cs @@ -152,10 +152,7 @@ public StreamReader(Stream stream, Encoding? encoding = null, bool detectEncodin { bufferSize = DefaultBufferSize; } - else if (bufferSize <= 0) - { - throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(bufferSize); _stream = stream; _encoding = encoding ??= Encoding.UTF8; @@ -232,10 +229,7 @@ private static Stream ValidateArgsAndOpenPath(string path, Encoding encoding, in { ArgumentException.ThrowIfNullOrEmpty(path); ArgumentNullException.ThrowIfNull(encoding); - if (bufferSize <= 0) - { - throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(bufferSize); return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultFileStreamBufferSize); } @@ -355,10 +349,8 @@ public override int Read(char[] buffer, int index, int count) { ArgumentNullException.ThrowIfNull(buffer); - if (index < 0 || count < 0) - { - throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); @@ -436,10 +428,8 @@ public override int ReadBlock(char[] buffer, int index, int count) { ArgumentNullException.ThrowIfNull(buffer); - if (index < 0 || count < 0) - { - throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); @@ -1060,10 +1050,8 @@ public override Task ReadAsync(char[] buffer, int index, int count) { ArgumentNullException.ThrowIfNull(buffer); - if (index < 0 || count < 0) - { - throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); @@ -1273,10 +1261,8 @@ public override Task ReadBlockAsync(char[] buffer, int index, int count) { ArgumentNullException.ThrowIfNull(buffer); - if (index < 0 || count < 0) - { - throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/StreamWriter.cs b/src/libraries/System.Private.CoreLib/src/System/IO/StreamWriter.cs index d5a18b2ca47159..60b752bf2b56d3 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/StreamWriter.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/StreamWriter.cs @@ -107,10 +107,7 @@ public StreamWriter(Stream stream, Encoding? encoding = null, int bufferSize = - { bufferSize = DefaultBufferSize; } - else if (bufferSize <= 0) - { - throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(bufferSize); _stream = stream; _encoding = encoding ?? UTF8NoBOM; @@ -179,10 +176,7 @@ private static Stream ValidateArgsAndOpenPath(string path, bool append, Encoding { ArgumentException.ThrowIfNullOrEmpty(path); ArgumentNullException.ThrowIfNull(encoding); - if (bufferSize <= 0) - { - throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(bufferSize); return new FileStream(path, append ? FileMode.Append : FileMode.Create, FileAccess.Write, FileShare.Read, DefaultFileStreamBufferSize); } @@ -368,15 +362,8 @@ public override void Write(char[]? buffer) public override void Write(char[] buffer, int index, int count) { ArgumentNullException.ThrowIfNull(buffer); - - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); - } - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); @@ -701,14 +688,8 @@ public override Task WriteAsync(char[] buffer, int index, int count) { ArgumentNullException.ThrowIfNull(buffer); - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); - } - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); @@ -859,14 +840,8 @@ public override Task WriteLineAsync(char[] buffer, int index, int count) { ArgumentNullException.ThrowIfNull(buffer); - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); - } - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/StringReader.cs b/src/libraries/System.Private.CoreLib/src/System/IO/StringReader.cs index ecb756ef736d0c..da3837db0ef909 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/StringReader.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/StringReader.cs @@ -87,14 +87,8 @@ public override int Read(char[] buffer, int index, int count) { ArgumentNullException.ThrowIfNull(buffer); - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); - } - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); @@ -294,10 +288,8 @@ public override Task ReadBlockAsync(char[] buffer, int index, int count) { ArgumentNullException.ThrowIfNull(buffer); - if (index < 0 || count < 0) - { - throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); @@ -314,10 +306,8 @@ public override Task ReadAsync(char[] buffer, int index, int count) { ArgumentNullException.ThrowIfNull(buffer); - if (index < 0 || count < 0) - { - throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/StringWriter.cs b/src/libraries/System.Private.CoreLib/src/System/IO/StringWriter.cs index 97584ac8fa8211..9b5eee9d8c0417 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/StringWriter.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/StringWriter.cs @@ -89,14 +89,8 @@ public override void Write(char[] buffer, int index, int count) { ArgumentNullException.ThrowIfNull(buffer); - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); - } - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/TextReader.cs b/src/libraries/System.Private.CoreLib/src/System/IO/TextReader.cs index 793bb1c4371a55..7da76e7869cb72 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/TextReader.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/TextReader.cs @@ -71,14 +71,8 @@ public virtual int Read(char[] buffer, int index, int count) { ArgumentNullException.ThrowIfNull(buffer); - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); - } - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); @@ -267,10 +261,8 @@ public virtual Task ReadAsync(char[] buffer, int index, int count) { ArgumentNullException.ThrowIfNull(buffer); - if (index < 0 || count < 0) - { - throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); @@ -401,8 +393,8 @@ public override Task ReadBlockAsync(char[] buffer, int index, int count) { ArgumentNullException.ThrowIfNull(buffer); - if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (buffer.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); @@ -414,8 +406,8 @@ public override Task ReadAsync(char[] buffer, int index, int count) { ArgumentNullException.ThrowIfNull(buffer); - if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (buffer.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/TextWriter.cs b/src/libraries/System.Private.CoreLib/src/System/IO/TextWriter.cs index a8ba47123f41b6..813a542a5b15da 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/TextWriter.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/TextWriter.cs @@ -145,14 +145,8 @@ public virtual void Write(char[] buffer, int index, int count) { ArgumentNullException.ThrowIfNull(buffer); - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); - } - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryAccessor.cs b/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryAccessor.cs index f895be77711962..87b369c1b838fe 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryAccessor.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryAccessor.cs @@ -15,6 +15,7 @@ using System.Diagnostics; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; +using System.Reflection; namespace System.IO { @@ -49,14 +50,8 @@ protected void Initialize(SafeBuffer buffer, long offset, long capacity, FileAcc { ArgumentNullException.ThrowIfNull(buffer); - if (offset < 0) - { - throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); - } - if (capacity < 0) - { - throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(offset); + ArgumentOutOfRangeException.ThrowIfNegative(capacity); if (buffer.ByteLength < (ulong)(offset + capacity)) { throw new ArgumentException(SR.Argument_OffsetAndCapacityOutOfBounds); @@ -294,10 +289,7 @@ public decimal ReadDecimal(long position) // bools, etc. public void Read(long position, out T structure) where T : struct { - if (position < 0) - { - throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(position); if (!_isOpen) { @@ -331,14 +323,8 @@ public int ReadArray(long position, T[] array, int offset, int count) where T { ArgumentNullException.ThrowIfNull(array); - if (offset < 0) - { - throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); - } - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(offset); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (array.Length - offset < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); @@ -351,10 +337,7 @@ public int ReadArray(long position, T[] array, int offset, int count) where T { throw new NotSupportedException(SR.NotSupported_Reading); } - if (position < 0) - { - throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(position); uint sizeOfT = SafeBuffer.AlignedSizeOf(); @@ -535,10 +518,7 @@ public void Write(long position, decimal value) // the WriteX methods for small standard types such as ints, longs, bools, etc. public void Write(long position, ref T structure) where T : struct { - if (position < 0) - { - throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(position); if (!_isOpen) { throw new ObjectDisposedException(nameof(UnmanagedMemoryAccessor), SR.ObjectDisposed_ViewAccessorClosed); @@ -569,22 +549,13 @@ public void WriteArray(long position, T[] array, int offset, int count) where { ArgumentNullException.ThrowIfNull(array); - if (offset < 0) - { - throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); - } - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(offset); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (array.Length - offset < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } - if (position < 0) - { - throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(position); if (position >= Capacity) { throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired); @@ -612,10 +583,7 @@ private void EnsureSafeToRead(long position, int sizeOfType) { throw new NotSupportedException(SR.NotSupported_Reading); } - if (position < 0) - { - throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(position); if (position > _capacity - sizeOfType) { if (position >= _capacity) @@ -639,10 +607,7 @@ private void EnsureSafeToWrite(long position, int sizeOfType) { throw new NotSupportedException(SR.NotSupported_Writing); } - if (position < 0) - { - throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(position); if (position > _capacity - sizeOfType) { if (position >= _capacity) diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryStreamWrapper.cs b/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryStreamWrapper.cs index bc9f9c3f674634..bdab1b017534bc 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryStreamWrapper.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryStreamWrapper.cs @@ -141,8 +141,7 @@ public override Task CopyToAsync(Stream destination, int bufferSize, Cancellatio { ArgumentNullException.ThrowIfNull(destination); - if (bufferSize <= 0) - throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(bufferSize); if (!CanRead && !CanWrite) ThrowHelper.ThrowObjectDisposedException_StreamClosed(null); diff --git a/src/libraries/System.Private.CoreLib/src/System/Random.cs b/src/libraries/System.Private.CoreLib/src/System/Random.cs index cc2363739465e1..2c406efbc6b2c7 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Random.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Random.cs @@ -69,10 +69,7 @@ public virtual int Next() /// is less than 0. public virtual int Next(int maxValue) { - if (maxValue < 0) - { - ThrowMaxValueMustBeNonNegative(); - } + ArgumentOutOfRangeException.ThrowIfNegative(maxValue); int result = _impl.Next(maxValue); AssertInRange(result, 0, maxValue); @@ -117,10 +114,7 @@ public virtual long NextInt64() /// is less than 0. public virtual long NextInt64(long maxValue) { - if (maxValue < 0) - { - ThrowMaxValueMustBeNonNegative(); - } + ArgumentOutOfRangeException.ThrowIfNegative(maxValue); long result = _impl.NextInt64(maxValue); AssertInRange(result, 0, maxValue); @@ -191,9 +185,6 @@ protected virtual double Sample() return result; } - private static void ThrowMaxValueMustBeNonNegative() => - throw new ArgumentOutOfRangeException("maxValue", SR.ArgumentOutOfRange_NeedNonNegNum); - private static void ThrowMinMaxValueSwapped() => throw new ArgumentOutOfRangeException("minValue", SR.Format(SR.Argument_MinMaxValue, "minValue", "maxValue")); @@ -251,10 +242,7 @@ public override int Next() public override int Next(int maxValue) { - if (maxValue < 0) - { - ThrowMaxValueMustBeNonNegative(); - } + ArgumentOutOfRangeException.ThrowIfNegative(maxValue); int result = LocalRandom.Next(maxValue); AssertInRange(result, 0, maxValue); @@ -282,10 +270,7 @@ public override long NextInt64() public override long NextInt64(long maxValue) { - if (maxValue < 0) - { - ThrowMaxValueMustBeNonNegative(); - } + ArgumentOutOfRangeException.ThrowIfNegative(maxValue); long result = LocalRandom.NextInt64(maxValue); AssertInRange(result, 0, maxValue); diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.cs index c1756ce8d4c60a..3fa56b3fa99f65 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.cs @@ -43,10 +43,7 @@ public static partial class Marshal public static unsafe string PtrToStringAnsi(IntPtr ptr, int len) { ArgumentNullException.ThrowIfNull(ptr); - if (len < 0) - { - throw new ArgumentOutOfRangeException(nameof(len), len, SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(len); return new string((sbyte*)ptr, 0, len); } @@ -64,10 +61,7 @@ public static unsafe string PtrToStringAnsi(IntPtr ptr, int len) public static unsafe string PtrToStringUni(IntPtr ptr, int len) { ArgumentNullException.ThrowIfNull(ptr); - if (len < 0) - { - throw new ArgumentOutOfRangeException(nameof(len), len, SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(len); return new string((char*)ptr, 0, len); } @@ -86,10 +80,7 @@ public static unsafe string PtrToStringUni(IntPtr ptr, int len) public static unsafe string PtrToStringUTF8(IntPtr ptr, int byteLen) { ArgumentNullException.ThrowIfNull(ptr); - if (byteLen < 0) - { - throw new ArgumentOutOfRangeException(nameof(byteLen), byteLen, SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(byteLen); return string.CreateStringFromEncoding((byte*)ptr, byteLen, Encoding.UTF8); } @@ -285,10 +276,8 @@ private static unsafe void CopyToManaged(IntPtr source, T[] destination, int ArgumentNullException.ThrowIfNull(destination); ArgumentNullException.ThrowIfNull(source); - if (startIndex < 0) - throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex); - if (length < 0) - throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(startIndex); + ArgumentOutOfRangeException.ThrowIfNegative(length); // The rest of the argument validation is done by CopyTo diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/SafeBuffer.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/SafeBuffer.cs index ef19c8291e5d42..d35b5dd174fc73 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/SafeBuffer.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/SafeBuffer.cs @@ -217,10 +217,8 @@ public void ReadArray(ulong byteOffset, T[] array, int index, int count) { ArgumentNullException.ThrowIfNull(array); - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); - if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (array.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); @@ -306,10 +304,8 @@ public void WriteArray(ulong byteOffset, T[] array, int index, int count) { ArgumentNullException.ThrowIfNull(array); - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); - if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (array.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/MemoryFailPoint.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/MemoryFailPoint.cs index 79535d873867d4..5c3cd273bba57b 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/MemoryFailPoint.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/MemoryFailPoint.cs @@ -139,8 +139,7 @@ private static long LastTimeCheckingAddressSpace // is somehow incorrect. public MemoryFailPoint(int sizeInMegabytes) { - if (sizeInMegabytes <= 0) - throw new ArgumentOutOfRangeException(nameof(sizeInMegabytes), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sizeInMegabytes); ulong size = ((ulong)sizeInMegabytes) << 20; _reservedMemory = size; diff --git a/src/libraries/System.Private.CoreLib/src/System/Security/SecureString.cs b/src/libraries/System.Private.CoreLib/src/System/Security/SecureString.cs index a0fa1773f640b2..3a3a54b954a2f0 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Security/SecureString.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Security/SecureString.cs @@ -26,14 +26,8 @@ public unsafe SecureString(char* value, int length) { ArgumentNullException.ThrowIfNull(value); - if (length < 0) - { - throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum); - } - if (length > MaxLength) - { - throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_Length); - } + ArgumentOutOfRangeException.ThrowIfNegative(length); + ArgumentOutOfRangeException.ThrowIfGreaterThan(length, MaxLength); Initialize(new ReadOnlySpan(value, length)); } diff --git a/src/libraries/System.Private.CoreLib/src/System/String.Manipulation.cs b/src/libraries/System.Private.CoreLib/src/System/String.Manipulation.cs index 64aad87d6cfea2..58b7f1ca18ccd0 100644 --- a/src/libraries/System.Private.CoreLib/src/System/String.Manipulation.cs +++ b/src/libraries/System.Private.CoreLib/src/System/String.Manipulation.cs @@ -1845,10 +1845,11 @@ public string Substring(int startIndex, int length) [DoesNotReturn] private void ThrowSubstringArgumentOutOfRange(int startIndex, int length) { - (string paramName, string message) = - startIndex < 0 ? (nameof(startIndex), SR.ArgumentOutOfRange_StartIndex) : - startIndex > Length ? (nameof(startIndex), SR.ArgumentOutOfRange_StartIndexLargerThanLength) : - length < 0 ? (nameof(length), SR.ArgumentOutOfRange_NegativeLength) : + ArgumentOutOfRangeException.ThrowIfNegative(startIndex); + ArgumentOutOfRangeException.ThrowIfNegative(length); + + (string paramName, string message) = startIndex > Length ? + (nameof(startIndex), SR.ArgumentOutOfRange_StartIndexLargerThanLength) : (nameof(length), SR.ArgumentOutOfRange_IndexLength); throw new ArgumentOutOfRangeException(paramName, message); diff --git a/src/libraries/System.Private.CoreLib/src/System/String.cs b/src/libraries/System.Private.CoreLib/src/System/String.cs index 971f1bbbef9fa5..cbd49eeaf964cf 100644 --- a/src/libraries/System.Private.CoreLib/src/System/String.cs +++ b/src/libraries/System.Private.CoreLib/src/System/String.cs @@ -266,9 +266,8 @@ private static string Ctor(char c, int count) { if (count <= 0) { - if (count == 0) - return Empty; - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NegativeCount); + ArgumentOutOfRangeException.ThrowIfNegative(count); + return Empty; } string result = FastAllocateString(count); @@ -450,9 +449,8 @@ public char[] ToCharArray(int startIndex, int length) if (length <= 0) { - if (length == 0) - return Array.Empty(); - throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength); + ArgumentOutOfRangeException.ThrowIfNegative(length); + return Array.Empty(); } char[] chars = new char[length]; diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/ASCIIEncoding.cs b/src/libraries/System.Private.CoreLib/src/System/Text/ASCIIEncoding.cs index ebf07d971271d9..902abc7e3b3a8e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/ASCIIEncoding.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/ASCIIEncoding.cs @@ -807,9 +807,7 @@ internal sealed override OperationStatus DecodeFirstRune(ReadOnlySpan byte public override int GetMaxByteCount(int charCount) { - if (charCount < 0) - throw new ArgumentOutOfRangeException(nameof(charCount), - SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); // Characters would be # of characters + 1 in case high surrogate is ? * max fallback long byteCount = (long)charCount + 1; @@ -827,9 +825,7 @@ public override int GetMaxByteCount(int charCount) public override int GetMaxCharCount(int byteCount) { - if (byteCount < 0) - throw new ArgumentOutOfRangeException(nameof(byteCount), - SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); // Just return length, SBCS stay the same length because they don't map to surrogate long charCount = (long)byteCount; diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/Decoder.cs b/src/libraries/System.Private.CoreLib/src/System/Text/Decoder.cs index 8447ff61be03b5..254ac5fbd5903c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/Decoder.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/Decoder.cs @@ -97,8 +97,7 @@ public virtual int GetCharCount(byte[] bytes, int index, int count, bool flush) public virtual unsafe int GetCharCount(byte* bytes, int count, bool flush) { ArgumentNullException.ThrowIfNull(bytes); - if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(count); byte[] arrbyte = new byte[count]; @@ -161,9 +160,8 @@ public virtual unsafe int GetChars(byte* bytes, int byteCount, { ArgumentNullException.ThrowIfNull(bytes); ArgumentNullException.ThrowIfNull(chars); - if (byteCount < 0 || charCount < 0) - throw new ArgumentOutOfRangeException(byteCount < 0 ? nameof(byteCount) : nameof(charCount), - SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); // Get the byte array to convert byte[] arrByte = new byte[byteCount]; @@ -224,13 +222,10 @@ public virtual void Convert(byte[] bytes, int byteIndex, int byteCount, ArgumentNullException.ThrowIfNull(bytes); ArgumentNullException.ThrowIfNull(chars); - if (byteIndex < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), - SR.ArgumentOutOfRange_NeedNonNegNum); - - if (charIndex < 0 || charCount < 0) - throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), - SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(byteIndex); + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); + ArgumentOutOfRangeException.ThrowIfNegative(charIndex); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), @@ -278,9 +273,8 @@ public virtual unsafe void Convert(byte* bytes, int byteCount, ArgumentNullException.ThrowIfNull(bytes); ArgumentNullException.ThrowIfNull(chars); - if (byteCount < 0 || charCount < 0) - throw new ArgumentOutOfRangeException(byteCount < 0 ? nameof(byteCount) : nameof(charCount), - SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); // Get ready to do it bytesUsed = byteCount; diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/DecoderNLS.cs b/src/libraries/System.Private.CoreLib/src/System/Text/DecoderNLS.cs index 3dea2a410e81c7..80a71fad3dc172 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/DecoderNLS.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/DecoderNLS.cs @@ -50,9 +50,8 @@ public override unsafe int GetCharCount(byte[] bytes, int index, int count, bool { ArgumentNullException.ThrowIfNull(bytes); - if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), - SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException(nameof(bytes), @@ -67,9 +66,7 @@ public override unsafe int GetCharCount(byte* bytes, int count, bool flush) { ArgumentNullException.ThrowIfNull(bytes); - if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count), - SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(count); // Remember the flush _mustFlush = flush; @@ -92,9 +89,8 @@ public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, ArgumentNullException.ThrowIfNull(bytes); ArgumentNullException.ThrowIfNull(chars); - if (byteIndex < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), - SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(byteIndex); + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), @@ -120,9 +116,8 @@ public override unsafe int GetChars(byte* bytes, int byteCount, ArgumentNullException.ThrowIfNull(bytes); ArgumentNullException.ThrowIfNull(chars); - if (byteCount < 0 || charCount < 0) - throw new ArgumentOutOfRangeException(byteCount < 0 ? nameof(byteCount) : nameof(charCount), - SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); // Remember our flush _mustFlush = flush; @@ -142,13 +137,11 @@ public override unsafe void Convert(byte[] bytes, int byteIndex, int byteCount, ArgumentNullException.ThrowIfNull(bytes); ArgumentNullException.ThrowIfNull(chars); - if (byteIndex < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), - SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(byteIndex); + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); - if (charIndex < 0 || charCount < 0) - throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), - SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(charIndex); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), @@ -178,9 +171,8 @@ public override unsafe void Convert(byte* bytes, int byteCount, ArgumentNullException.ThrowIfNull(bytes); ArgumentNullException.ThrowIfNull(chars); - if (byteCount < 0 || charCount < 0) - throw new ArgumentOutOfRangeException(byteCount < 0 ? nameof(byteCount) : nameof(charCount), - SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); // We don't want to throw _mustFlush = flush; diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/Encoder.cs b/src/libraries/System.Private.CoreLib/src/System/Text/Encoder.cs index dffd4be8a0a52e..0b35e749fda967 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/Encoder.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/Encoder.cs @@ -95,8 +95,7 @@ public virtual unsafe int GetByteCount(char* chars, int count, bool flush) { ArgumentNullException.ThrowIfNull(chars); - if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(count); char[] arrChar = new char[count]; @@ -159,9 +158,8 @@ public virtual unsafe int GetBytes(char* chars, int charCount, ArgumentNullException.ThrowIfNull(chars); ArgumentNullException.ThrowIfNull(bytes); - if (charCount < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), - SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); // Get the char array to convert char[] arrChar = new char[charCount]; @@ -221,13 +219,11 @@ public virtual void Convert(char[] chars, int charIndex, int charCount, ArgumentNullException.ThrowIfNull(chars); ArgumentNullException.ThrowIfNull(bytes); - if (charIndex < 0 || charCount < 0) - throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), - SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(charIndex); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); - if (byteIndex < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), - SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(byteIndex); + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), @@ -276,8 +272,8 @@ public virtual unsafe void Convert(char* chars, int charCount, ArgumentNullException.ThrowIfNull(chars); ArgumentNullException.ThrowIfNull(bytes); - if (charCount < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); // Get ready to do it charsUsed = charCount; diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/EncoderNLS.cs b/src/libraries/System.Private.CoreLib/src/System/Text/EncoderNLS.cs index dc183037910e5d..eec28b3b459b87 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/EncoderNLS.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/EncoderNLS.cs @@ -45,9 +45,8 @@ public override unsafe int GetByteCount(char[] chars, int index, int count, bool { ArgumentNullException.ThrowIfNull(chars); - if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), - SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (chars.Length - index < count) throw new ArgumentOutOfRangeException(nameof(chars), @@ -66,9 +65,7 @@ public override unsafe int GetByteCount(char* chars, int count, bool flush) { ArgumentNullException.ThrowIfNull(chars); - if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count), - SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(count); _mustFlush = flush; _throwOnOverflow = true; @@ -82,9 +79,8 @@ public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, ArgumentNullException.ThrowIfNull(chars); ArgumentNullException.ThrowIfNull(bytes); - if (charIndex < 0 || charCount < 0) - throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), - SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(charIndex); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), @@ -110,9 +106,8 @@ public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int ArgumentNullException.ThrowIfNull(chars); ArgumentNullException.ThrowIfNull(bytes); - if (byteCount < 0 || charCount < 0) - throw new ArgumentOutOfRangeException(byteCount < 0 ? nameof(byteCount) : nameof(charCount), - SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); _mustFlush = flush; _throwOnOverflow = true; @@ -129,13 +124,11 @@ public override unsafe void Convert(char[] chars, int charIndex, int charCount, ArgumentNullException.ThrowIfNull(chars); ArgumentNullException.ThrowIfNull(bytes); - if (charIndex < 0 || charCount < 0) - throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), - SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(charIndex); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); - if (byteIndex < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), - SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(byteIndex); + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), @@ -165,9 +158,8 @@ public override unsafe void Convert(char* chars, int charCount, ArgumentNullException.ThrowIfNull(chars); ArgumentNullException.ThrowIfNull(bytes); - if (charCount < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), - SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); // We don't want to throw _mustFlush = flush; diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/Encoding.cs b/src/libraries/System.Private.CoreLib/src/System/Text/Encoding.cs index 6cca9d2396711f..7145be9695c5e3 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/Encoding.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/Encoding.cs @@ -696,9 +696,8 @@ public virtual unsafe int GetBytes(char* chars, int charCount, ArgumentNullException.ThrowIfNull(chars); ArgumentNullException.ThrowIfNull(bytes); - if (charCount < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), - SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); // Get the char array to convert char[] arrChar = new ReadOnlySpan(chars, charCount).ToArray(); @@ -756,9 +755,7 @@ public virtual unsafe int GetCharCount(byte* bytes, int count) { ArgumentNullException.ThrowIfNull(bytes); - if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count), - SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(count); byte[] arrByte = new ReadOnlySpan(bytes, count).ToArray(); @@ -830,9 +827,8 @@ public virtual unsafe int GetChars(byte* bytes, int byteCount, ArgumentNullException.ThrowIfNull(bytes); ArgumentNullException.ThrowIfNull(chars); - if (byteCount < 0 || charCount < 0) - throw new ArgumentOutOfRangeException(byteCount < 0 ? nameof(byteCount) : nameof(charCount), - SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); // Get the byte array to convert byte[] arrByte = new ReadOnlySpan(bytes, byteCount).ToArray(); @@ -873,8 +869,7 @@ public unsafe string GetString(byte* bytes, int byteCount) { ArgumentNullException.ThrowIfNull(bytes); - if (byteCount < 0) - throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); return string.CreateStringFromEncoding(bytes, byteCount, this); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs b/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs index 2c9331c0e1d0b4..dae115fe505d06 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs @@ -116,18 +116,9 @@ public StringBuilder(string? value, int capacity) /// The initial capacity of this builder. public StringBuilder(string? value, int startIndex, int length, int capacity) { - if (capacity < 0) - { - throw new ArgumentOutOfRangeException(nameof(capacity), SR.Format(SR.ArgumentOutOfRange_MustBePositive, nameof(capacity))); - } - if (length < 0) - { - throw new ArgumentOutOfRangeException(nameof(length), SR.Format(SR.ArgumentOutOfRange_MustBeNonNegNum, nameof(length))); - } - if (startIndex < 0) - { - throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex); - } + ArgumentOutOfRangeException.ThrowIfNegative(capacity); + ArgumentOutOfRangeException.ThrowIfNegative(length); + ArgumentOutOfRangeException.ThrowIfNegative(startIndex); value ??= string.Empty; @@ -160,14 +151,8 @@ public StringBuilder(int capacity, int maxCapacity) { throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_Capacity); } - if (maxCapacity < 1) - { - throw new ArgumentOutOfRangeException(nameof(maxCapacity), SR.ArgumentOutOfRange_SmallMaxCapacity); - } - if (capacity < 0) - { - throw new ArgumentOutOfRangeException(nameof(capacity), SR.Format(SR.ArgumentOutOfRange_MustBePositive, nameof(capacity))); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxCapacity); + ArgumentOutOfRangeException.ThrowIfNegative(capacity); if (capacity == 0) { @@ -281,10 +266,7 @@ public int Capacity get => m_ChunkChars.Length + m_ChunkOffset; set { - if (value < 0) - { - throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NegativeCapacity); - } + ArgumentOutOfRangeException.ThrowIfNegative(value); if (value > MaxCapacity) { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_Capacity); @@ -319,10 +301,7 @@ public int Capacity /// public int EnsureCapacity(int capacity) { - if (capacity < 0) - { - throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NegativeCapacity); - } + ArgumentOutOfRangeException.ThrowIfNegative(capacity); if (Capacity < capacity) { @@ -377,18 +356,12 @@ ref MemoryMarshal.GetArrayDataReference(sourceArray), public string ToString(int startIndex, int length) { int currentLength = this.Length; - if (startIndex < 0) - { - throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex); - } + ArgumentOutOfRangeException.ThrowIfNegative(startIndex); if (startIndex > currentLength) { throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndexLargerThanLength); } - if (length < 0) - { - throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength); - } + ArgumentOutOfRangeException.ThrowIfNegative(length); if (startIndex > currentLength - length) { throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_IndexLength); @@ -415,10 +388,7 @@ public int Length set { // If the new length is less than 0 or greater than our Maximum capacity, bail. - if (value < 0) - { - throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NegativeLength); - } + ArgumentOutOfRangeException.ThrowIfNegative(value); if (value > MaxCapacity) { @@ -682,10 +652,7 @@ public ManyChunkInfo(StringBuilder? stringBuilder, int chunkCount) /// The number of times to append . public StringBuilder Append(char value, int repeatCount) { - if (repeatCount < 0) - { - throw new ArgumentOutOfRangeException(nameof(repeatCount), SR.ArgumentOutOfRange_NegativeCount); - } + ArgumentOutOfRangeException.ThrowIfNegative(repeatCount); if (repeatCount == 0) { @@ -730,14 +697,8 @@ public StringBuilder Append(char value, int repeatCount) /// The number of characters to read in . public StringBuilder Append(char[]? value, int startIndex, int charCount) { - if (startIndex < 0) - { - throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_GenericPositive); - } - if (charCount < 0) - { - throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_GenericPositive); - } + ArgumentOutOfRangeException.ThrowIfNegative(startIndex); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); if (value == null) { @@ -783,14 +744,8 @@ public StringBuilder Append(string? value) /// The number of characters to read in . public StringBuilder Append(string? value, int startIndex, int count) { - if (startIndex < 0) - { - throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); - } - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_GenericPositive); - } + ArgumentOutOfRangeException.ThrowIfNegative(startIndex); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (value == null) { @@ -825,15 +780,8 @@ public StringBuilder Append(StringBuilder? value) public StringBuilder Append(StringBuilder? value, int startIndex, int count) { - if (startIndex < 0) - { - throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); - } - - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_GenericPositive); - } + ArgumentOutOfRangeException.ThrowIfNegative(startIndex); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (value == null) { @@ -901,10 +849,7 @@ public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, in { ArgumentNullException.ThrowIfNull(destination); - if (destinationIndex < 0) - { - throw new ArgumentOutOfRangeException(nameof(destinationIndex), SR.Format(SR.ArgumentOutOfRange_MustBeNonNegNum, nameof(destinationIndex))); - } + ArgumentOutOfRangeException.ThrowIfNegative(destinationIndex); if (destinationIndex > destination.Length - count) { @@ -916,10 +861,7 @@ public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, in public void CopyTo(int sourceIndex, Span destination, int count) { - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count), SR.Arg_NegativeArgCount); - } + ArgumentOutOfRangeException.ThrowIfNegative(count); if ((uint)sourceIndex > (uint)Length) { @@ -970,10 +912,7 @@ public void CopyTo(int sourceIndex, Span destination, int count) private StringBuilder Insert(int index, ReadOnlySpan value, int count) { - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(count); int currentLength = Length; if ((uint)index > (uint)currentLength) @@ -1014,16 +953,8 @@ private StringBuilder Insert(int index, ReadOnlySpan value, int count) /// public StringBuilder Remove(int startIndex, int length) { - if (length < 0) - { - throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength); - } - - if (startIndex < 0) - { - throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex); - } - + ArgumentOutOfRangeException.ThrowIfNegative(length); + ArgumentOutOfRangeException.ThrowIfNegative(startIndex); if (length > Length - startIndex) { throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); @@ -1331,16 +1262,8 @@ public StringBuilder Insert(int index, char[]? value, int startIndex, int charCo ArgumentNullException.Throw(nameof(value)); } - if (startIndex < 0) - { - throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex); - } - - if (charCount < 0) - { - throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_GenericPositive); - } - + ArgumentOutOfRangeException.ThrowIfNegative(startIndex); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); if (startIndex > value.Length - charCount) { throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); @@ -1990,10 +1913,7 @@ public StringBuilder Replace(char oldChar, char newChar, int startIndex, int cou public unsafe StringBuilder Append(char* value, int valueCount) { // We don't check null value as this case will throw null reference exception anyway - if (valueCount < 0) - { - throw new ArgumentOutOfRangeException(nameof(valueCount), SR.ArgumentOutOfRange_NegativeCount); - } + ArgumentOutOfRangeException.ThrowIfNegative(valueCount); Append(ref *value, valueCount); return this; diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/UTF32Encoding.cs b/src/libraries/System.Private.CoreLib/src/System/Text/UTF32Encoding.cs index 9097bcf4af3530..9afbf6736ff08c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/UTF32Encoding.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/UTF32Encoding.cs @@ -94,8 +94,8 @@ public override unsafe int GetByteCount(char[] chars, int index, int count) { ArgumentNullException.ThrowIfNull(chars); - if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (chars.Length - index < count) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); @@ -134,8 +134,7 @@ public override unsafe int GetByteCount(char* chars, int count) { ArgumentNullException.ThrowIfNull(chars); - if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(count); // Call it with empty encoder return GetByteCount(chars, count, null); @@ -152,8 +151,8 @@ public override unsafe int GetBytes(string s, int charIndex, int charCount, ArgumentNullException.ThrowIfNull(s); ArgumentNullException.ThrowIfNull(bytes); - if (charIndex < 0 || charCount < 0) - throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(charIndex); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); if (s.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(s), SR.ArgumentOutOfRange_IndexCount); @@ -187,8 +186,8 @@ public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, ArgumentNullException.ThrowIfNull(chars); ArgumentNullException.ThrowIfNull(bytes); - if (charIndex < 0 || charCount < 0) - throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(charIndex); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); @@ -218,8 +217,8 @@ public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int ArgumentNullException.ThrowIfNull(chars); ArgumentNullException.ThrowIfNull(bytes); - if (charCount < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); return GetBytes(chars, charCount, bytes, byteCount, null); } @@ -236,8 +235,8 @@ public override unsafe int GetCharCount(byte[] bytes, int index, int count) { ArgumentNullException.ThrowIfNull(bytes); - if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); @@ -260,8 +259,7 @@ public override unsafe int GetCharCount(byte* bytes, int count) { ArgumentNullException.ThrowIfNull(bytes); - if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(count); return GetCharCount(bytes, count, null); } @@ -277,8 +275,8 @@ public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, ArgumentNullException.ThrowIfNull(bytes); ArgumentNullException.ThrowIfNull(chars); - if (byteIndex < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(byteIndex); + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); @@ -308,8 +306,8 @@ public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int ArgumentNullException.ThrowIfNull(bytes); ArgumentNullException.ThrowIfNull(chars); - if (charCount < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); return GetChars(bytes, byteCount, chars, charCount, null); } @@ -326,8 +324,8 @@ public override unsafe string GetString(byte[] bytes, int index, int count) { ArgumentNullException.ThrowIfNull(bytes); - if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); @@ -1060,9 +1058,7 @@ public override Encoder GetEncoder() public override int GetMaxByteCount(int charCount) { - if (charCount < 0) - throw new ArgumentOutOfRangeException(nameof(charCount), - SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); // Characters would be # of characters + 1 in case left over high surrogate is ? * max fallback long byteCount = (long)charCount + 1; @@ -1081,9 +1077,7 @@ public override int GetMaxByteCount(int charCount) public override int GetMaxCharCount(int byteCount) { - if (byteCount < 0) - throw new ArgumentOutOfRangeException(nameof(byteCount), - SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); // A supplementary character becomes 2 surrogate characters, so 4 input bytes becomes 2 chars, // plus we may have 1 surrogate char left over if the decoder has 3 bytes in it already for a non-bmp char. diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/UTF7Encoding.cs b/src/libraries/System.Private.CoreLib/src/System/Text/UTF7Encoding.cs index 9c9666141076a5..e4c4e3457008ff 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/UTF7Encoding.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/UTF7Encoding.cs @@ -137,8 +137,8 @@ public override unsafe int GetByteCount(char[] chars, int index, int count) { ArgumentNullException.ThrowIfNull(chars); - if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (chars.Length - index < count) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); @@ -177,8 +177,7 @@ public override unsafe int GetByteCount(char* chars, int count) { ArgumentNullException.ThrowIfNull(chars); - if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(count); // Call it with empty encoder return GetByteCount(chars, count, null); @@ -195,8 +194,8 @@ public override unsafe int GetBytes(string s, int charIndex, int charCount, ArgumentNullException.ThrowIfNull(s); ArgumentNullException.ThrowIfNull(bytes); - if (charIndex < 0 || charCount < 0) - throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(charIndex); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); if (s.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(s), SR.ArgumentOutOfRange_IndexCount); @@ -230,8 +229,8 @@ public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, ArgumentNullException.ThrowIfNull(chars); ArgumentNullException.ThrowIfNull(bytes); - if (charIndex < 0 || charCount < 0) - throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(charIndex); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); @@ -261,8 +260,8 @@ public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int ArgumentNullException.ThrowIfNull(chars); ArgumentNullException.ThrowIfNull(bytes); - if (charCount < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); return GetBytes(chars, charCount, bytes, byteCount, null); } @@ -279,8 +278,8 @@ public override unsafe int GetCharCount(byte[] bytes, int index, int count) { ArgumentNullException.ThrowIfNull(bytes); - if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); @@ -303,8 +302,7 @@ public override unsafe int GetCharCount(byte* bytes, int count) { ArgumentNullException.ThrowIfNull(bytes); - if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(count); return GetCharCount(bytes, count, null); } @@ -320,8 +318,8 @@ public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, ArgumentNullException.ThrowIfNull(bytes); ArgumentNullException.ThrowIfNull(chars); - if (byteIndex < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(byteIndex); + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); @@ -351,8 +349,8 @@ public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int ArgumentNullException.ThrowIfNull(bytes); ArgumentNullException.ThrowIfNull(chars); - if (charCount < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); return GetChars(bytes, byteCount, chars, charCount, null); } @@ -369,8 +367,8 @@ public override unsafe string GetString(byte[] bytes, int index, int count) { ArgumentNullException.ThrowIfNull(bytes); - if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); @@ -723,9 +721,7 @@ public override System.Text.Encoder GetEncoder() public override int GetMaxByteCount(int charCount) { - if (charCount < 0) - throw new ArgumentOutOfRangeException(nameof(charCount), - SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); // Suppose that every char can not be direct-encoded, we know that // a byte can encode 6 bits of the Unicode character. And we will @@ -754,9 +750,7 @@ public override int GetMaxByteCount(int charCount) public override int GetMaxCharCount(int byteCount) { - if (byteCount < 0) - throw new ArgumentOutOfRangeException(nameof(byteCount), - SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); // Worst case is 1 char per byte. Minimum 1 for left over bits in case decoder is being flushed // Also note that we ignore extra bits (per spec), so UTF7 doesn't have unknown in this direction. diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/UnicodeEncoding.cs b/src/libraries/System.Private.CoreLib/src/System/Text/UnicodeEncoding.cs index d2299ee9a798bb..e6aaa42e93d5bc 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/UnicodeEncoding.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/UnicodeEncoding.cs @@ -86,8 +86,8 @@ public override unsafe int GetByteCount(char[] chars, int index, int count) { ArgumentNullException.ThrowIfNull(chars); - if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (chars.Length - index < count) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); @@ -126,8 +126,7 @@ public override unsafe int GetByteCount(char* chars, int count) { ArgumentNullException.ThrowIfNull(chars); - if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(count); // Call it with empty encoder return GetByteCount(chars, count, null); @@ -144,8 +143,8 @@ public override unsafe int GetBytes(string s, int charIndex, int charCount, ArgumentNullException.ThrowIfNull(s); ArgumentNullException.ThrowIfNull(bytes); - if (charIndex < 0 || charCount < 0) - throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(charIndex); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); if (s.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(s), SR.ArgumentOutOfRange_IndexCount); @@ -179,8 +178,8 @@ public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, ArgumentNullException.ThrowIfNull(chars); ArgumentNullException.ThrowIfNull(bytes); - if (charIndex < 0 || charCount < 0) - throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(charIndex); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); @@ -210,8 +209,8 @@ public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int ArgumentNullException.ThrowIfNull(chars); ArgumentNullException.ThrowIfNull(bytes); - if (charCount < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); return GetBytes(chars, charCount, bytes, byteCount, null); } @@ -228,8 +227,8 @@ public override unsafe int GetCharCount(byte[] bytes, int index, int count) { ArgumentNullException.ThrowIfNull(bytes); - if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); @@ -252,8 +251,7 @@ public override unsafe int GetCharCount(byte* bytes, int count) { ArgumentNullException.ThrowIfNull(bytes); - if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(count); return GetCharCount(bytes, count, null); } @@ -269,8 +267,8 @@ public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, ArgumentNullException.ThrowIfNull(bytes); ArgumentNullException.ThrowIfNull(chars); - if (byteIndex < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(byteIndex); + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); @@ -300,8 +298,8 @@ public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int ArgumentNullException.ThrowIfNull(bytes); ArgumentNullException.ThrowIfNull(chars); - if (charCount < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); return GetChars(bytes, byteCount, chars, charCount, null); } @@ -318,8 +316,8 @@ public override unsafe string GetString(byte[] bytes, int index, int count) { ArgumentNullException.ThrowIfNull(bytes); - if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); @@ -1753,9 +1751,7 @@ public override byte[] GetPreamble() public override int GetMaxByteCount(int charCount) { - if (charCount < 0) - throw new ArgumentOutOfRangeException(nameof(charCount), - SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(charCount); // Characters would be # of characters + 1 in case left over high surrogate is ? * max fallback long byteCount = (long)charCount + 1; @@ -1774,9 +1770,7 @@ public override int GetMaxByteCount(int charCount) public override int GetMaxCharCount(int byteCount) { - if (byteCount < 0) - throw new ArgumentOutOfRangeException(nameof(byteCount), - SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(byteCount); // long because byteCount could be biggest int. // 1 char per 2 bytes. Round up in case 1 left over in decoder. diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Semaphore.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Semaphore.cs index fb386e9e8be9d0..9ebf8594889166 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Semaphore.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Semaphore.cs @@ -21,11 +21,8 @@ public Semaphore(int initialCount, int maximumCount, string? name) : public Semaphore(int initialCount, int maximumCount, string? name, out bool createdNew) { - if (initialCount < 0) - throw new ArgumentOutOfRangeException(nameof(initialCount), SR.ArgumentOutOfRange_NeedNonNegNum); - - if (maximumCount < 1) - throw new ArgumentOutOfRangeException(nameof(maximumCount), SR.ArgumentOutOfRange_NeedPosNum); + ArgumentOutOfRangeException.ThrowIfNegative(initialCount); + ArgumentOutOfRangeException.ThrowIfLessThan(maximumCount, 1); if (initialCount > maximumCount) throw new ArgumentException(SR.Argument_SemaphoreInitialMaximum); @@ -59,8 +56,7 @@ public static bool TryOpenExisting(string name, [NotNullWhen(true)] out Semaphor // increase the count on a semaphore, returns previous count public int Release(int releaseCount) { - if (releaseCount < 1) - throw new ArgumentOutOfRangeException(nameof(releaseCount), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfLessThan(releaseCount, 1); return ReleaseCore(releaseCount); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/SpinWait.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/SpinWait.cs index 4ebd8547287518..d827208377ab08 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/SpinWait.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/SpinWait.cs @@ -143,10 +143,7 @@ public void SpinOnce() /// public void SpinOnce(int sleep1Threshold) { - if (sleep1Threshold < -1) - { - throw new ArgumentOutOfRangeException(nameof(sleep1Threshold), sleep1Threshold, SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - } + ArgumentOutOfRangeException.ThrowIfLessThan(sleep1Threshold, -1); if (sleep1Threshold >= 0 && sleep1Threshold < YieldThreshold) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Thread.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Thread.cs index a27ced32def893..0f39e88c8c6ef4 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Thread.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Thread.cs @@ -120,10 +120,7 @@ public Thread(ThreadStart start, int maxStackSize) { ArgumentNullException.ThrowIfNull(start); - if (maxStackSize < 0) - { - throw new ArgumentOutOfRangeException(nameof(maxStackSize), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(maxStackSize); _startHelper = new StartHelper(start) { _maxStackSize = maxStackSize }; @@ -143,10 +140,7 @@ public Thread(ParameterizedThreadStart start, int maxStackSize) { ArgumentNullException.ThrowIfNull(start); - if (maxStackSize < 0) - { - throw new ArgumentOutOfRangeException(nameof(maxStackSize), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(maxStackSize); _startHelper = new StartHelper(start) { _maxStackSize = maxStackSize }; @@ -369,8 +363,7 @@ public static Thread CurrentThread [MethodImpl(MethodImplOptions.NoInlining)] // Slow path method. Make sure that the caller frame does not pay for PInvoke overhead. public static void Sleep(int millisecondsTimeout) { - if (millisecondsTimeout < Timeout.Infinite) - throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), millisecondsTimeout, SR.ArgumentOutOfRange_NeedNonNegOrNegative1); + ArgumentOutOfRangeException.ThrowIfLessThan(millisecondsTimeout, Timeout.Infinite); SleepInternal(millisecondsTimeout); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadPoolWorkQueue.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadPoolWorkQueue.cs index 8ad921e002cd5e..eaa0c04226619f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadPoolWorkQueue.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadPoolWorkQueue.cs @@ -1418,8 +1418,7 @@ public static RegisteredWaitHandle RegisterWaitForSingleObject( bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC ) { - if (millisecondsTimeOutInterval < -1) - throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); + ArgumentOutOfRangeException.ThrowIfLessThan(millisecondsTimeOutInterval, -1); return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)millisecondsTimeOutInterval, executeOnlyOnce, true); } @@ -1434,8 +1433,7 @@ public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject( bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC ) { - if (millisecondsTimeOutInterval < -1) - throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); + ArgumentOutOfRangeException.ThrowIfLessThan(millisecondsTimeOutInterval, -1); return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)millisecondsTimeOutInterval, executeOnlyOnce, false); } @@ -1450,10 +1448,8 @@ public static RegisteredWaitHandle RegisterWaitForSingleObject( bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC ) { - if (millisecondsTimeOutInterval < -1) - throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - if (millisecondsTimeOutInterval > (uint)int.MaxValue) - throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_LessEqualToIntegerMaxVal); + ArgumentOutOfRangeException.ThrowIfLessThan(millisecondsTimeOutInterval, -1); + ArgumentOutOfRangeException.ThrowIfGreaterThan(millisecondsTimeOutInterval, int.MaxValue); return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)millisecondsTimeOutInterval, executeOnlyOnce, true); } @@ -1468,10 +1464,8 @@ public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject( bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC ) { - if (millisecondsTimeOutInterval < -1) - throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - if (millisecondsTimeOutInterval > (uint)int.MaxValue) - throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_LessEqualToIntegerMaxVal); + ArgumentOutOfRangeException.ThrowIfLessThan(millisecondsTimeOutInterval, -1); + ArgumentOutOfRangeException.ThrowIfGreaterThan(millisecondsTimeOutInterval, int.MaxValue); return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)millisecondsTimeOutInterval, executeOnlyOnce, false); } @@ -1487,10 +1481,10 @@ bool executeOnlyOnce ) { long tm = (long)timeout.TotalMilliseconds; - if (tm < -1) - throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - if (tm > (long)int.MaxValue) - throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_LessEqualToIntegerMaxVal); + + ArgumentOutOfRangeException.ThrowIfLessThan(tm, -1, nameof(timeout)); + ArgumentOutOfRangeException.ThrowIfGreaterThan(tm, int.MaxValue, nameof(timeout)); + return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)tm, executeOnlyOnce, true); } @@ -1506,10 +1500,10 @@ bool executeOnlyOnce ) { long tm = (long)timeout.TotalMilliseconds; - if (tm < -1) - throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - if (tm > (long)int.MaxValue) - throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_LessEqualToIntegerMaxVal); + + ArgumentOutOfRangeException.ThrowIfLessThan(tm, -1, nameof(timeout)); + ArgumentOutOfRangeException.ThrowIfGreaterThan(tm, int.MaxValue, nameof(timeout)); + return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)tm, executeOnlyOnce, false); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Timer.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Timer.cs index d3e566708d72c5..9aecda2bb67914 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Timer.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Timer.cs @@ -825,10 +825,8 @@ internal Timer(TimerCallback callback, int period, bool flowExecutionContext) { - if (dueTime < -1) - throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - if (period < -1) - throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); + ArgumentOutOfRangeException.ThrowIfLessThan(dueTime, -1); + ArgumentOutOfRangeException.ThrowIfLessThan(period, -1); TimerSetup(callback, state, (uint)dueTime, (uint)period, flowExecutionContext); } @@ -839,16 +837,12 @@ public Timer(TimerCallback callback, TimeSpan period) { long dueTm = (long)dueTime.TotalMilliseconds; - if (dueTm < -1) - throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - if (dueTm > MaxSupportedTimeout) - throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_TimeoutTooLarge); + ArgumentOutOfRangeException.ThrowIfLessThan(dueTm, -1, nameof(dueTime)); + ArgumentOutOfRangeException.ThrowIfGreaterThan(dueTm, MaxSupportedTimeout, nameof(dueTime)); long periodTm = (long)period.TotalMilliseconds; - if (periodTm < -1) - throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - if (periodTm > MaxSupportedTimeout) - throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_PeriodTooLarge); + ArgumentOutOfRangeException.ThrowIfLessThan(periodTm, -1); + ArgumentOutOfRangeException.ThrowIfGreaterThan(periodTm, MaxSupportedTimeout, nameof(period)); TimerSetup(callback, state, (uint)dueTm, (uint)periodTm); } @@ -867,14 +861,11 @@ public Timer(TimerCallback callback, long dueTime, long period) { - if (dueTime < -1) - throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - if (period < -1) - throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - if (dueTime > MaxSupportedTimeout) - throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_TimeoutTooLarge); - if (period > MaxSupportedTimeout) - throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_PeriodTooLarge); + ArgumentOutOfRangeException.ThrowIfLessThan(dueTime, -1); + ArgumentOutOfRangeException.ThrowIfLessThan(period, -1); + ArgumentOutOfRangeException.ThrowIfGreaterThan(dueTime, MaxSupportedTimeout); + ArgumentOutOfRangeException.ThrowIfGreaterThan(period, MaxSupportedTimeout); + TimerSetup(callback, state, (uint)dueTime, (uint)period); } @@ -902,10 +893,8 @@ private void TimerSetup(TimerCallback callback, public bool Change(int dueTime, int period) { - if (dueTime < -1) - throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - if (period < -1) - throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); + ArgumentOutOfRangeException.ThrowIfLessThan(dueTime, -1); + ArgumentOutOfRangeException.ThrowIfLessThan(period, -1); return _timer._timer.Change((uint)dueTime, (uint)period); } @@ -923,14 +912,10 @@ public bool Change(uint dueTime, uint period) public bool Change(long dueTime, long period) { - if (dueTime < -1) - throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - if (period < -1) - throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - if (dueTime > MaxSupportedTimeout) - throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_TimeoutTooLarge); - if (period > MaxSupportedTimeout) - throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_PeriodTooLarge); + ArgumentOutOfRangeException.ThrowIfLessThan(dueTime, -1); + ArgumentOutOfRangeException.ThrowIfLessThan(period, -1); + ArgumentOutOfRangeException.ThrowIfGreaterThan(dueTime, MaxSupportedTimeout); + ArgumentOutOfRangeException.ThrowIfGreaterThan(period, MaxSupportedTimeout); return _timer._timer.Change((uint)dueTime, (uint)period); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/WaitHandle.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/WaitHandle.cs index f60fecc5933352..ef7fcfffe6d09b 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/WaitHandle.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/WaitHandle.cs @@ -77,14 +77,8 @@ public SafeWaitHandle SafeWaitHandle internal static int ToTimeoutMilliseconds(TimeSpan timeout) { long timeoutMilliseconds = (long)timeout.TotalMilliseconds; - if (timeoutMilliseconds < -1) - { - throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - } - if (timeoutMilliseconds > int.MaxValue) - { - throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_LessEqualToIntegerMaxVal); - } + ArgumentOutOfRangeException.ThrowIfLessThan(timeoutMilliseconds, -1); + ArgumentOutOfRangeException.ThrowIfGreaterThan(timeoutMilliseconds, int.MaxValue); return (int)timeoutMilliseconds; } @@ -103,10 +97,7 @@ public void Dispose() public virtual bool WaitOne(int millisecondsTimeout) { - if (millisecondsTimeout < -1) - { - throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - } + ArgumentOutOfRangeException.ThrowIfLessThan(millisecondsTimeout, -1); return WaitOneNoCheck(millisecondsTimeout); } @@ -255,10 +246,7 @@ private static int WaitMultiple(ReadOnlySpan waitHandles, bool waitA { throw new NotSupportedException(SR.NotSupported_MaxWaitHandles); } - if (millisecondsTimeout < -1) - { - throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - } + ArgumentOutOfRangeException.ThrowIfLessThan(millisecondsTimeout, -1); SynchronizationContext? context = SynchronizationContext.Current; bool useWaitContext = context != null && context.IsWaitNotificationRequired(); @@ -355,10 +343,7 @@ private static bool SignalAndWait(WaitHandle toSignal, WaitHandle toWaitOn, int ArgumentNullException.ThrowIfNull(toSignal); ArgumentNullException.ThrowIfNull(toWaitOn); - if (millisecondsTimeout < -1) - { - throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - } + ArgumentOutOfRangeException.ThrowIfLessThan(millisecondsTimeout, -1); // The field value is modifiable via the public property, save it locally // to ensure that one instance is used in all places in this method diff --git a/src/libraries/System.Private.CoreLib/src/System/Type.cs b/src/libraries/System.Private.CoreLib/src/System/Type.cs index 0ab6e955e37d99..270f3d2348b4ba 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Type.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Type.cs @@ -327,9 +327,7 @@ private protected static ArgumentException CreateGetMemberWithSameMetadataDefini public MethodInfo? GetMethod(string name, int genericParameterCount, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers) { ArgumentNullException.ThrowIfNull(name); - - if (genericParameterCount < 0) - throw new ArgumentException(SR.ArgumentOutOfRange_NeedNonNegNum, nameof(genericParameterCount)); + ArgumentOutOfRangeException.ThrowIfNegative(genericParameterCount); ArgumentNullException.ThrowIfNull(types); for (int i = 0; i < types.Length; i++) { @@ -602,8 +600,7 @@ public virtual Array GetEnumValues() public static Type MakeGenericMethodParameter(int position) { - if (position < 0) - throw new ArgumentException(SR.ArgumentOutOfRange_NeedNonNegNum, nameof(position)); + ArgumentOutOfRangeException.ThrowIfNegative(position); return new SignatureGenericMethodParameterType(position); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Version.cs b/src/libraries/System.Private.CoreLib/src/System/Version.cs index c672ef8d69d07c..5b8f4b0c5fc248 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Version.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Version.cs @@ -346,10 +346,8 @@ private static bool TryParseComponent(ReadOnlySpan component, string compo { if (throwOnFailure) { - if ((parsedComponent = int.Parse(component, NumberStyles.Integer, CultureInfo.InvariantCulture)) < 0) - { - throw new ArgumentOutOfRangeException(componentName, SR.ArgumentOutOfRange_Version); - } + parsedComponent = int.Parse(component, NumberStyles.Integer, CultureInfo.InvariantCulture); + ArgumentOutOfRangeException.ThrowIfNegative(parsedComponent, componentName); return true; } diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNodeReader.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNodeReader.cs index 3f31cd085e9276..ddbf41d82b8b45 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNodeReader.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNodeReader.cs @@ -557,10 +557,7 @@ public override string GetAttribute(int index) throw new InvalidOperationException(SR.InvalidOperation_ExpectedInteractive); } - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); XElement? e = GetElementInAttributeScope(); if (e != null) @@ -697,7 +694,7 @@ public override void MoveToAttribute(int index) { return; } - if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); + ArgumentOutOfRangeException.ThrowIfNegative(index); XElement? e = GetElementInAttributeScope(); if (e != null) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Base64Decoder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Base64Decoder.cs index 1352e3e9f1b705..bb8dbbd5f63a59 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Base64Decoder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Base64Decoder.cs @@ -46,18 +46,9 @@ internal override int Decode(char[] chars, int startPos, int len) { ArgumentNullException.ThrowIfNull(chars); - if (len < 0) - { - throw new ArgumentOutOfRangeException(nameof(len)); - } - if (startPos < 0) - { - throw new ArgumentOutOfRangeException(nameof(startPos)); - } - if (chars.Length - startPos < len) - { - throw new ArgumentOutOfRangeException(nameof(len)); - } + ArgumentOutOfRangeException.ThrowIfNegative(len); + ArgumentOutOfRangeException.ThrowIfNegative(startPos); + ArgumentOutOfRangeException.ThrowIfGreaterThan(len, chars.Length - startPos); if (len == 0) { @@ -74,18 +65,9 @@ internal override int Decode(string str, int startPos, int len) { ArgumentNullException.ThrowIfNull(str); - if (len < 0) - { - throw new ArgumentOutOfRangeException(nameof(len)); - } - if (startPos < 0) - { - throw new ArgumentOutOfRangeException(nameof(startPos)); - } - if (str.Length - startPos < len) - { - throw new ArgumentOutOfRangeException(nameof(len)); - } + ArgumentOutOfRangeException.ThrowIfNegative(len); + ArgumentOutOfRangeException.ThrowIfNegative(startPos); + ArgumentOutOfRangeException.ThrowIfGreaterThan(len, str.Length - startPos); if (len == 0) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Base64Encoder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Base64Encoder.cs index 720b5d460509fe..5405e91d99ed8e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Base64Encoder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Base64Encoder.cs @@ -26,18 +26,9 @@ internal void Encode(byte[] buffer, int index, int count) { ArgumentNullException.ThrowIfNull(buffer); - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - if (count > buffer.Length - index) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfGreaterThan(count, buffer.Length - index); // encode left-over buffer if (_leftOverBytesCount > 0) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/BinHexDecoder.cs b/src/libraries/System.Private.Xml/src/System/Xml/BinHexDecoder.cs index 352dfd92400b6f..502f3d5d4d1446 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/BinHexDecoder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/BinHexDecoder.cs @@ -41,18 +41,9 @@ internal override int Decode(char[] chars, int startPos, int len) { ArgumentNullException.ThrowIfNull(chars); - if (len < 0) - { - throw new ArgumentOutOfRangeException(nameof(len)); - } - if (startPos < 0) - { - throw new ArgumentOutOfRangeException(nameof(startPos)); - } - if (chars.Length - startPos < len) - { - throw new ArgumentOutOfRangeException(nameof(len)); - } + ArgumentOutOfRangeException.ThrowIfNegative(len); + ArgumentOutOfRangeException.ThrowIfNegative(startPos); + ArgumentOutOfRangeException.ThrowIfGreaterThan(len, chars.Length - startPos); if (len == 0) { @@ -71,18 +62,9 @@ internal override int Decode(string str, int startPos, int len) { ArgumentNullException.ThrowIfNull(str); - if (len < 0) - { - throw new ArgumentOutOfRangeException(nameof(len)); - } - if (startPos < 0) - { - throw new ArgumentOutOfRangeException(nameof(startPos)); - } - if (str.Length - startPos < len) - { - throw new ArgumentOutOfRangeException(nameof(len)); - } + ArgumentOutOfRangeException.ThrowIfNegative(len); + ArgumentOutOfRangeException.ThrowIfNegative(startPos); + ArgumentOutOfRangeException.ThrowIfGreaterThan(len, str.Length - startPos); if (len == 0) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/BinHexEncoder.cs b/src/libraries/System.Private.Xml/src/System/Xml/BinHexEncoder.cs index dd0f19a19add8b..b60679e1a78b15 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/BinHexEncoder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/BinHexEncoder.cs @@ -11,18 +11,9 @@ internal static void Encode(byte[] buffer, int index, int count, XmlWriter write { ArgumentNullException.ThrowIfNull(buffer); - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - if (count > buffer.Length - index) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfGreaterThan(count, buffer.Length - index); char[] chars = new char[(count * 2) < CharsChunkSize ? (count * 2) : CharsChunkSize]; int endIndex = index + count; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/ReadContentAsBinaryHelper.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/ReadContentAsBinaryHelper.cs index 7b8420a7908f57..6b9aeb6a349cf6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/ReadContentAsBinaryHelper.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/ReadContentAsBinaryHelper.cs @@ -63,18 +63,9 @@ internal static ReadContentAsBinaryHelper CreateOrReset(ReadContentAsBinaryHelpe internal int ReadContentAsBase64(byte[] buffer, int index, int count) { ArgumentNullException.ThrowIfNull(buffer); - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - if (buffer.Length - index < count) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfGreaterThan(count, buffer.Length - index); switch (_state) { @@ -115,18 +106,9 @@ internal int ReadContentAsBase64(byte[] buffer, int index, int count) internal int ReadContentAsBinHex(byte[] buffer, int index, int count) { ArgumentNullException.ThrowIfNull(buffer); - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - if (buffer.Length - index < count) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfGreaterThan(count, buffer.Length - index); switch (_state) { @@ -167,18 +149,9 @@ internal int ReadContentAsBinHex(byte[] buffer, int index, int count) internal int ReadElementContentAsBase64(byte[] buffer, int index, int count) { ArgumentNullException.ThrowIfNull(buffer); - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - if (buffer.Length - index < count) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfGreaterThan(count, buffer.Length - index); switch (_state) { @@ -219,18 +192,9 @@ internal int ReadElementContentAsBase64(byte[] buffer, int index, int count) internal int ReadElementContentAsBinHex(byte[] buffer, int index, int count) { ArgumentNullException.ThrowIfNull(buffer); - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - if (buffer.Length - index < count) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfGreaterThan(count, buffer.Length - index); switch (_state) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingReader.cs index 3aeefe3b256f49..0d3b9bb88eef36 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingReader.cs @@ -479,18 +479,9 @@ public override int ReadContentAsBinHex(byte[] buffer, int index, int count) public override int ReadElementContentAsBase64(byte[] buffer, int index, int count) { ArgumentNullException.ThrowIfNull(buffer); - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - if (buffer.Length - index < count) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfGreaterThan(count, buffer.Length - index); if (ReadState != ReadState.Interactive) { @@ -536,18 +527,9 @@ public override int ReadElementContentAsBase64(byte[] buffer, int index, int cou public override int ReadElementContentAsBinHex(byte[] buffer, int index, int count) { ArgumentNullException.ThrowIfNull(buffer); - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - if (buffer.Length - index < count) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfGreaterThan(count, buffer.Length - index); if (ReadState != ReadState.Interactive) { return 0; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriter.cs index 3c4c24b97808e9..f16e3b69d2b2da 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriter.cs @@ -270,18 +270,9 @@ public override void WriteChars(char[] buffer, int index, int count) { ArgumentNullException.ThrowIfNull(buffer); - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - if (count > buffer.Length - index) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfGreaterThan(count, buffer.Length - index); if (_checkValues) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriterAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriterAsync.cs index 8975998c46f6e8..eee4b81c1ed2a9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriterAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriterAsync.cs @@ -218,18 +218,9 @@ public override Task WriteCharsAsync(char[] buffer, int index, int count) { ArgumentNullException.ThrowIfNull(buffer); - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - if (count > buffer.Length - index) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfGreaterThan(count, buffer.Length - index); if (_checkValues) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSubtreeReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSubtreeReader.cs index f399f2c2556bb7..7994545eea712d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSubtreeReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSubtreeReader.cs @@ -1581,18 +1581,9 @@ private static void CheckBuffer(Array buffer, int index, int count) { ArgumentNullException.ThrowIfNull(buffer); - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - if (buffer.Length - index < count) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfGreaterThan(count, buffer.Length - index); } } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextEncoder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextEncoder.cs index 32d9d35cf8baa4..76ad973526d99e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextEncoder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextEncoder.cs @@ -111,20 +111,9 @@ internal void Write(char[] array, int offset, int count) { ArgumentNullException.ThrowIfNull(array); - if (0 > offset) - { - throw new ArgumentOutOfRangeException(nameof(offset)); - } - - if (0 > count) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - - if (count > array.Length - offset) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } + ArgumentOutOfRangeException.ThrowIfNegative(offset); + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfGreaterThan(count, array.Length - offset); if (_cacheAttrValue) { @@ -448,20 +437,9 @@ internal void WriteRaw(char[] array, int offset, int count) { ArgumentNullException.ThrowIfNull(array); - if (0 > count) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - - if (0 > offset) - { - throw new ArgumentOutOfRangeException(nameof(offset)); - } - - if (count > array.Length - offset) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfNegative(offset); + ArgumentOutOfRangeException.ThrowIfGreaterThan(count, array.Length - offset); if (_cacheAttrValue) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs index c1707fd21a36ca..f4f4476a147339 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs @@ -1596,18 +1596,9 @@ public override bool CanReadBinaryContent public override int ReadContentAsBase64(byte[] buffer, int index, int count) { ArgumentNullException.ThrowIfNull(buffer); - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - if (buffer.Length - index < count) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfGreaterThan(count, buffer.Length - index); // if not the first call to ReadContentAsBase64 if (_parsingFunction == ParsingFunction.InReadContentAsBinary) @@ -1652,18 +1643,9 @@ public override int ReadContentAsBase64(byte[] buffer, int index, int count) public override int ReadContentAsBinHex(byte[] buffer, int index, int count) { ArgumentNullException.ThrowIfNull(buffer); - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - if (buffer.Length - index < count) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfGreaterThan(count, buffer.Length - index); // if not the first call to ReadContentAsBinHex if (_parsingFunction == ParsingFunction.InReadContentAsBinary) @@ -1707,18 +1689,9 @@ public override int ReadContentAsBinHex(byte[] buffer, int index, int count) public override int ReadElementContentAsBase64(byte[] buffer, int index, int count) { ArgumentNullException.ThrowIfNull(buffer); - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - if (buffer.Length - index < count) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfGreaterThan(count, buffer.Length - index); // if not the first call to ReadContentAsBase64 if (_parsingFunction == ParsingFunction.InReadElementContentAsBinary) @@ -1763,18 +1736,9 @@ public override int ReadElementContentAsBase64(byte[] buffer, int index, int cou public override int ReadElementContentAsBinHex(byte[] buffer, int index, int count) { ArgumentNullException.ThrowIfNull(buffer); - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - if (buffer.Length - index < count) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfGreaterThan(count, buffer.Length - index); // if not the first call to ReadContentAsBinHex if (_parsingFunction == ParsingFunction.InReadElementContentAsBinary) @@ -1832,18 +1796,9 @@ public override int ReadValueChunk(char[] buffer, int index, int count) throw new InvalidOperationException(SR.Format(SR.Xml_InvalidReadValueChunk, _curNode.type)); } ArgumentNullException.ThrowIfNull(buffer); - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - if (buffer.Length - index < count) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfGreaterThan(count, buffer.Length - index); // first call of ReadValueChunk -> initialize incremental read state if (_parsingFunction != ParsingFunction.InReadValueChunk) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplAsync.cs index ca72311182e945..f7b904d4eac802 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplAsync.cs @@ -388,18 +388,9 @@ public override Task ReadContentAsBase64Async(byte[] buffer, int index, int { CheckAsyncCall(); ArgumentNullException.ThrowIfNull(buffer); - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - if (buffer.Length - index < count) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfGreaterThan(count, buffer.Length - index); // if not the first call to ReadContentAsBase64 if (_parsingFunction == ParsingFunction.InReadContentAsBinary) @@ -453,18 +444,9 @@ public override async Task ReadContentAsBinHexAsync(byte[] buffer, int inde { CheckAsyncCall(); ArgumentNullException.ThrowIfNull(buffer); - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - if (buffer.Length - index < count) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfGreaterThan(count, buffer.Length - index); // if not the first call to ReadContentAsBinHex if (_parsingFunction == ParsingFunction.InReadContentAsBinary) @@ -527,18 +509,9 @@ public override Task ReadElementContentAsBase64Async(byte[] buffer, int ind { CheckAsyncCall(); ArgumentNullException.ThrowIfNull(buffer); - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - if (buffer.Length - index < count) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfGreaterThan(count, buffer.Length - index); // if not the first call to ReadContentAsBase64 if (_parsingFunction == ParsingFunction.InReadElementContentAsBinary) @@ -592,18 +565,9 @@ public override async Task ReadElementContentAsBinHexAsync(byte[] buffer, i { CheckAsyncCall(); ArgumentNullException.ThrowIfNull(buffer); - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - if (buffer.Length - index < count) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfGreaterThan(count, buffer.Length - index); // if not the first call to ReadContentAsBinHex if (_parsingFunction == ParsingFunction.InReadElementContentAsBinary) @@ -653,18 +617,9 @@ public override async Task ReadValueChunkAsync(char[] buffer, int index, in throw new InvalidOperationException(SR.Format(SR.Xml_InvalidReadValueChunk, _curNode.type)); } ArgumentNullException.ThrowIfNull(buffer); - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - if (buffer.Length - index < count) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfGreaterThan(count, buffer.Length - index); // first call of ReadValueChunk -> initialize incremental read state if (_parsingFunction != ParsingFunction.InReadValueChunk) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriter.cs index 7e97af503db3fc..ad7903433b7c48 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriter.cs @@ -1073,18 +1073,9 @@ public override void WriteChars(char[] buffer, int index, int count) try { ArgumentNullException.ThrowIfNull(buffer); - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - if (count > buffer.Length - index) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfGreaterThan(count, buffer.Length - index); AdvanceState(Token.Text); if (SaveAttrValue) @@ -1108,18 +1099,9 @@ public override void WriteRaw(char[] buffer, int index, int count) try { ArgumentNullException.ThrowIfNull(buffer); - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - if (count > buffer.Length - index) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfGreaterThan(count, buffer.Length - index); AdvanceState(Token.RawData); if (SaveAttrValue) @@ -1169,18 +1151,9 @@ public override void WriteBase64(byte[] buffer, int index, int count) try { ArgumentNullException.ThrowIfNull(buffer); - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - if (count > buffer.Length - index) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfGreaterThan(count, buffer.Length - index); AdvanceState(Token.Base64); _writer.WriteBase64(buffer, index, count); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterAsync.cs index f6e02486f66858..efc1ae2bab6591 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterAsync.cs @@ -1013,18 +1013,9 @@ public override async Task WriteCharsAsync(char[] buffer, int index, int count) try { ArgumentNullException.ThrowIfNull(buffer); - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - if (count > buffer.Length - index) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfGreaterThan(count, buffer.Length - index); await AdvanceStateAsync(Token.Text).ConfigureAwait(false); if (SaveAttrValue) @@ -1048,18 +1039,9 @@ public override async Task WriteRawAsync(char[] buffer, int index, int count) try { ArgumentNullException.ThrowIfNull(buffer); - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - if (count > buffer.Length - index) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfGreaterThan(count, buffer.Length - index); await AdvanceStateAsync(Token.RawData).ConfigureAwait(false); if (SaveAttrValue) @@ -1109,18 +1091,9 @@ public override Task WriteBase64Async(byte[] buffer, int index, int count) try { ArgumentNullException.ThrowIfNull(buffer); - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - if (count > buffer.Length - index) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfGreaterThan(count, buffer.Length - index); Task task = AdvanceStateAsync(Token.Base64); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlText.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlText.cs index 788c2e2e1ea147..ccbd3578e7757b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlText.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlText.cs @@ -105,8 +105,7 @@ public virtual XmlText SplitText(int offset) { XmlNode? parentNode = this.ParentNode; int length = this.Length; - if (offset > length) - throw new ArgumentOutOfRangeException(nameof(offset)); + ArgumentOutOfRangeException.ThrowIfGreaterThan(offset, length); //if the text node is out of the living tree, throw exception. if (parentNode == null) throw new InvalidOperationException(SR.Xdom_TextNode_SplitText); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/NameTable.cs b/src/libraries/System.Private.Xml/src/System/Xml/NameTable.cs index e708bb83770c6c..a47436ccbd8b27 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/NameTable.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/NameTable.cs @@ -94,10 +94,7 @@ public override string Add(char[] key, int start, int len) } // Compatibility check for len < 0, just throw the same exception as new string(key, start, len) - if (len < 0) - { - throw new ArgumentOutOfRangeException(nameof(len)); - } + ArgumentOutOfRangeException.ThrowIfNegative(len); int hashCode = string.GetHashCode(key.AsSpan(start, len)); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Resolvers/XmlPreloadedResolver.cs b/src/libraries/System.Private.Xml/src/System/Xml/Resolvers/XmlPreloadedResolver.cs index a5e616d6391282..98a4e76ca380ec 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Resolvers/XmlPreloadedResolver.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Resolvers/XmlPreloadedResolver.cs @@ -292,18 +292,9 @@ public void Add(Uri uri, byte[] value, int offset, int count) ArgumentNullException.ThrowIfNull(uri); ArgumentNullException.ThrowIfNull(value); - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - if (offset < 0) - { - throw new ArgumentOutOfRangeException(nameof(offset)); - } - if (value.Length - offset < count) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfNegative(offset); + ArgumentOutOfRangeException.ThrowIfGreaterThan(count, value.Length - offset); Add(uri, new ByteArrayChunk(value, offset, count)); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaCollection.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaCollection.cs index 2dc4d66f0a972e..918fc6c4348156 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaCollection.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaCollection.cs @@ -228,8 +228,7 @@ void ICollection.CopyTo(Array array, int index) { ArgumentNullException.ThrowIfNull(array); - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index)); + ArgumentOutOfRangeException.ThrowIfNegative(index); for (XmlSchemaCollectionEnumerator e = this.GetEnumerator(); e.MoveNext();) { if (index == array.Length) @@ -244,8 +243,7 @@ public void CopyTo(XmlSchema[] array, int index) { ArgumentNullException.ThrowIfNull(array); - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index)); + ArgumentOutOfRangeException.ThrowIfNegative(index); for (XmlSchemaCollectionEnumerator e = this.GetEnumerator(); e.MoveNext();) { XmlSchema? schema = e.Current; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaObjectTable.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaObjectTable.cs index 8bccc26d7ceb08..30b5ab0963e832 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaObjectTable.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaObjectTable.cs @@ -190,8 +190,7 @@ public void CopyTo(Array array, int arrayIndex) { ArgumentNullException.ThrowIfNull(array); - if (arrayIndex < 0) - throw new ArgumentOutOfRangeException(nameof(arrayIndex)); + ArgumentOutOfRangeException.ThrowIfNegative(arrayIndex); Debug.Assert(array.Length >= _size, "array is not big enough to hold all the items in the ICollection"); @@ -244,8 +243,7 @@ public void CopyTo(Array array, int arrayIndex) { ArgumentNullException.ThrowIfNull(array); - if (arrayIndex < 0) - throw new ArgumentOutOfRangeException(nameof(arrayIndex)); + ArgumentOutOfRangeException.ThrowIfNegative(arrayIndex); Debug.Assert(array.Length >= _size, "array is not big enough to hold all the items in the ICollection"); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdDuration.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdDuration.cs index 80358d208c796a..f338959ee6a427 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdDuration.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdDuration.cs @@ -47,12 +47,12 @@ public enum DurationType /// public XsdDuration(bool isNegative, int years, int months, int days, int hours, int minutes, int seconds, int nanoseconds) { - if (years < 0) throw new ArgumentOutOfRangeException(nameof(years)); - if (months < 0) throw new ArgumentOutOfRangeException(nameof(months)); - if (days < 0) throw new ArgumentOutOfRangeException(nameof(days)); - if (hours < 0) throw new ArgumentOutOfRangeException(nameof(hours)); - if (minutes < 0) throw new ArgumentOutOfRangeException(nameof(minutes)); - if (seconds < 0) throw new ArgumentOutOfRangeException(nameof(seconds)); + ArgumentOutOfRangeException.ThrowIfNegative(years); + ArgumentOutOfRangeException.ThrowIfNegative(months); + ArgumentOutOfRangeException.ThrowIfNegative(days); + ArgumentOutOfRangeException.ThrowIfNegative(hours); + ArgumentOutOfRangeException.ThrowIfNegative(minutes); + ArgumentOutOfRangeException.ThrowIfNegative(seconds); if (nanoseconds < 0 || nanoseconds > 999999999) throw new ArgumentOutOfRangeException(nameof(nanoseconds)); _years = years; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQuerySequence.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQuerySequence.cs index 54894e7a2b1732..a887325887bd96 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQuerySequence.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQuerySequence.cs @@ -245,8 +245,7 @@ bool System.Collections.IList.IsReadOnly { get { - if (index >= _size) - throw new ArgumentOutOfRangeException(nameof(index)); + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(index, _size); return _items[index]; } @@ -321,8 +320,7 @@ public T this[int index] { get { - if (index >= _size) - throw new ArgumentOutOfRangeException(nameof(index)); + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(index, _size); return _items[index]; } @@ -726,8 +724,7 @@ XPathItem IList.this[int index] { get { - if (index >= Count) - throw new ArgumentOutOfRangeException(nameof(index)); + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(index, Count); return base[index]; } diff --git a/src/libraries/System.Security.AccessControl/src/Resources/Strings.resx b/src/libraries/System.Security.AccessControl/src/Resources/Strings.resx index f425668a7404b7..b3c932535261b4 100644 --- a/src/libraries/System.Security.AccessControl/src/Resources/Strings.resx +++ b/src/libraries/System.Security.AccessControl/src/Resources/Strings.resx @@ -156,9 +156,6 @@ User-defined ACEs must not have a well-known ACE type. - - Non-negative number required. - This access control list is not in canonical form and therefore cannot be modified. @@ -198,4 +195,4 @@ Access Control List (ACL) APIs are part of resource management on Windows and are not supported on this platform. - \ No newline at end of file + diff --git a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACE.cs b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACE.cs index 1ee2824659ddd0..4932b83e822eb9 100644 --- a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACE.cs +++ b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACE.cs @@ -114,13 +114,8 @@ internal void MarshalHeader(byte[] binaryForm, int offset) int Length = BinaryLength; // Invokes the most derived property - if (offset < 0) - { - throw new ArgumentOutOfRangeException( - nameof(offset), - SR.ArgumentOutOfRange_NeedNonNegNum); - } - else if (binaryForm.Length - offset < BinaryLength) + ArgumentOutOfRangeException.ThrowIfNegative(offset); + if (binaryForm.Length - offset < BinaryLength) { // // The buffer will not fit the header @@ -243,13 +238,8 @@ internal static void VerifyHeader(byte[] binaryForm, int offset) { ArgumentNullException.ThrowIfNull(binaryForm); - if (offset < 0) - { - throw new ArgumentOutOfRangeException( - nameof(offset), - SR.ArgumentOutOfRange_NeedNonNegNum); - } - else if (binaryForm.Length - offset < HeaderLength) + ArgumentOutOfRangeException.ThrowIfNegative(offset); + if (binaryForm.Length - offset < HeaderLength) { // // We expect at least the ACE header ( 4 bytes ) diff --git a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACL.cs b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACL.cs index d4e7a294e538f3..13d19509d57822 100644 --- a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACL.cs +++ b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACL.cs @@ -173,11 +173,8 @@ void ICollection.CopyTo(Array array, int index) throw new RankException(SR.Rank_MultiDimNotSupported); } - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); - } - else if (array.Length - index < Count) + ArgumentOutOfRangeException.ThrowIfNegative(index); + if (array.Length - index < Count) { throw new ArgumentOutOfRangeException(nameof(array), SR.ArgumentOutOfRange_ArrayTooSmall); } @@ -238,14 +235,7 @@ private static void VerifyHeader(byte[] binaryForm, int offset, out byte revisio { ArgumentNullException.ThrowIfNull(binaryForm); - if (offset < 0) - { - // - // Offset must not be negative - // - - throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(offset); if (binaryForm.Length - offset < HeaderLength) { @@ -281,11 +271,8 @@ private void MarshalHeader(byte[] binaryForm, int offset) { ArgumentNullException.ThrowIfNull(binaryForm); - if (offset < 0) - { - throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); - } - else if (BinaryLength > MaxBinaryLength) + ArgumentOutOfRangeException.ThrowIfNegative(offset); + if (BinaryLength > MaxBinaryLength) { throw new InvalidOperationException(SR.AccessControl_AclTooLong); } diff --git a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/SecurityDescriptor.cs b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/SecurityDescriptor.cs index c82fbacc1f4450..2320b2ddefa0df 100644 --- a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/SecurityDescriptor.cs +++ b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/SecurityDescriptor.cs @@ -261,11 +261,7 @@ public void GetBinaryForm(byte[] binaryForm, int offset) { ArgumentNullException.ThrowIfNull(binaryForm); - if (offset < 0) - { - throw new ArgumentOutOfRangeException(nameof(offset), - SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(offset); if (binaryForm.Length - offset < BinaryLength) { @@ -472,15 +468,7 @@ public RawSecurityDescriptor(byte[] binaryForm, int offset) // The array passed in must be valid // - if (offset < 0) - { - // - // Offset must not be negative - // - - throw new ArgumentOutOfRangeException(nameof(offset), - SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(offset); // // At least make sure the header is in place diff --git a/src/libraries/System.Security.Cryptography/src/Resources/Strings.resx b/src/libraries/System.Security.Cryptography/src/Resources/Strings.resx index 4dc40bba0b1b7a..7d06f8e688ac89 100644 --- a/src/libraries/System.Security.Cryptography/src/Resources/Strings.resx +++ b/src/libraries/System.Security.Cryptography/src/Resources/Strings.resx @@ -159,9 +159,6 @@ Non-negative number required. - - Positive number required. - An empty custom trust store is not supported on this platform. diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CryptoStream.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CryptoStream.cs index 71b9d9115115b5..8eac210d621d52 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CryptoStream.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CryptoStream.cs @@ -723,8 +723,7 @@ private void CheckCopyToArguments(Stream destination, int bufferSize) if (!destination.CanWrite) throw new NotSupportedException(SR.NotSupported_UnwritableStream); - if (bufferSize <= 0) - throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(bufferSize); if (!CanRead) throw new NotSupportedException(SR.NotSupported_UnreadableStream); } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSACryptoServiceProvider.Unix.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSACryptoServiceProvider.Unix.cs index 41fff5154c8c7f..7ff86dec1e9ddc 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSACryptoServiceProvider.Unix.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSACryptoServiceProvider.Unix.cs @@ -47,8 +47,7 @@ public DSACryptoServiceProvider() [UnsupportedOSPlatform("tvos")] public DSACryptoServiceProvider(int dwKeySize) : base() { - if (dwKeySize < 0) - throw new ArgumentOutOfRangeException(nameof(dwKeySize), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(dwKeySize); // This class wraps DSA _impl = DSA.Create(); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSACryptoServiceProvider.Windows.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSACryptoServiceProvider.Windows.cs index df1d311acad6c7..618b6c225f2827 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSACryptoServiceProvider.Windows.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSACryptoServiceProvider.Windows.cs @@ -68,8 +68,7 @@ public DSACryptoServiceProvider(CspParameters? parameters) [SupportedOSPlatform("windows")] public DSACryptoServiceProvider(int dwKeySize, CspParameters? parameters) { - if (dwKeySize < 0) - throw new ArgumentOutOfRangeException(nameof(dwKeySize), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(dwKeySize); _parameters = CapiHelper.SaveCspParameters( CapiHelper.CspAlgorithmType.Dss, diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HKDF.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HKDF.cs index 11fcc9fef17b7e..abb85e9a972e8c 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HKDF.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HKDF.cs @@ -85,8 +85,7 @@ public static byte[] Expand(HashAlgorithmName hashAlgorithmName, byte[] prk, int { ArgumentNullException.ThrowIfNull(prk); - if (outputLength <= 0) - throw new ArgumentOutOfRangeException(nameof(outputLength), SR.ArgumentOutOfRange_NeedPosNum); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(outputLength); int hashLength = HashLength(hashAlgorithmName); @@ -210,8 +209,7 @@ public static byte[] DeriveKey(HashAlgorithmName hashAlgorithmName, byte[] ikm, { ArgumentNullException.ThrowIfNull(ikm); - if (outputLength <= 0) - throw new ArgumentOutOfRangeException(nameof(outputLength), SR.ArgumentOutOfRange_NeedPosNum); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(outputLength); int hashLength = HashLength(hashAlgorithmName); Debug.Assert(hashLength <= 512 / 8, "hashLength is larger than expected, consider increasing this value or using regular allocation"); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HashAlgorithm.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HashAlgorithm.cs index add544fafff49c..1f570eeb22fc5f 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HashAlgorithm.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HashAlgorithm.cs @@ -77,8 +77,7 @@ public byte[] ComputeHash(byte[] buffer, int offset, int count) { ArgumentNullException.ThrowIfNull(buffer); - if (offset < 0) - throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(offset); if (count < 0 || (count > buffer.Length)) throw new ArgumentException(SR.Argument_InvalidValue); if ((buffer.Length - count) < offset) @@ -236,8 +235,7 @@ private void ValidateTransformBlock(byte[] inputBuffer, int inputOffset, int inp { ArgumentNullException.ThrowIfNull(inputBuffer); - if (inputOffset < 0) - throw new ArgumentOutOfRangeException(nameof(inputOffset), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(inputOffset); if (inputCount < 0 || inputCount > inputBuffer.Length) throw new ArgumentException(SR.Argument_InvalidValue); if ((inputBuffer.Length - inputCount) < inputOffset) diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HashProvider.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HashProvider.cs index 281634063f2918..926d9c4627eab9 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HashProvider.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HashProvider.cs @@ -21,10 +21,8 @@ public void AppendHashData(byte[] data, int offset, int count) // also receive a bad count from HashAlgorithm reading from a Stream that returns // an invalid number of bytes read. Since our implementations of AppendHashDataCore // end up using unsafe code, we want to be sure the arguments are valid. - if (offset < 0) - throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); - if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(offset); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (data.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/IncrementalHash.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/IncrementalHash.cs index 29bb8cc722164a..904c72c1c28050 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/IncrementalHash.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/IncrementalHash.cs @@ -87,10 +87,9 @@ public void AppendData(byte[] data, int offset, int count) { ArgumentNullException.ThrowIfNull(data); - if (offset < 0) - throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); - if (count < 0 || (count > data.Length)) - throw new ArgumentOutOfRangeException(nameof(count)); + ArgumentOutOfRangeException.ThrowIfNegative(offset); + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfGreaterThan(count, data.Length); if ((data.Length - count) < offset) throw new ArgumentException(SR.Argument_InvalidOffLen); ObjectDisposedException.ThrowIf(_disposed, this); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/PasswordDeriveBytes.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/PasswordDeriveBytes.cs index db227e67a5d490..6ece0e62b4e3ab 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/PasswordDeriveBytes.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/PasswordDeriveBytes.cs @@ -86,8 +86,7 @@ public int IterationCount get { return _iterations; } set { - if (value <= 0) - throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedPosNum); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(value); if (_baseValue != null) throw new CryptographicException(SR.Cryptography_PasswordDerivedBytes_ValuesFixed, nameof(IterationCount)); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/PbeParameters.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/PbeParameters.cs index 40f7b508867b3a..be84f23d7d8c44 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/PbeParameters.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/PbeParameters.cs @@ -14,13 +14,7 @@ public PbeParameters( HashAlgorithmName hashAlgorithm, int iterationCount) { - if (iterationCount < 1) - { - throw new ArgumentOutOfRangeException( - nameof(iterationCount), - iterationCount, - SR.ArgumentOutOfRange_NeedPosNum); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(iterationCount); EncryptionAlgorithm = encryptionAlgorithm; HashAlgorithm = hashAlgorithm; diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/PemEncoding.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/PemEncoding.cs index 6e157c2fc59e5d..7bd87738e53b18 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/PemEncoding.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/PemEncoding.cs @@ -353,10 +353,8 @@ public static int GetEncodedSize(int labelLength, int dataLength) // is accounted for assuming an empty label. const int MaxDataLength = 1_585_834_053; - if (labelLength < 0) - throw new ArgumentOutOfRangeException(nameof(labelLength), SR.ArgumentOutOfRange_NeedPosNum); - if (dataLength < 0) - throw new ArgumentOutOfRangeException(nameof(dataLength), SR.ArgumentOutOfRange_NeedPosNum); + ArgumentOutOfRangeException.ThrowIfNegative(labelLength); + ArgumentOutOfRangeException.ThrowIfNegative(dataLength); if (labelLength > MaxLabelSize) throw new ArgumentOutOfRangeException(nameof(labelLength), SR.Argument_PemEncoding_EncodedSizeTooLarge); if (dataLength > MaxDataLength) diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSACryptoServiceProvider.Unix.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSACryptoServiceProvider.Unix.cs index 374faf2d85d376..8cb55d97b6aabe 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSACryptoServiceProvider.Unix.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSACryptoServiceProvider.Unix.cs @@ -21,8 +21,7 @@ public RSACryptoServiceProvider() [UnsupportedOSPlatform("browser")] public RSACryptoServiceProvider(int dwKeySize) { - if (dwKeySize < 0) - throw new ArgumentOutOfRangeException(nameof(dwKeySize), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(dwKeySize); // This class wraps RSA _impl = RSA.Create(dwKeySize); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSACryptoServiceProvider.Windows.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSACryptoServiceProvider.Windows.cs index 5050cd0e4796a7..b327866789cbd8 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSACryptoServiceProvider.Windows.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSACryptoServiceProvider.Windows.cs @@ -54,10 +54,7 @@ public RSACryptoServiceProvider(CspParameters? parameters) private RSACryptoServiceProvider(int keySize, CspParameters? parameters, bool useDefaultKeySize) { - if (keySize < 0) - { - throw new ArgumentOutOfRangeException("dwKeySize", "ArgumentOutOfRange_NeedNonNegNum"); - } + ArgumentOutOfRangeException.ThrowIfNegative(keySize); _parameters = CapiHelper.SaveCspParameters( CapiHelper.CspAlgorithmType.Rsa, diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RandomNumberGenerator.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RandomNumberGenerator.cs index 88f6ca8a8d2c57..b227e931c443c4 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RandomNumberGenerator.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RandomNumberGenerator.cs @@ -139,8 +139,7 @@ public static int GetInt32(int fromInclusive, int toExclusive) public static int GetInt32(int toExclusive) { - if (toExclusive <= 0) - throw new ArgumentOutOfRangeException(nameof(toExclusive), SR.ArgumentOutOfRange_NeedPosNum); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(toExclusive); return GetInt32(0, toExclusive); } @@ -157,8 +156,7 @@ public static int GetInt32(int toExclusive) /// public static byte[] GetBytes(int count) { - if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(count); byte[] ret = new byte[count]; RandomNumberGeneratorImplementation.FillSpan(ret); @@ -169,10 +167,8 @@ internal static void VerifyGetBytes(byte[] data, int offset, int count) { ArgumentNullException.ThrowIfNull(data); - if (offset < 0) - throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); - if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(offset); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (count > data.Length - offset) throw new ArgumentException(SR.Argument_InvalidOffLen); } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/Rfc2898DeriveBytes.OneShot.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/Rfc2898DeriveBytes.OneShot.cs index 9b8f8a9b6af369..c4643a56921e5d 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/Rfc2898DeriveBytes.OneShot.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/Rfc2898DeriveBytes.OneShot.cs @@ -79,10 +79,8 @@ public static byte[] Pbkdf2( HashAlgorithmName hashAlgorithm, int outputLength) { - if (iterations <= 0) - throw new ArgumentOutOfRangeException(nameof(iterations), SR.ArgumentOutOfRange_NeedPosNum); - if (outputLength < 0) - throw new ArgumentOutOfRangeException(nameof(outputLength), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(iterations); + ArgumentOutOfRangeException.ThrowIfNegative(outputLength); ValidateHashAlgorithm(hashAlgorithm); @@ -118,8 +116,7 @@ public static void Pbkdf2( int iterations, HashAlgorithmName hashAlgorithm) { - if (iterations <= 0) - throw new ArgumentOutOfRangeException(nameof(iterations), SR.ArgumentOutOfRange_NeedPosNum); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(iterations); ValidateHashAlgorithm(hashAlgorithm); @@ -209,10 +206,8 @@ public static byte[] Pbkdf2( HashAlgorithmName hashAlgorithm, int outputLength) { - if (outputLength < 0) - throw new ArgumentOutOfRangeException(nameof(outputLength), SR.ArgumentOutOfRange_NeedNonNegNum); - if (iterations <= 0) - throw new ArgumentOutOfRangeException(nameof(iterations), SR.ArgumentOutOfRange_NeedPosNum); + ArgumentOutOfRangeException.ThrowIfNegative(outputLength); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(iterations); ValidateHashAlgorithm(hashAlgorithm); @@ -256,8 +251,7 @@ public static void Pbkdf2( int iterations, HashAlgorithmName hashAlgorithm) { - if (iterations <= 0) - throw new ArgumentOutOfRangeException(nameof(iterations), SR.ArgumentOutOfRange_NeedPosNum); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(iterations); ValidateHashAlgorithm(hashAlgorithm); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/Rfc2898DeriveBytes.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/Rfc2898DeriveBytes.cs index e41f15e4bc5540..736fc089ee9041 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/Rfc2898DeriveBytes.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/Rfc2898DeriveBytes.cs @@ -76,10 +76,8 @@ public Rfc2898DeriveBytes(string password, int saltSize, int iterations) public Rfc2898DeriveBytes(string password, int saltSize, int iterations, HashAlgorithmName hashAlgorithm) { - if (saltSize < 0) - throw new ArgumentOutOfRangeException(nameof(saltSize), SR.ArgumentOutOfRange_NeedNonNegNum); - if (iterations <= 0) - throw new ArgumentOutOfRangeException(nameof(iterations), SR.ArgumentOutOfRange_NeedPosNum); + ArgumentOutOfRangeException.ThrowIfNegative(saltSize); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(iterations); _salt = new byte[saltSize + sizeof(uint)]; RandomNumberGenerator.Fill(_salt.AsSpan(0, saltSize)); @@ -109,8 +107,7 @@ internal Rfc2898DeriveBytes(byte[] password, byte[] salt, int iterations, HashAl internal Rfc2898DeriveBytes(ReadOnlySpan password, ReadOnlySpan salt, int iterations, HashAlgorithmName hashAlgorithm) { - if (iterations <= 0) - throw new ArgumentOutOfRangeException(nameof(iterations), SR.ArgumentOutOfRange_NeedPosNum); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(iterations); _salt = new byte[salt.Length + sizeof(uint)]; salt.CopyTo(_salt); @@ -131,8 +128,7 @@ public int IterationCount set { - if (value <= 0) - throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedPosNum); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(value); _iterations = (uint)value; Initialize(); } @@ -174,8 +170,7 @@ protected override void Dispose(bool disposing) public override byte[] GetBytes(int cb) { - if (cb <= 0) - throw new ArgumentOutOfRangeException(nameof(cb), SR.ArgumentOutOfRange_NeedPosNum); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(cb); byte[] ret = new byte[cb]; GetBytes(ret); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SymmetricAlgorithm.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SymmetricAlgorithm.cs index f9f200ff47b92e..316d2e08f7bd02 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SymmetricAlgorithm.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SymmetricAlgorithm.cs @@ -312,8 +312,7 @@ public int GetCiphertextLengthCbc(int plaintextLength, PaddingMode paddingMode = private int GetCiphertextLengthBlockAligned(int plaintextLength, PaddingMode paddingMode) { - if (plaintextLength < 0) - throw new ArgumentOutOfRangeException(nameof(plaintextLength), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(plaintextLength); int blockSizeBits = BlockSize; // The BlockSize property is in bits. @@ -394,12 +393,8 @@ private int GetCiphertextLengthBlockAligned(int plaintextLength, PaddingMode pad /// public int GetCiphertextLengthCfb(int plaintextLength, PaddingMode paddingMode = PaddingMode.None, int feedbackSizeInBits = 8) { - if (plaintextLength < 0) - throw new ArgumentOutOfRangeException(nameof(plaintextLength), SR.ArgumentOutOfRange_NeedNonNegNum); - - if (feedbackSizeInBits <= 0) - throw new ArgumentOutOfRangeException(nameof(feedbackSizeInBits), SR.ArgumentOutOfRange_NeedPosNum); - + ArgumentOutOfRangeException.ThrowIfNegative(plaintextLength); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(feedbackSizeInBits); if ((feedbackSizeInBits & 0b111) != 0) throw new ArgumentException(SR.Argument_BitsMustBeWholeBytes, nameof(feedbackSizeInBits)); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/UniversalCryptoTransform.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/UniversalCryptoTransform.cs index 0bf92d61b029d6..865b6a54e8617f 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/UniversalCryptoTransform.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/UniversalCryptoTransform.cs @@ -69,20 +69,16 @@ public void Dispose() public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { ArgumentNullException.ThrowIfNull(inputBuffer); - if (inputOffset < 0) - throw new ArgumentOutOfRangeException(nameof(inputOffset)); - if (inputOffset > inputBuffer.Length) - throw new ArgumentOutOfRangeException(nameof(inputOffset)); - if (inputCount <= 0) - throw new ArgumentOutOfRangeException(nameof(inputCount)); + ArgumentOutOfRangeException.ThrowIfNegative(inputOffset); + ArgumentOutOfRangeException.ThrowIfGreaterThan(inputOffset, inputBuffer.Length); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(inputCount); if (inputCount % InputBlockSize != 0) throw new ArgumentOutOfRangeException(nameof(inputCount), SR.Cryptography_MustTransformWholeBlock); if (inputCount > inputBuffer.Length - inputOffset) throw new ArgumentOutOfRangeException(nameof(inputCount), SR.Argument_InvalidOffLen); ArgumentNullException.ThrowIfNull(outputBuffer); - if (outputOffset > outputBuffer.Length) - throw new ArgumentOutOfRangeException(nameof(outputOffset)); + ArgumentOutOfRangeException.ThrowIfGreaterThan(outputOffset, outputBuffer.Length); if (inputCount > outputBuffer.Length - outputOffset) throw new ArgumentOutOfRangeException(nameof(outputOffset), SR.Argument_InvalidOffLen); @@ -95,12 +91,9 @@ public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int input { ArgumentNullException.ThrowIfNull(inputBuffer); - if (inputOffset < 0) - throw new ArgumentOutOfRangeException(nameof(inputOffset)); - if (inputCount < 0) - throw new ArgumentOutOfRangeException(nameof(inputCount)); - if (inputOffset > inputBuffer.Length) - throw new ArgumentOutOfRangeException(nameof(inputOffset)); + ArgumentOutOfRangeException.ThrowIfNegative(inputOffset); + ArgumentOutOfRangeException.ThrowIfNegative(inputCount); + ArgumentOutOfRangeException.ThrowIfGreaterThan(inputOffset, inputBuffer.Length); if (inputCount > inputBuffer.Length - inputOffset) throw new ArgumentOutOfRangeException(nameof(inputCount), SR.Argument_InvalidOffLen); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/CertificateRevocationListBuilder.Build.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/CertificateRevocationListBuilder.Build.cs index f44ed1fa04edc0..ae2d7b1a097ea3 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/CertificateRevocationListBuilder.Build.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/CertificateRevocationListBuilder.Build.cs @@ -136,8 +136,7 @@ private byte[] Build( throw new ArgumentException( SR.Cryptography_CertReq_IssuerRequiresPrivateKey, nameof(issuerCertificate)); - if (crlNumber < 0) - throw new ArgumentOutOfRangeException(nameof(crlNumber), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(crlNumber); if (nextUpdate <= thisUpdate) throw new ArgumentException(SR.Cryptography_CRLBuilder_DatesReversed); @@ -321,8 +320,7 @@ private byte[] Build( ArgumentNullException.ThrowIfNull(issuerName); ArgumentNullException.ThrowIfNull(generator); - if (crlNumber < 0) - throw new ArgumentOutOfRangeException(nameof(crlNumber), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(crlNumber); if (nextUpdate <= thisUpdate) throw new ArgumentException(SR.Cryptography_CRLBuilder_DatesReversed); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509BasicConstraintsExtension.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509BasicConstraintsExtension.cs index f109bc0bcfcc87..d092d06b9d07c3 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509BasicConstraintsExtension.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509BasicConstraintsExtension.cs @@ -106,8 +106,10 @@ public static X509BasicConstraintsExtension CreateForEndEntity(bool critical = f private static byte[] EncodeExtension(bool certificateAuthority, bool hasPathLengthConstraint, int pathLengthConstraint) { - if (hasPathLengthConstraint && pathLengthConstraint < 0) - throw new ArgumentOutOfRangeException(nameof(pathLengthConstraint), SR.ArgumentOutOfRange_NeedNonNegNum); + if (hasPathLengthConstraint) + { + ArgumentOutOfRangeException.ThrowIfNegative(pathLengthConstraint); + } return X509Pal.Instance.EncodeX509BasicConstraints2Extension(certificateAuthority, hasPathLengthConstraint, pathLengthConstraint); } diff --git a/src/libraries/System.Security.Principal.Windows/src/Resources/Strings.resx b/src/libraries/System.Security.Principal.Windows/src/Resources/Strings.resx index ac766cc5e7e886..74d5447db60586 100644 --- a/src/libraries/System.Security.Principal.Windows/src/Resources/Strings.resx +++ b/src/libraries/System.Security.Principal.Windows/src/Resources/Strings.resx @@ -81,9 +81,6 @@ Destination array is not long enough to copy all the required data. Check array length and offset. - - Non-negative number required. - Account name is too long. diff --git a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/SID.cs b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/SID.cs index fc456e219bb167..99e25d4b09fa0d 100644 --- a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/SID.cs +++ b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/SID.cs @@ -400,10 +400,7 @@ private void CreateFromBinaryForm(byte[] binaryForm, int offset) // Negative offsets are not allowed // - if (offset < 0) - { - throw new ArgumentOutOfRangeException(nameof(offset), offset, SR.ArgumentOutOfRange_NeedNonNegNum); - } + ArgumentOutOfRangeException.ThrowIfNegative(offset); // // At least a minimum-size SID should fit in the buffer diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionManager.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionManager.cs index 93a6fefadb88b0..70c6cf24ee8114 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionManager.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionManager.cs @@ -373,10 +373,7 @@ public static TimeSpan MaximumTimeout etwLog.MethodEnter(TraceSourceType.TraceSourceBase, "TransactionManager.set_DefaultMaximumTimeout"); } - if (value < TimeSpan.Zero) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } + ArgumentOutOfRangeException.ThrowIfLessThan(value, TimeSpan.Zero); s_cachedMaxTimeout = true; s_maximumTimeout = value; @@ -535,10 +532,7 @@ internal static void ValidateIsolationLevel(IsolationLevel transactionIsolationL /// internal static TimeSpan ValidateTimeout(TimeSpan transactionTimeout) { - if (transactionTimeout < TimeSpan.Zero) - { - throw new ArgumentOutOfRangeException(nameof(transactionTimeout)); - } + ArgumentOutOfRangeException.ThrowIfLessThan(transactionTimeout, TimeSpan.Zero); if (MaximumTimeout != TimeSpan.Zero) { diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionScope.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionScope.cs index b761e13c0c2ded..71edfdf6103259 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionScope.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionScope.cs @@ -1122,10 +1122,7 @@ private static void ValidateInteropOption(EnterpriseServicesInteropOption intero // Scope timeouts are not governed by MaxTimeout and therefore need a special validate function private static void ValidateScopeTimeout(string? paramName, TimeSpan scopeTimeout) { - if (scopeTimeout < TimeSpan.Zero) - { - throw new ArgumentOutOfRangeException(paramName); - } + ArgumentOutOfRangeException.ThrowIfLessThan(scopeTimeout, TimeSpan.Zero, paramName); } private void ValidateAndSetAsyncFlowOption(TransactionScopeAsyncFlowOption asyncFlowOption) diff --git a/src/mono/System.Private.CoreLib/src/System/Array.Mono.cs b/src/mono/System.Private.CoreLib/src/System/Array.Mono.cs index 0231d4d61de2c7..152b609805fa28 100644 --- a/src/mono/System.Private.CoreLib/src/System/Array.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/Array.Mono.cs @@ -116,8 +116,7 @@ private static void Copy(Array sourceArray, int sourceIndex, Array destinationAr ArgumentNullException.ThrowIfNull(sourceArray); ArgumentNullException.ThrowIfNull(destinationArray); - if (length < 0) - throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum); + ArgumentOutOfRangeException.ThrowIfNegative(length); if (sourceArray.Rank != destinationArray.Rank) throw new RankException(SR.Rank_MultiDimNotSupported); diff --git a/src/mono/System.Private.CoreLib/src/System/GC.Mono.cs b/src/mono/System.Private.CoreLib/src/System/GC.Mono.cs index 69fb8d423194f7..ec06bebb9ae860 100644 --- a/src/mono/System.Private.CoreLib/src/System/GC.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/GC.Mono.cs @@ -55,19 +55,21 @@ public static partial class GC public static void AddMemoryPressure(long bytesAllocated) { - if (bytesAllocated <= 0) - throw new ArgumentOutOfRangeException(nameof(bytesAllocated), SR.ArgumentOutOfRange_NeedPosNum); - if (IntPtr.Size == 4 && bytesAllocated > int.MaxValue) - throw new ArgumentOutOfRangeException(nameof(bytesAllocated), SR.ArgumentOutOfRange_MustBeNonNegInt32); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(bytesAllocated); + if (IntPtr.Size == 4) + { + ArgumentOutOfRangeException.ThrowIfGreaterThan(bytesAllocated, int.MaxValue); + } RecordPressure(bytesAllocated); } public static void RemoveMemoryPressure(long bytesAllocated) { - if (bytesAllocated <= 0) - throw new ArgumentOutOfRangeException(nameof(bytesAllocated), SR.ArgumentOutOfRange_NeedPosNum); - if (IntPtr.Size == 4 && bytesAllocated > int.MaxValue) - throw new ArgumentOutOfRangeException(nameof(bytesAllocated), SR.ArgumentOutOfRange_MustBeNonNegInt32); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(bytesAllocated); + if (IntPtr.Size == 4) + { + ArgumentOutOfRangeException.ThrowIfGreaterThan(bytesAllocated, int.MaxValue); + } RecordPressure(-bytesAllocated); } @@ -90,8 +92,7 @@ public static void Collect() public static void Collect(int generation, GCCollectionMode mode, bool blocking, bool compacting) { - if (generation < 0) - throw new ArgumentOutOfRangeException(nameof(generation), "generation", SR.ArgumentOutOfRange_GenericPositive); + ArgumentOutOfRangeException.ThrowIfNegative(generation); if ((mode < GCCollectionMode.Default) || (mode > GCCollectionMode.Aggressive)) throw new ArgumentOutOfRangeException(nameof(mode), SR.ArgumentOutOfRange_Enum); @@ -100,8 +101,7 @@ public static void Collect(int generation, GCCollectionMode mode, bool blocking, public static int CollectionCount(int generation) { - if (generation < 0) - throw new ArgumentOutOfRangeException(nameof(generation), SR.ArgumentOutOfRange_GenericPositive); + ArgumentOutOfRangeException.ThrowIfNegative(generation); return GetCollectionCount(generation); } @@ -196,8 +196,7 @@ public static GCNotificationStatus WaitForFullGCApproach() public static GCNotificationStatus WaitForFullGCApproach(int millisecondsTimeout) { - if (millisecondsTimeout < -1) - throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); + ArgumentOutOfRangeException.ThrowIfLessThan(millisecondsTimeout, -1); return _WaitForFullGCApproach(millisecondsTimeout); } @@ -209,8 +208,7 @@ public static GCNotificationStatus WaitForFullGCComplete() public static GCNotificationStatus WaitForFullGCComplete(int millisecondsTimeout) { - if (millisecondsTimeout < -1) - throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); + ArgumentOutOfRangeException.ThrowIfLessThan(millisecondsTimeout, -1); return _WaitForFullGCComplete(millisecondsTimeout); } diff --git a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/DynamicILInfo.cs b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/DynamicILInfo.cs index 18ed42f645201a..ca10cc9b377c13 100644 --- a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/DynamicILInfo.cs +++ b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/DynamicILInfo.cs @@ -111,8 +111,7 @@ public void SetCode(byte[]? code, int maxStackSize) [CLSCompliantAttribute(false)] public unsafe void SetCode(byte* code, int codeSize, int maxStackSize) { - if (codeSize < 0) - throw new ArgumentOutOfRangeException(nameof(codeSize), SR.ArgumentOutOfRange_GenericPositive); + ArgumentOutOfRangeException.ThrowIfNegative(codeSize); if (codeSize > 0) ArgumentNullException.ThrowIfNull(code); diff --git a/src/mono/System.Private.CoreLib/src/System/Threading/Thread.Mono.cs b/src/mono/System.Private.CoreLib/src/System/Threading/Thread.Mono.cs index 13adc4d13f3414..37a5f9aa149f48 100644 --- a/src/mono/System.Private.CoreLib/src/System/Threading/Thread.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/Threading/Thread.Mono.cs @@ -204,8 +204,7 @@ public void Interrupt() public bool Join(int millisecondsTimeout) { - if (millisecondsTimeout < Timeout.Infinite) - throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), millisecondsTimeout, SR.ArgumentOutOfRange_NeedNonNegOrNegative1); + ArgumentOutOfRangeException.ThrowIfLessThan(millisecondsTimeout, Timeout.Infinite); return JoinInternal(this, millisecondsTimeout); } From a4a277f96dd1e00c33932de01602f6516f684b4f Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Fri, 9 Dec 2022 14:30:00 -0500 Subject: [PATCH 2/4] Fix a few issues --- .../tests/BitVector32Tests.cs | 4 ++-- .../tests/ContextStackTests.cs | 1 - .../src/System/String.Manipulation.cs | 12 +++++++----- .../src/System/Threading/Timer.cs | 2 +- .../src/System/Threading/WaitHandle.cs | 4 ++-- .../tests/System/Reflection/SignatureTypes.cs | 4 ++-- 6 files changed, 14 insertions(+), 13 deletions(-) diff --git a/src/libraries/System.Collections.Specialized/tests/BitVector32Tests.cs b/src/libraries/System.Collections.Specialized/tests/BitVector32Tests.cs index 69453b6c574d5a..14906ddd847c5e 100644 --- a/src/libraries/System.Collections.Specialized/tests/BitVector32Tests.cs +++ b/src/libraries/System.Collections.Specialized/tests/BitVector32Tests.cs @@ -429,9 +429,9 @@ public static void CreateSection_NextTest(short maximum, short mask) [InlineData(0)] public static void CreateSection_InvalidMaximumTest(short maxvalue) { - AssertExtensions.Throws("maxValue", () => BitVector32.CreateSection(maxvalue)); + AssertExtensions.Throws("maxValue", () => BitVector32.CreateSection(maxvalue)); BitVector32.Section valid = BitVector32.CreateSection(1); - AssertExtensions.Throws("maxValue", () => BitVector32.CreateSection(maxvalue, valid)); + AssertExtensions.Throws("maxValue", () => BitVector32.CreateSection(maxvalue, valid)); } [Theory] diff --git a/src/libraries/System.ComponentModel.TypeConverter/tests/ContextStackTests.cs b/src/libraries/System.ComponentModel.TypeConverter/tests/ContextStackTests.cs index 27794d55120225..2a272461142ab4 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/tests/ContextStackTests.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/tests/ContextStackTests.cs @@ -116,7 +116,6 @@ public void Indexer1_Level_Negative() ex = Assert.Throws(() => stack[-1]); Assert.Equal(typeof(ArgumentOutOfRangeException), ex.GetType()); Assert.Null(ex.InnerException); - Assert.Equal(new ArgumentOutOfRangeException("level").Message, ex.Message); Assert.Equal("level", ex.ParamName); ex = Assert.Throws(() => stack[-5]); diff --git a/src/libraries/System.Private.CoreLib/src/System/String.Manipulation.cs b/src/libraries/System.Private.CoreLib/src/System/String.Manipulation.cs index 58b7f1ca18ccd0..81cffc8b494c41 100644 --- a/src/libraries/System.Private.CoreLib/src/System/String.Manipulation.cs +++ b/src/libraries/System.Private.CoreLib/src/System/String.Manipulation.cs @@ -1846,13 +1846,15 @@ public string Substring(int startIndex, int length) private void ThrowSubstringArgumentOutOfRange(int startIndex, int length) { ArgumentOutOfRangeException.ThrowIfNegative(startIndex); - ArgumentOutOfRangeException.ThrowIfNegative(length); - (string paramName, string message) = startIndex > Length ? - (nameof(startIndex), SR.ArgumentOutOfRange_StartIndexLargerThanLength) : - (nameof(length), SR.ArgumentOutOfRange_IndexLength); + if (startIndex > Length) + { + throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndexLargerThanLength); + } + + ArgumentOutOfRangeException.ThrowIfNegative(length); - throw new ArgumentOutOfRangeException(paramName, message); + throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_IndexLength); } private string InternalSubString(int startIndex, int length) diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Timer.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Timer.cs index 9aecda2bb67914..40ecd77c61b418 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Timer.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Timer.cs @@ -841,7 +841,7 @@ public Timer(TimerCallback callback, ArgumentOutOfRangeException.ThrowIfGreaterThan(dueTm, MaxSupportedTimeout, nameof(dueTime)); long periodTm = (long)period.TotalMilliseconds; - ArgumentOutOfRangeException.ThrowIfLessThan(periodTm, -1); + ArgumentOutOfRangeException.ThrowIfLessThan(periodTm, -1, nameof(period)); ArgumentOutOfRangeException.ThrowIfGreaterThan(periodTm, MaxSupportedTimeout, nameof(period)); TimerSetup(callback, state, (uint)dueTm, (uint)periodTm); diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/WaitHandle.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/WaitHandle.cs index ef7fcfffe6d09b..85a236cdcc1960 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/WaitHandle.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/WaitHandle.cs @@ -77,8 +77,8 @@ public SafeWaitHandle SafeWaitHandle internal static int ToTimeoutMilliseconds(TimeSpan timeout) { long timeoutMilliseconds = (long)timeout.TotalMilliseconds; - ArgumentOutOfRangeException.ThrowIfLessThan(timeoutMilliseconds, -1); - ArgumentOutOfRangeException.ThrowIfGreaterThan(timeoutMilliseconds, int.MaxValue); + ArgumentOutOfRangeException.ThrowIfLessThan(timeoutMilliseconds, -1, nameof(timeout)); + ArgumentOutOfRangeException.ThrowIfGreaterThan(timeoutMilliseconds, int.MaxValue, nameof(timeout)); return (int)timeoutMilliseconds; } diff --git a/src/libraries/System.Runtime/tests/System/Reflection/SignatureTypes.cs b/src/libraries/System.Runtime/tests/System/Reflection/SignatureTypes.cs index f631cd6f1e3190..95fbae3cb3e43d 100644 --- a/src/libraries/System.Runtime/tests/System/Reflection/SignatureTypes.cs +++ b/src/libraries/System.Runtime/tests/System/Reflection/SignatureTypes.cs @@ -110,7 +110,7 @@ public static void GetMethodWithNegativeGenericParameterCount() Type t = typeof(TestClass1); const BindingFlags bf = BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly; Type[] args = { typeof(int) }; - Assert.Throws(() => t.GetMethod("Moo", -1, bf, null, args, null)); + AssertExtensions.Throws("genericParameterCount", () => t.GetMethod("Moo", -1, bf, null, args, null)); } [Theory] @@ -220,7 +220,7 @@ public static void MakeGenericMethodParameter(int position) [InlineData(int.MinValue)] public static void MakeGenericMethodParameterNegative(int position) { - Assert.Throws(() => Type.MakeGenericMethodParameter(position)); + AssertExtensions.Throws("position", () => Type.MakeGenericMethodParameter(position)); } [Fact] From 136d53b3ff9581a610c30da5e8345aec9b5509a0 Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Fri, 9 Dec 2022 17:01:21 -0500 Subject: [PATCH 3/4] Fix another test --- .../tests/ContextStackTests.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/libraries/System.ComponentModel.TypeConverter/tests/ContextStackTests.cs b/src/libraries/System.ComponentModel.TypeConverter/tests/ContextStackTests.cs index 2a272461142ab4..cec886168c4e8b 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/tests/ContextStackTests.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/tests/ContextStackTests.cs @@ -121,7 +121,6 @@ public void Indexer1_Level_Negative() ex = Assert.Throws(() => stack[-5]); Assert.Equal(typeof(ArgumentOutOfRangeException), ex.GetType()); Assert.Null(ex.InnerException); - Assert.Equal(new ArgumentOutOfRangeException("level").Message, ex.Message); Assert.Equal("level", ex.ParamName); } From 2c82adbab5f0eee6433781362aa86f967804af68 Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Sat, 10 Dec 2022 16:17:18 -0500 Subject: [PATCH 4/4] Apply suggestions from code review Co-authored-by: Miha Zupan --- .../src/System/Collections/Generic/HashSet.cs | 1 - .../src/System/Globalization/JulianCalendar.cs | 2 -- .../src/System/IO/UnmanagedMemoryAccessor.cs | 1 - 3 files changed, 4 deletions(-) diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/HashSet.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/HashSet.cs index 9a3ab8a0f922ec..fe7912af6a710e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/HashSet.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/HashSet.cs @@ -3,7 +3,6 @@ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; -using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Serialization; diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/JulianCalendar.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/JulianCalendar.cs index c468484b694a34..4edc8cbce6f400 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/JulianCalendar.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/JulianCalendar.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Reflection; - namespace System.Globalization { /// diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryAccessor.cs b/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryAccessor.cs index 87b369c1b838fe..a8a56e86cbd782 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryAccessor.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryAccessor.cs @@ -15,7 +15,6 @@ using System.Diagnostics; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; -using System.Reflection; namespace System.IO {