diff --git a/.editorconfig b/.editorconfig index bb9c61f6623de..28e3eaba64e83 100644 --- a/.editorconfig +++ b/.editorconfig @@ -155,6 +155,7 @@ csharp_space_between_square_brackets = false # Analyzers dotnet_code_quality.ca1802.api_surface = private, internal +dotnet_code_quality.CA2208.api_surface = public # C++ Files [*.{cpp,h,in}] diff --git a/eng/CodeAnalysis.ruleset b/eng/CodeAnalysis.ruleset index bc11bd3b6d58a..66a6af943a1ef 100644 --- a/eng/CodeAnalysis.ruleset +++ b/eng/CodeAnalysis.ruleset @@ -106,7 +106,7 @@ - + diff --git a/src/coreclr/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/ComActivator.cs b/src/coreclr/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/ComActivator.cs index 2b6c9b7ebad22..ffecc9b0d493b 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/ComActivator.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/ComActivator.cs @@ -124,7 +124,7 @@ public static object GetClassFactoryForType(ComActivationContext cxt) if (!Path.IsPathRooted(cxt.AssemblyPath)) { - throw new ArgumentException(); + throw new ArgumentException(null, nameof(cxt)); } Type classType = FindClassType(cxt.ClassId, cxt.AssemblyPath, cxt.AssemblyName, cxt.TypeName); @@ -156,7 +156,7 @@ public static void ClassRegistrationScenarioForType(ComActivationContext cxt, bo if (!Path.IsPathRooted(cxt.AssemblyPath)) { - throw new ArgumentException(); + throw new ArgumentException(null, nameof(cxt)); } Type classType = FindClassType(cxt.ClassId, cxt.AssemblyPath, cxt.AssemblyName, cxt.TypeName); @@ -288,7 +288,7 @@ public static unsafe int RegisterClassForTypeInternal(ComActivationContextIntern if (cxtInt.InterfaceId != Guid.Empty || cxtInt.ClassFactoryDest != IntPtr.Zero) { - throw new ArgumentException(); + throw new ArgumentException(null, nameof(pCxtInt)); } try @@ -328,7 +328,7 @@ public static unsafe int UnregisterClassForTypeInternal(ComActivationContextInte if (cxtInt.InterfaceId != Guid.Empty || cxtInt.ClassFactoryDest != IntPtr.Zero) { - throw new ArgumentException(); + throw new ArgumentException(null, nameof(pCxtInt)); } try diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/ArgIterator.cs b/src/coreclr/src/System.Private.CoreLib/src/System/ArgIterator.cs index d32d53ae753b6..8c7039e557b45 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/ArgIterator.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/ArgIterator.cs @@ -85,7 +85,9 @@ public TypedReference GetNextArg(RuntimeTypeHandle rth) // malicious caller to increment the pointer to an arbitrary // location in memory and read the contents. if (ArgPtr == IntPtr.Zero) +#pragma warning disable CA2208 // Instantiate argument exceptions correctly, the argument not applicable throw new ArgumentNullException(); +#pragma warning restore CA2208 TypedReference result = default; // reference to TypedReference is banned, so have to pass result as pointer diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/GC.cs b/src/coreclr/src/System.Private.CoreLib/src/System/GC.cs index fc8a9650f63b7..e3e1b54373fa5 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/GC.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/GC.cs @@ -135,7 +135,7 @@ public static void AddMemoryPressure(long bytesAllocated) if ((4 == IntPtr.Size) && (bytesAllocated > int.MaxValue)) { - throw new ArgumentOutOfRangeException("pressure", + throw new ArgumentOutOfRangeException(nameof(bytesAllocated), SR.ArgumentOutOfRange_MustBeNonNegInt32); } diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComWrappers.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComWrappers.cs index 8c377012666b5..6bdd48d7290a9 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComWrappers.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComWrappers.cs @@ -136,7 +136,7 @@ public IntPtr GetOrCreateComInterfaceForObject(object instance, CreateComInterfa { IntPtr ptr; if (!TryGetOrCreateComInterfaceForObjectInternal(this, instance, flags, out ptr)) - throw new ArgumentException(); + throw new ArgumentException(null, nameof(instance)); return ptr; } @@ -215,7 +215,7 @@ public object GetOrCreateObjectForComInstance(IntPtr externalComObject, CreateOb { object? obj; if (!TryGetOrCreateObjectForComInstanceInternal(this, externalComObject, flags, null, out obj)) - throw new ArgumentNullException(); + throw new ArgumentNullException(nameof(externalComObject)); return obj!; } @@ -271,7 +271,7 @@ public object GetOrRegisterObjectForComInstance(IntPtr externalComObject, Create object? obj; if (!TryGetOrCreateObjectForComInstanceInternal(this, externalComObject, flags, wrapper, out obj)) - throw new ArgumentNullException(); + throw new ArgumentNullException(nameof(externalComObject)); return obj!; } diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs b/src/coreclr/src/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs index bfbdbea7de41d..38511276255be 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs @@ -2755,7 +2755,7 @@ public override InterfaceMapping GetInterfaceMap(Type ifaceType) protected override PropertyInfo? GetPropertyImpl( string name, BindingFlags bindingAttr, Binder? binder, Type? returnType, Type[]? types, ParameterModifier[]? modifiers) { - if (name == null) throw new ArgumentNullException(); + if (name == null) throw new ArgumentNullException(nameof(name)); ListBuilder candidates = GetPropertyCandidates(name, bindingAttr, types, false); @@ -2791,7 +2791,7 @@ public override InterfaceMapping GetInterfaceMap(Type ifaceType) public override EventInfo? GetEvent(string name, BindingFlags bindingAttr) { - if (name is null) throw new ArgumentNullException(); + if (name is null) throw new ArgumentNullException(nameof(name)); FilterHelper(bindingAttr, ref name, out _, out MemberListType listType); @@ -2854,7 +2854,7 @@ public override InterfaceMapping GetInterfaceMap(Type ifaceType) public override Type? GetInterface(string fullname, bool ignoreCase) { - if (fullname is null) throw new ArgumentNullException(); + if (fullname is null) throw new ArgumentNullException(nameof(fullname)); BindingFlags bindingAttr = BindingFlags.Public | BindingFlags.NonPublic; @@ -2888,7 +2888,7 @@ public override InterfaceMapping GetInterfaceMap(Type ifaceType) public override Type? GetNestedType(string fullname, BindingFlags bindingAttr) { - if (fullname is null) throw new ArgumentNullException(); + if (fullname is null) throw new ArgumentNullException(nameof(fullname)); bindingAttr &= ~BindingFlags.Static; string name, ns; @@ -2916,7 +2916,7 @@ public override InterfaceMapping GetInterfaceMap(Type ifaceType) public override MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr) { - if (name is null) throw new ArgumentNullException(); + if (name is null) throw new ArgumentNullException(nameof(name)); ListBuilder methods = default; ListBuilder constructors = default; diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Threading/ThreadPool.CoreCLR.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Threading/ThreadPool.CoreCLR.cs index c2d72e3915cae..9752c3cbde366 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Threading/ThreadPool.CoreCLR.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Threading/ThreadPool.CoreCLR.cs @@ -260,7 +260,7 @@ private static extern long PendingUnmanagedWorkItemCount get; } - private static RegisteredWaitHandle RegisterWaitForSingleObject( // throws RegisterWaitException + private static RegisteredWaitHandle RegisterWaitForSingleObject( WaitHandle waitObject, WaitOrTimerCallback callBack, object? state, diff --git a/src/libraries/Common/src/System/Buffers/ArrayBufferWriter.cs b/src/libraries/Common/src/System/Buffers/ArrayBufferWriter.cs index 71b23e1f7cd3f..a7b047119d5d5 100644 --- a/src/libraries/Common/src/System/Buffers/ArrayBufferWriter.cs +++ b/src/libraries/Common/src/System/Buffers/ArrayBufferWriter.cs @@ -42,7 +42,7 @@ public ArrayBufferWriter() public ArrayBufferWriter(int initialCapacity) { if (initialCapacity <= 0) - throw new ArgumentException(nameof(initialCapacity)); + throw new ArgumentException(null, nameof(initialCapacity)); _buffer = new T[initialCapacity]; _index = 0; @@ -101,7 +101,7 @@ public void Clear() public void Advance(int count) { if (count < 0) - throw new ArgumentException(nameof(count)); + throw new ArgumentException(null, nameof(count)); if (_index > _buffer.Length - count) ThrowInvalidOperationException_AdvancedTooFar(_buffer.Length); diff --git a/src/libraries/Common/src/System/Threading/Tasks/TaskToApm.cs b/src/libraries/Common/src/System/Threading/Tasks/TaskToApm.cs index ecd9f27ecb8dd..96b41501f3407 100644 --- a/src/libraries/Common/src/System/Threading/Tasks/TaskToApm.cs +++ b/src/libraries/Common/src/System/Threading/Tasks/TaskToApm.cs @@ -43,7 +43,7 @@ public static void End(IAsyncResult asyncResult) return; } - throw new ArgumentNullException(); + throw new ArgumentNullException(nameof(asyncResult)); } /// Processes an IAsyncResult returned by Begin. @@ -55,7 +55,7 @@ public static TResult End(IAsyncResult asyncResult) return task.GetAwaiter().GetResult(); } - throw new ArgumentNullException(); + throw new ArgumentNullException(nameof(asyncResult)); } /// Provides a simple IAsyncResult that wraps a Task. diff --git a/src/libraries/Common/tests/TestUtilities/System/AssertExtensions.cs b/src/libraries/Common/tests/TestUtilities/System/AssertExtensions.cs index d1688c9c860b0..45f0d59333667 100644 --- a/src/libraries/Common/tests/TestUtilities/System/AssertExtensions.cs +++ b/src/libraries/Common/tests/TestUtilities/System/AssertExtensions.cs @@ -27,7 +27,7 @@ public static void ThrowsContains(Action action, string expectedMessageConten Assert.Contains(expectedMessageContent, Assert.Throws(action).Message); } - public static void Throws(string netCoreParamName, string netFxParamName, Action action) + public static T Throws(string netCoreParamName, string netFxParamName, Action action) where T : ArgumentException { T exception = Assert.Throws(action); @@ -35,7 +35,7 @@ public static void Throws(string netCoreParamName, string netFxParamName, Act if (netFxParamName == null && IsNetFramework) { // Param name varies between .NET Framework versions -- skip checking it - return; + return exception; } string expectedParamName = @@ -43,6 +43,7 @@ public static void Throws(string netCoreParamName, string netFxParamName, Act netFxParamName : netCoreParamName; Assert.Equal(expectedParamName, exception.ParamName); + return exception; } public static void Throws(string netCoreParamName, string netFxParamName, Func testCode) diff --git a/src/libraries/Microsoft.Extensions.Configuration/src/ChainedConfigurationProvider.cs b/src/libraries/Microsoft.Extensions.Configuration/src/ChainedConfigurationProvider.cs index ffc3a406b9f8f..56802e813c795 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/src/ChainedConfigurationProvider.cs +++ b/src/libraries/Microsoft.Extensions.Configuration/src/ChainedConfigurationProvider.cs @@ -29,7 +29,7 @@ public ChainedConfigurationProvider(ChainedConfigurationSource source) } if (source.Configuration == null) { - throw new ArgumentNullException(nameof(source.Configuration)); + throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "source.Configuration"), nameof(source)); } _config = source.Configuration; diff --git a/src/libraries/Microsoft.Extensions.Configuration/src/Resources/Strings.resx b/src/libraries/Microsoft.Extensions.Configuration/src/Resources/Strings.resx index 52fb2be3e50a1..1c4c38af9b51b 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/src/Resources/Strings.resx +++ b/src/libraries/Microsoft.Extensions.Configuration/src/Resources/Strings.resx @@ -120,4 +120,7 @@ A configuration source is not registered. Please register one before setting a value. + + Null is not a valid value for '{0}'. + \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/Dependency.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/Dependency.cs index e60989f77a5c8..6c26416a9359e 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/Dependency.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/Dependency.cs @@ -13,11 +13,11 @@ public Dependency(string name, string version) { if (string.IsNullOrEmpty(name)) { - throw new ArgumentException(nameof(name)); + throw new ArgumentException(null, nameof(name)); } if (string.IsNullOrEmpty(version)) { - throw new ArgumentException(nameof(version)); + throw new ArgumentException(null, nameof(version)); } Name = name; Version = version; diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/Library.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/Library.cs index cef2b76d2c9c9..eb64ac5fc95da 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/Library.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/Library.cs @@ -43,15 +43,15 @@ public Library(string type, { if (string.IsNullOrEmpty(type)) { - throw new ArgumentException(nameof(type)); + throw new ArgumentException(null, nameof(type)); } if (string.IsNullOrEmpty(name)) { - throw new ArgumentException(nameof(name)); + throw new ArgumentException(null, nameof(name)); } if (string.IsNullOrEmpty(version)) { - throw new ArgumentException(nameof(version)); + throw new ArgumentException(null, nameof(version)); } if (dependencies == null) { diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/ResourceAssembly.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/ResourceAssembly.cs index 998789b51001e..4e754367b7791 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/ResourceAssembly.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/ResourceAssembly.cs @@ -12,11 +12,11 @@ public ResourceAssembly(string path, string locale) { if (string.IsNullOrEmpty(path)) { - throw new ArgumentException(nameof(path)); + throw new ArgumentException(null, nameof(path)); } if (string.IsNullOrEmpty(locale)) { - throw new ArgumentException(nameof(locale)); + throw new ArgumentException(null, nameof(locale)); } Locale = locale; Path = path; @@ -27,4 +27,4 @@ public ResourceAssembly(string path, string locale) public string Path { get; set; } } -} \ No newline at end of file +} diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeAssembly.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeAssembly.cs index c4e07fe7deb4b..edf908e9766c6 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeAssembly.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeAssembly.cs @@ -16,11 +16,11 @@ public RuntimeAssembly(string assemblyName, string path) { if (string.IsNullOrEmpty(assemblyName)) { - throw new ArgumentException(nameof(assemblyName)); + throw new ArgumentException(null, nameof(assemblyName)); } if (string.IsNullOrEmpty(path)) { - throw new ArgumentException(nameof(path)); + throw new ArgumentException(null, nameof(path)); } _assemblyName = assemblyName; Path = path; @@ -45,4 +45,4 @@ public static RuntimeAssembly Create(string path) return new RuntimeAssembly(assemblyName, path); } } -} \ No newline at end of file +} diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeFallbacks.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeFallbacks.cs index 32b3635c92f66..9ce186d557b6c 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeFallbacks.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeFallbacks.cs @@ -18,7 +18,7 @@ public RuntimeFallbacks(string runtime, IEnumerable fallbacks) { if (string.IsNullOrEmpty(runtime)) { - throw new ArgumentException(nameof(runtime)); + throw new ArgumentException(null, nameof(runtime)); } if (fallbacks == null) { @@ -28,4 +28,4 @@ public RuntimeFallbacks(string runtime, IEnumerable fallbacks) Fallbacks = fallbacks.ToArray(); } } -} \ No newline at end of file +} diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeFile.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeFile.cs index 542a5b65a51aa..5777a34dfa2c4 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeFile.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeFile.cs @@ -12,7 +12,7 @@ public RuntimeFile(string path, string assemblyVersion, string fileVersion) { if (string.IsNullOrEmpty(path)) { - throw new ArgumentException(nameof(path)); + throw new ArgumentException(null, nameof(path)); } Path = path; diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/TargetInfo.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/TargetInfo.cs index 0b2f53607b863..485ff58d3eb23 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/TargetInfo.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/TargetInfo.cs @@ -14,7 +14,7 @@ public TargetInfo(string framework, { if (string.IsNullOrEmpty(framework)) { - throw new ArgumentException(nameof(framework)); + throw new ArgumentException(null, nameof(framework)); } Framework = framework; @@ -32,4 +32,4 @@ public TargetInfo(string framework, public bool IsPortable { get; } } -} \ No newline at end of file +} diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/Resources/Strings.resx b/src/libraries/System.ComponentModel.TypeConverter/src/Resources/Strings.resx index 84fd677ad6763..7de9810d591ed 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/Resources/Strings.resx +++ b/src/libraries/System.ComponentModel.TypeConverter/src/Resources/Strings.resx @@ -1,4 +1,5 @@ - + + @@ -76,16 +77,16 @@ The value '{0}' is not a valid value for the enum '{1}'. - Invalid event handler for the {0} event. + Invalid event handler for the {0} event. - Invalid type for the {0} event. + Invalid type for the {0} event. Invalid type for the {0} property - Accessor methods for the {0} event are missing. + Accessor methods for the {0} event are missing. Accessor methods for the {0} property are missing. @@ -170,7 +171,7 @@ The {0} culture cannot be converted to a CultureInfo object on this computer. - + The service instance must derive from or implement {0}. @@ -178,7 +179,7 @@ The service {0} already exists in the service container. - Value of '{1}' is not valid for '{0}'. + Value of '{0}' cannot be empty. Null is not a valid value for {0}. @@ -242,11 +243,11 @@ The checkout was canceled by the user. - - + + (none) - + Relationships between {0}.{1} and {2}.{3} are not supported. - + \ No newline at end of file diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerOptionService.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerOptionService.cs index ae870960bbf87..3227d9c8170df 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerOptionService.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerOptionService.cs @@ -47,7 +47,7 @@ protected DesignerOptionCollection CreateOptionCollection(DesignerOptionCollecti if (name.Length == 0) { - throw new ArgumentException(SR.Format(SR.InvalidArgumentValue, name.Length.ToString(), "0"), "name.Length"); + throw new ArgumentException(SR.Format(SR.InvalidArgumentValue, "name.Length"), nameof(name)); } return new DesignerOptionCollection(this, parent, name, value); diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/MemberRelationshipService.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/MemberRelationshipService.cs index c5bceb6e9d450..81889b0ca6327 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/MemberRelationshipService.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/MemberRelationshipService.cs @@ -44,7 +44,7 @@ public MemberRelationship this[MemberRelationship source] // and not the other as the main constructor performs argument validation. if (source.Owner == null) { - throw new ArgumentNullException(nameof(MemberRelationship.Owner)); + throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "source.Owner"), nameof(source)); } Debug.Assert(source.Member != null); @@ -57,7 +57,7 @@ public MemberRelationship this[MemberRelationship source] // and not the other as the main constructor performs argument validation. if (source.Owner == null) { - throw new ArgumentNullException(nameof(MemberRelationship.Owner)); + throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "source.Owner"), nameof(source)); } Debug.Assert(source.Member != null); diff --git a/src/libraries/System.ComponentModel.TypeConverter/tests/Design/DesignerOptionServiceTests.cs b/src/libraries/System.ComponentModel.TypeConverter/tests/Design/DesignerOptionServiceTests.cs index 37aaf19073788..78778d048a330 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/tests/Design/DesignerOptionServiceTests.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/tests/Design/DesignerOptionServiceTests.cs @@ -53,7 +53,7 @@ public void CreateOptionCollection_NullName_ThrowsArgumentNullException() public void CreateOptionCollection_EmptyName_ThrowsArgumentException() { var service = new TestDesignerOptionService(); - AssertExtensions.Throws("name.Length", () => service.DoCreateOptionCollection(service.Options, string.Empty, "value")); + AssertExtensions.Throws("name", () => service.DoCreateOptionCollection(service.Options, string.Empty, "value")); } [Fact] diff --git a/src/libraries/System.ComponentModel.TypeConverter/tests/Design/Serialization/MemberRelationshipServiceTests.cs b/src/libraries/System.ComponentModel.TypeConverter/tests/Design/Serialization/MemberRelationshipServiceTests.cs index 9f85a1eeff671..5bc0242ca9ed5 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/tests/Design/Serialization/MemberRelationshipServiceTests.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/tests/Design/Serialization/MemberRelationshipServiceTests.cs @@ -56,8 +56,8 @@ public void Indexer_NullSourceOwner_ThrowsArgumentNullException() Assert.Throws("sourceOwner", () => service[null, member]); Assert.Throws("sourceOwner", () => service[null, member] = new MemberRelationship()); - Assert.Throws("Owner", () => service[new MemberRelationship()]); - Assert.Throws("Owner", () => service[new MemberRelationship()] = new MemberRelationship()); + Assert.Throws("source", () => service[new MemberRelationship()]); + Assert.Throws("source", () => service[new MemberRelationship()] = new MemberRelationship()); } [Fact] diff --git a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceData/CounterSet.cs b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceData/CounterSet.cs index 13ac7471b6968..3a62324c07461 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceData/CounterSet.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceData/CounterSet.cs @@ -195,7 +195,7 @@ public CounterSetInstance CreateCounterSetInstance(string instanceName) { if (_provider == null) { - throw new ArgumentException(SR.Format(SR.Perflib_Argument_ProviderNotFound, _providerGuid), "ProviderGuid"); + throw new InvalidOperationException(SR.Format(SR.Perflib_InvalidOperation_NoActiveProvider, _providerGuid)); } if (_provider._hProvider.IsInvalid) { @@ -256,7 +256,7 @@ public CounterSetInstance CreateCounterSetInstance(string instanceName) { throw Status switch { - (uint)Interop.Errors.ERROR_ALREADY_EXISTS => new ArgumentException(SR.Format(SR.Perflib_Argument_CounterSetAlreadyRegister, _counterSet), "CounterSetGuid"), + (uint)Interop.Errors.ERROR_ALREADY_EXISTS => new InvalidOperationException(SR.Format(SR.Perflib_Argument_CounterSetAlreadyRegister, _counterSet)), _ => new Win32Exception((int)Status), }; diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Principal.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Principal.cs index 040de0d0c932c..8c2bcb0871291 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Principal.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Principal.cs @@ -124,7 +124,7 @@ public string SamAccountName set { if (null == value || 0 == value.Length) - throw new ArgumentNullException(PropertyNames.PrincipalSamAccountName); + throw new ArgumentNullException(nameof(value)); if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.PrincipalSamAccountName)) throw new InvalidOperationException(SR.InvalidPropertyForStore); @@ -244,7 +244,7 @@ public string Name set { if (null == value || 0 == value.Length) - throw new ArgumentNullException(PropertyNames.PrincipalName); + throw new ArgumentNullException(nameof(value)); if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.PrincipalName)) throw new InvalidOperationException(SR.InvalidPropertyForStore); diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/PrincipalSearcher.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/PrincipalSearcher.cs index 62b8e52e5239d..68d1811c0a0eb 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/PrincipalSearcher.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/PrincipalSearcher.cs @@ -23,7 +23,7 @@ public PrincipalSearcher() public PrincipalSearcher(Principal queryFilter) { if (null == queryFilter) - throw new ArgumentException(nameof(queryFilter)); + throw new ArgumentException(null, nameof(queryFilter)); _ctx = queryFilter.Context; this.QueryFilter = queryFilter; // use property to enforce "no persisted principals" check diff --git a/src/libraries/System.DirectoryServices.AccountManagement/tests/ComputerPrincipalTest.cs b/src/libraries/System.DirectoryServices.AccountManagement/tests/ComputerPrincipalTest.cs index e17eaf3f60aac..9d83710d15168 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/tests/ComputerPrincipalTest.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/tests/ComputerPrincipalTest.cs @@ -35,7 +35,7 @@ public void Ctor_NullSamAccountName_ThrowsArgumentException() public void Ctor_EmptySamAccountName_ThrowsArgumentNullException() { var context = new PrincipalContext(ContextType.Machine); - AssertExtensions.Throws("Principal.SamAccountName", null, () => new ComputerPrincipal(context, string.Empty, "password", enabled: true)); + AssertExtensions.Throws("value", null, () => new ComputerPrincipal(context, string.Empty, "password", enabled: true)); } [Fact] diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchedule.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchedule.cs index e4eee6a47e26d..2ae4757c6f3b9 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchedule.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchedule.cs @@ -59,7 +59,7 @@ public ActiveDirectorySchedule() public ActiveDirectorySchedule(ActiveDirectorySchedule schedule) : this() { if (schedule == null) - throw new ArgumentNullException(); + throw new ArgumentNullException(nameof(schedule)); bool[] tmpSchedule = schedule._scheduleArray; for (int i = 0; i < 672; i++) diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClassCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClassCollection.cs index ae07de8d521e5..c506669acc835 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClassCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClassCollection.cs @@ -111,7 +111,7 @@ public void AddRange(ActiveDirectorySchemaClass[] schemaClasses) { if (schemaClass == null) { - throw new ArgumentException(nameof(schemaClasses)); + throw new ArgumentException(null, nameof(schemaClasses)); } } @@ -132,7 +132,7 @@ public void AddRange(ActiveDirectorySchemaClassCollection schemaClasses) { if (schemaClass == null) { - throw new ArgumentException(nameof(schemaClasses)); + throw new ArgumentException(null, nameof(schemaClasses)); } } @@ -154,7 +154,7 @@ public void AddRange(ReadOnlyActiveDirectorySchemaClassCollection schemaClasses) { if (schemaClass == null) { - throw new ArgumentException(nameof(schemaClasses)); + throw new ArgumentException(null, nameof(schemaClasses)); } } @@ -360,7 +360,7 @@ protected override void OnValidate(object value) if (!(value is ActiveDirectorySchemaClass)) { - throw new ArgumentException(nameof(value)); + throw new ArgumentException(null, nameof(value)); } if (!((ActiveDirectorySchemaClass)value).isBound) diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaPropertyCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaPropertyCollection.cs index 0e312f9b392cb..5bea1fa12e76e 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaPropertyCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaPropertyCollection.cs @@ -109,7 +109,7 @@ public void AddRange(ActiveDirectorySchemaProperty[] properties) { if (property == null) { - throw new ArgumentException(nameof(properties)); + throw new ArgumentException(null, nameof(properties)); } } @@ -130,7 +130,7 @@ public void AddRange(ActiveDirectorySchemaPropertyCollection properties) { if (property == null) { - throw new ArgumentException(nameof(properties)); + throw new ArgumentException(null, nameof(properties)); } } @@ -153,7 +153,7 @@ public void AddRange(ReadOnlyActiveDirectorySchemaPropertyCollection properties) { if (property == null) { - throw new ArgumentException(nameof(properties)); + throw new ArgumentException(null, nameof(properties)); } } @@ -369,7 +369,7 @@ protected override void OnValidate(object value) if (value == null) throw new ArgumentNullException(nameof(value)); if (!(value is ActiveDirectorySchemaProperty)) - throw new ArgumentException(nameof(value)); + throw new ArgumentException(null, nameof(value)); if (!((ActiveDirectorySchemaProperty)value).isBound) throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted, ((ActiveDirectorySchemaProperty)value).Name)); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteCollection.cs index 88beabbb7b375..5e85364b26da9 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteCollection.cs @@ -232,7 +232,7 @@ protected override void OnValidate(object value) if (value == null) throw new ArgumentNullException(nameof(value)); if (!(value is ActiveDirectorySite)) - throw new ArgumentException(nameof(value)); + throw new ArgumentException(null, nameof(value)); if (!((ActiveDirectorySite)value).existing) throw new InvalidOperationException(SR.Format(SR.SiteNotCommitted, ((ActiveDirectorySite)value).Name)); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLink.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLink.cs index e35ece7285cfe..244b020f7b3f3 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLink.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLink.cs @@ -268,7 +268,7 @@ public int Cost throw new ObjectDisposedException(GetType().Name); if (value < 0) - throw new ArgumentException(nameof(value)); + throw new ArgumentException(null, nameof(value)); try { diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLinkCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLinkCollection.cs index 24d230c920a80..3f6afc747b36a 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLinkCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLinkCollection.cs @@ -226,7 +226,7 @@ protected override void OnValidate(object value) if (value == null) throw new ArgumentNullException(nameof(value)); if (!(value is ActiveDirectorySiteLink)) - throw new ArgumentException(nameof(value)); + throw new ArgumentException(null, nameof(value)); if (!((ActiveDirectorySiteLink)value).existing) throw new InvalidOperationException(SR.Format(SR.SiteLinkNotCommitted, ((ActiveDirectorySiteLink)value).Name)); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySubnetCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySubnetCollection.cs index b270eab2247fb..540be8cbfc5c0 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySubnetCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySubnetCollection.cs @@ -68,7 +68,7 @@ public void AddRange(ActiveDirectorySubnet[] subnets) { if (s == null) { - throw new ArgumentException(nameof(subnets)); + throw new ArgumentException(null, nameof(subnets)); } } @@ -263,7 +263,7 @@ protected override void OnValidate(object value) if (value == null) throw new ArgumentNullException(nameof(value)); if (!(value is ActiveDirectorySubnet)) - throw new ArgumentException(nameof(value)); + throw new ArgumentException(null, nameof(value)); if (!((ActiveDirectorySubnet)value).existing) throw new InvalidOperationException(SR.Format(SR.SubnetNotCommitted, ((ActiveDirectorySubnet)value).Name)); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServerCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServerCollection.cs index 20ee51fd55c60..64de6d61b67e8 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServerCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServerCollection.cs @@ -115,7 +115,7 @@ public void AddRange(DirectoryServer[] servers) { if (s == null) { - throw new ArgumentException(nameof(servers)); + throw new ArgumentException(null, nameof(servers)); } } @@ -386,7 +386,7 @@ protected override void OnValidate(object value) else { if (!(value is DirectoryServer)) - throw new ArgumentException(nameof(value)); + throw new ArgumentException(null, nameof(value)); } } diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/LinearGradientBrush.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/LinearGradientBrush.cs index 19228b5266f03..666eb631d7b37 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/LinearGradientBrush.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/LinearGradientBrush.cs @@ -232,14 +232,14 @@ public Blend? Blend throw new NullReferenceException(); if (value.Positions == null) - throw new ArgumentNullException("source"); + throw new ArgumentException(SR.Format(SR.InvalidArgumentValue, "value.Positions", value.Positions), nameof(value)); int count = value.Factors.Length; if (count == 0 || value.Positions.Length == 0) throw new ArgumentException(SR.BlendObjectMustHaveTwoElements); if (count >= 2 && count != value.Positions.Length) - throw new ArgumentOutOfRangeException(); + throw new ArgumentOutOfRangeException(nameof(value)); if (count >= 2 && value.Positions[0] != 0.0F) throw new ArgumentException(SR.BlendObjectFirstElementInvalid); if (count >= 2 && value.Positions[count - 1] != 1.0F) diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/PathGradientBrush.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/PathGradientBrush.cs index bae8b7a6121d2..f416ff221aa69 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/PathGradientBrush.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/PathGradientBrush.cs @@ -185,10 +185,8 @@ public Blend Blend if (value == null || value.Factors == null) throw new NullReferenceException(); - // The Desktop implementation throws ArgumentNullException("source") because it never validates the value of value.Positions, and then passes it - // on to Marshal.Copy(value.Positions, 0, positions, count);. The first argument of Marshal.Copy is source, hence this exception. if (value.Positions == null) - throw new ArgumentNullException("source"); + throw new ArgumentException(SR.Format(SR.InvalidArgumentValue, "value.Positions", value.Positions), nameof(value)); int count = value.Factors.Length; @@ -196,7 +194,7 @@ public Blend Blend if (count == 0 || value.Positions.Length == 0) throw new ArgumentException(SR.BlendObjectMustHaveTwoElements); if (count >= 2 && count != value.Positions.Length) - throw new ArgumentOutOfRangeException(); + throw new ArgumentOutOfRangeException(nameof(value)); if (count >= 2 && value.Positions[0] != 0.0F) throw new ArgumentException(SR.BlendObjectFirstElementInvalid); if (count >= 2 && value.Positions[count - 1] != 1.0F) @@ -298,16 +296,12 @@ public ColorBlend InterpolationColors } set { - // The Desktop implementation will throw various exceptions - ranging from NullReferenceExceptions to Argument(OutOfRange)Exceptions - // depending on how sane the input is. These checks exist to replicate the exact Desktop behavior. int count = value.Colors.Length; if (value.Positions == null) - throw new ArgumentNullException("source"); - if (value.Colors.Length > value.Positions.Length) - throw new ArgumentOutOfRangeException(); - if (value.Colors.Length < value.Positions.Length) - throw new ArgumentException(); + throw new ArgumentException(SR.Format(SR.InvalidArgumentValue, "value.Positions", value.Positions), nameof(value)); + if (value.Colors.Length != value.Positions.Length) + throw new ArgumentOutOfRangeException(nameof(value)); float[] positions = value.Positions; int[] argbs = new int[count]; diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Font.Windows.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Font.Windows.cs index bfa06594420bc..41ed7b89b7b40 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Font.Windows.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Font.Windows.cs @@ -306,7 +306,7 @@ public static unsafe Font FromLogFont(object lf, IntPtr hdc) { // If we don't actually have an object that is LOGFONT in size, trying to pass // it to GDI+ is likely to cause an AV. - throw new ArgumentException(); + throw new ArgumentException(null, nameof(lf)); } // Now that we know the marshalled size is the same as LOGFONT, copy in the data diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Font.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Font.cs index b030638dda613..bbabbf88ed0b8 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Font.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Font.cs @@ -285,7 +285,7 @@ public unsafe void ToLogFont(object logFont, Graphics graphics) { // If we don't actually have an object that is LOGFONT in size, trying to pass // it to GDI+ is likely to cause an AV. - throw new ArgumentException(); + throw new ArgumentException(null, nameof(logFont)); } Interop.User32.LOGFONT nativeLogFont = ToLogFontInternal(graphics); diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.Windows.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.Windows.cs index 02021231f9f29..a71a09d6e793e 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.Windows.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.Windows.cs @@ -639,9 +639,8 @@ public void Save(Stream outputStream) { try { - // We threw this way on NetFX if (outputStream == null) - throw new ArgumentNullException("dataStream"); + throw new ArgumentNullException(nameof(outputStream)); picture.SaveAsFile(new GPStream(outputStream, makeSeekable: false), -1, out int temp); } diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Text/PrivateFontCollection.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Text/PrivateFontCollection.cs index 3b150283b5dd6..60c016124d99e 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Text/PrivateFontCollection.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Text/PrivateFontCollection.cs @@ -60,16 +60,16 @@ public void AddFontFile(string filename) { if (_nativeFontCollection == IntPtr.Zero) { +#pragma warning disable CA2208 // Instantiate argument exceptions correctly // This is the default behavior on Desktop. The ArgumentException originates from GdipPrivateAddFontFile which would // refuse the null pointer. throw new ArgumentException(); +#pragma warning restore CA2208 } if (filename == null) { - // This is the default behavior on Desktop. The name "path" originates from Path.GetFullPath or similar which would refuse - // a null value. - throw new ArgumentNullException("path"); + throw new ArgumentNullException(nameof(filename)); } // this ensure the filename is valid (or throw the correct exception) diff --git a/src/libraries/System.Drawing.Common/tests/Drawing2D/LinearGradientBrushTests.cs b/src/libraries/System.Drawing.Common/tests/Drawing2D/LinearGradientBrushTests.cs index bcc33b61b72d5..2140688e8e8ba 100644 --- a/src/libraries/System.Drawing.Common/tests/Drawing2D/LinearGradientBrushTests.cs +++ b/src/libraries/System.Drawing.Common/tests/Drawing2D/LinearGradientBrushTests.cs @@ -358,11 +358,11 @@ public void Blend_SetNullBlendFactors_ThrowsNullReferenceException() } [ConditionalFact(Helpers.IsDrawingSupported)] - public void Blend_SetNullBlendPositions_ThrowsArgumentNullException() + public void Blend_SetNullBlendPositions_ThrowsArgumentException() { using (var brush = new LinearGradientBrush(new Rectangle(1, 2, 3, 4), Color.Plum, Color.Red, 45, true)) { - AssertExtensions.Throws("source", () => brush.Blend = new Blend { Factors = new float[2], Positions = null }); + AssertExtensions.Throws("value", "source", () => brush.Blend = new Blend { Factors = new float[2], Positions = null }); } } @@ -371,7 +371,7 @@ public void Blend_SetFactorsLengthGreaterThanPositionsLength_ThrowsArgumentOutOf { using (var brush = new LinearGradientBrush(new Rectangle(1, 2, 3, 4), Color.Plum, Color.Red, 45, true)) { - AssertExtensions.Throws(null, () => brush.Blend = new Blend { Factors = new float[2], Positions = new float[1] }); + AssertExtensions.Throws("value", null, () => brush.Blend = new Blend { Factors = new float[2], Positions = new float[1] }); } } diff --git a/src/libraries/System.Drawing.Common/tests/Drawing2D/PathGradientBrushTests.cs b/src/libraries/System.Drawing.Common/tests/Drawing2D/PathGradientBrushTests.cs index 3046c01641846..3019394844d4d 100644 --- a/src/libraries/System.Drawing.Common/tests/Drawing2D/PathGradientBrushTests.cs +++ b/src/libraries/System.Drawing.Common/tests/Drawing2D/PathGradientBrushTests.cs @@ -350,7 +350,7 @@ public void Blend_InvalidFactorPositionsLengthMismatch_ThrowsArgumentOutOfRangeE using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { - AssertExtensions.Throws(null, () => brush.Blend = invalidBlend); + AssertExtensions.Throws("value", null, () => brush.Blend = invalidBlend); } } @@ -366,11 +366,11 @@ public void Blend_Null_ThrowsNullReferenceException() } [ConditionalFact(Helpers.IsDrawingSupported)] - public void Blend_NullBlendProperites_ThrowsArgumentNullException() + public void Blend_NullBlendProperites_ThrowsArgumentException() { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { - AssertExtensions.Throws("source", () => + AssertExtensions.Throws("value", "source", () => brush.Blend = new Blend() { Factors = new float[0], Positions = null }); } } @@ -651,11 +651,11 @@ public void InterpolationColors_NullColors_ThrowsNullReferenceException() } [ConditionalFact(Helpers.IsDrawingSupported)] - public void InterpolationColors_NullPoints_ArgumentNullException() + public void InterpolationColors_NullPoints_ArgumentException() { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { - AssertExtensions.Throws("source", () => + AssertExtensions.Throws("value", "source", () => brush.InterpolationColors = new ColorBlend() { Colors = new Color[1], Positions = null }); } } @@ -680,11 +680,11 @@ public void InterpolationColors_EmptyColors_ArgumentException() } [ConditionalFact(Helpers.IsDrawingSupported)] - public void InterpolationColors_PointsLengthGreaterThenColorsLength_ArgumentException() + public void InterpolationColors_PointsLengthGreaterThenColorsLength_ArgumentOutOfRangeException() { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { - AssertExtensions.Throws(null, () => + AssertExtensions.Throws("value", null, () => brush.InterpolationColors = new ColorBlend() { Colors = new Color[1], Positions = new float[2] }); } } diff --git a/src/libraries/System.Drawing.Common/tests/IconTests.cs b/src/libraries/System.Drawing.Common/tests/IconTests.cs index a201c9bce16e3..440fd59f2be77 100644 --- a/src/libraries/System.Drawing.Common/tests/IconTests.cs +++ b/src/libraries/System.Drawing.Common/tests/IconTests.cs @@ -525,7 +525,7 @@ public void Save_NullOutputStreamNoIconData_ThrowsArgumentNullException() var icon = Icon.FromHandle(source.Handle); icon.Dispose(); - AssertExtensions.Throws("dataStream", () => icon.Save(null)); + AssertExtensions.Throws("outputStream", "dataStream", () => icon.Save(null)); } } diff --git a/src/libraries/System.Drawing.Common/tests/Text/PrivateFontCollectionTests.cs b/src/libraries/System.Drawing.Common/tests/Text/PrivateFontCollectionTests.cs index af934a15f458a..364ba09bdb9dd 100644 --- a/src/libraries/System.Drawing.Common/tests/Text/PrivateFontCollectionTests.cs +++ b/src/libraries/System.Drawing.Common/tests/Text/PrivateFontCollectionTests.cs @@ -107,7 +107,7 @@ public void AddFontFile_NullFileName_ThrowsArgumentNullException() { using (var fontCollection = new PrivateFontCollection()) { - AssertExtensions.Throws("path", () => fontCollection.AddFontFile(null)); + AssertExtensions.Throws("filename", "path", () => fontCollection.AddFontFile(null)); } } diff --git a/src/libraries/System.Management/src/Resources/Strings.resx b/src/libraries/System.Management/src/Resources/Strings.resx index f740f60b40f99..40f915ba6f640 100644 --- a/src/libraries/System.Management/src/Resources/Strings.resx +++ b/src/libraries/System.Management/src/Resources/Strings.resx @@ -1,4 +1,5 @@ - + + @@ -292,4 +293,7 @@ The native library '{0}' does not have all required functions. Please, update the .NET Framework. - + + The Query string supplied was invalid or improperly formed. Token `{0}` is expected + + \ No newline at end of file diff --git a/src/libraries/System.Management/src/System/Management/ManagementDateTime.cs b/src/libraries/System.Management/src/System/Management/ManagementDateTime.cs index 27114f9453b21..6a71452dc1120 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementDateTime.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementDateTime.cs @@ -415,7 +415,7 @@ public static string ToDmtfTimeInterval(TimeSpan timespan) // and also negative timespan cannot be represented in DMTF if (timespan.Days > MAXDATE_INTIMESPAN || timespan < TimeSpan.Zero) { - throw new System.ArgumentOutOfRangeException(); + throw new System.ArgumentOutOfRangeException(nameof(timespan)); } dmtftimespan = (dmtftimespan + timespan.Hours.ToString(frmInt32).PadLeft(2, '0')); diff --git a/src/libraries/System.Management/src/System/Management/ManagementQuery.cs b/src/libraries/System.Management/src/System/Management/ManagementQuery.cs index 62797f9dbd3e5..1c49c3019e4de 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementQuery.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementQuery.cs @@ -1040,13 +1040,13 @@ protected internal override void ParseQuery(string query) // Should start with "select" if ((q.Length < keyword.Length) || (0 != string.Compare(q, 0, keyword, 0, keyword.Length, StringComparison.OrdinalIgnoreCase))) - throw new ArgumentException(SR.InvalidQuery, "select"); + throw new ArgumentException(SR.Format(SR.InvalidQueryTokenExpected, keyword), nameof(query)); q = q.Remove(0, keyword.Length).TrimStart(null); // Next should be a '*' if (0 != q.IndexOf('*', 0)) - throw new ArgumentException(SR.InvalidQuery, "*"); + throw new ArgumentException(SR.Format(SR.InvalidQueryTokenExpected, "*"), nameof(query)); q = q.Remove(0, 1).TrimStart(null); @@ -1055,7 +1055,7 @@ protected internal override void ParseQuery(string query) if ((q.Length < keyword.Length) || (0 != string.Compare(q, 0, keyword, 0, keyword.Length, StringComparison.OrdinalIgnoreCase))) - throw new ArgumentException(SR.InvalidQuery, "from"); + throw new ArgumentException(SR.Format(SR.InvalidQueryTokenExpected, keyword), nameof(query)); q = q.Remove(0, keyword.Length).TrimStart(null); @@ -1064,7 +1064,7 @@ protected internal override void ParseQuery(string query) if ((q.Length < keyword.Length) || (0 != string.Compare(q, 0, keyword, 0, keyword.Length, StringComparison.OrdinalIgnoreCase))) - throw new ArgumentException(SR.InvalidQuery, "meta_class"); + throw new ArgumentException(SR.Format(SR.InvalidQueryTokenExpected, keyword), nameof(query)); q = q.Remove(0, keyword.Length).TrimStart(null); @@ -1076,7 +1076,7 @@ protected internal override void ParseQuery(string query) if ((q.Length < keyword.Length) || (0 != string.Compare(q, 0, keyword, 0, keyword.Length, StringComparison.OrdinalIgnoreCase))) - throw new ArgumentException(SR.InvalidQuery, "where"); + throw new ArgumentException(SR.Format(SR.InvalidQueryTokenExpected, keyword), nameof(query)); q = q.Remove(0, keyword.Length); @@ -1650,7 +1650,7 @@ protected internal override void ParseQuery(string query) //Find "associators" clause if (0 != string.Compare(q, 0, TokenAssociators, 0, TokenAssociators.Length, StringComparison.OrdinalIgnoreCase)) - throw new ArgumentException(SR.InvalidQuery, "associators"); // Invalid query + throw new ArgumentException(SR.Format(SR.InvalidQueryTokenExpected, TokenAssociators), nameof(query)); // Invalid query // Strip off the clause q = q.Remove(0, TokenAssociators.Length); @@ -1663,7 +1663,7 @@ protected internal override void ParseQuery(string query) // Next token should be "of" if (0 != string.Compare(q, 0, TokenOf, 0, TokenOf.Length, StringComparison.OrdinalIgnoreCase)) - throw new ArgumentException(SR.InvalidQuery, "of"); // Invalid query + throw new ArgumentException(SR.Format(SR.InvalidQueryTokenExpected, TokenOf), nameof(query)); // Invalid query // Strip off the clause and leading WS q = q.Remove(0, TokenOf.Length).TrimStart(null); @@ -1687,7 +1687,7 @@ protected internal override void ParseQuery(string query) { // Next should be the "where" clause if (0 != string.Compare(q, 0, TokenWhere, 0, TokenWhere.Length, StringComparison.OrdinalIgnoreCase)) - throw new ArgumentException(SR.InvalidQuery, "where"); // Invalid query + throw new ArgumentException(SR.Format(SR.InvalidQueryTokenExpected, TokenWhere), nameof(query)); // Invalid query q = q.Remove(0, TokenWhere.Length); @@ -2167,7 +2167,7 @@ protected internal override void ParseQuery(string query) //Find "references" clause if (0 != string.Compare(q, 0, TokenReferences, 0, TokenReferences.Length, StringComparison.OrdinalIgnoreCase)) - throw new ArgumentException(SR.InvalidQuery, "references"); // Invalid query + throw new ArgumentException(SR.Format(SR.InvalidQueryTokenExpected, TokenReferences), nameof(query)); // Invalid query // Strip off the clause q = q.Remove(0, TokenReferences.Length); @@ -2180,7 +2180,7 @@ protected internal override void ParseQuery(string query) // Next token should be "of" if (0 != string.Compare(q, 0, TokenOf, 0, TokenOf.Length, StringComparison.OrdinalIgnoreCase)) - throw new ArgumentException(SR.InvalidQuery, "of"); // Invalid query + throw new ArgumentException(SR.Format(SR.InvalidQueryTokenExpected, TokenOf), nameof(query)); // Invalid query // Strip off the clause and leading WS q = q.Remove(0, TokenOf.Length).TrimStart(null); @@ -2204,7 +2204,7 @@ protected internal override void ParseQuery(string query) { // Next should be the "where" clause if (0 != string.Compare(q, 0, TokenWhere, 0, TokenWhere.Length, StringComparison.OrdinalIgnoreCase)) - throw new ArgumentException(SR.InvalidQuery, "where"); // Invalid query + throw new ArgumentException(SR.Format(SR.InvalidQueryTokenExpected, TokenWhere), nameof(query)); // Invalid query q = q.Remove(0, TokenWhere.Length); @@ -3043,13 +3043,13 @@ protected internal override void ParseQuery(string query) q = q.Remove(0, keyword.Length).TrimStart(null); if (!q.StartsWith("*", StringComparison.Ordinal)) - throw new ArgumentException(SR.InvalidQuery, "*"); + throw new ArgumentException(SR.Format(SR.InvalidQueryTokenExpected, "*"), nameof(query)); q = q.Remove(0, 1).TrimStart(null); //Find "from" clause keyword = "from "; if ((q.Length < keyword.Length) || (0 != string.Compare(q, 0, keyword, 0, keyword.Length, StringComparison.OrdinalIgnoreCase))) - throw new ArgumentException(SR.InvalidQuery, "from"); + throw new ArgumentException(SR.Format(SR.InvalidQueryTokenExpected, keyword), nameof(query)); ParseToken(ref q, keyword, null, ref bFound, ref eventClassName); //Find "within" clause @@ -3119,7 +3119,7 @@ protected internal override void ParseQuery(string query) q = q.Remove(0, keyword.Length); if (q.Length == 0) //bad query - throw new ArgumentException(SR.InvalidQuery, "having"); + throw new ArgumentException(SR.Format(SR.InvalidQueryTokenExpected, keyword), nameof(query)); havingCondition = q; } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerResponse.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerResponse.cs index 41e3f78d340c8..97c8339c3b95f 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerResponse.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerResponse.cs @@ -188,7 +188,7 @@ public string StatusDescription char c = (char)(0x000000ff & (uint)value[i]); if ((c <= 31 && c != (byte)'\t') || c == 127) { - throw new ArgumentException(SR.net_WebHeaderInvalidControlChars, "name"); + throw new ArgumentException(SR.net_WebHeaderInvalidControlChars, nameof(value)); } } diff --git a/src/libraries/System.Net.HttpListener/tests/HttpListenerResponseTests.Headers.cs b/src/libraries/System.Net.HttpListener/tests/HttpListenerResponseTests.Headers.cs index 112c841b8594a..f52b79f355844 100644 --- a/src/libraries/System.Net.HttpListener/tests/HttpListenerResponseTests.Headers.cs +++ b/src/libraries/System.Net.HttpListener/tests/HttpListenerResponseTests.Headers.cs @@ -436,7 +436,7 @@ public async Task StatusDescription_SetInvalid_ThrowsArgumentException(string st { using (HttpListenerResponse response = await GetResponse()) { - AssertExtensions.Throws("name", () => response.StatusDescription = statusDescription); + AssertExtensions.Throws("value", () => response.StatusDescription = statusDescription); Assert.Equal("OK", response.StatusDescription); } } diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/SystemIPGlobalProperties.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/SystemIPGlobalProperties.cs index 315915b5ed0c3..39220cab5c204 100644 --- a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/SystemIPGlobalProperties.cs +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/SystemIPGlobalProperties.cs @@ -380,7 +380,7 @@ public override UnicastIPAddressInformationCollection GetUnicastAddresses() => public override async Task GetUnicastAddressesAsync() { // Wait for the address table to stabilize. - var tcs = new TaskCompletionSource(TaskContinuationOptions.RunContinuationsAsynchronously); + var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); if (!TeredoHelper.UnsafeNotifyStableUnicastIpAddressTable(s => ((TaskCompletionSource)s).TrySetResult(true), tcs)) { await tcs.Task.ConfigureAwait(false); 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 75f68bb98086e..af1f75ebc9d49 100644 --- a/src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs +++ b/src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs @@ -118,7 +118,7 @@ public CookieContainer(int capacity) { if (capacity <= 0) { - throw new ArgumentException(SR.net_toosmall, "Capacity"); + throw new ArgumentException(SR.net_toosmall, nameof(capacity)); } m_maxCookies = capacity; } @@ -132,7 +132,7 @@ public CookieContainer(int capacity, int perDomainCapacity, int maxCookieSize) : m_maxCookiesPerDomain = perDomainCapacity; if (maxCookieSize <= 0) { - throw new ArgumentException(SR.net_toosmall, "MaxCookieSize"); + throw new ArgumentException(SR.net_toosmall, nameof(maxCookieSize)); } m_maxCookieSize = maxCookieSize; } @@ -230,7 +230,7 @@ public void Add(Cookie cookie) { throw new ArgumentException( SR.Format(SR.net_emptystringcall, nameof(cookie) + "." + nameof(cookie.Domain)), - nameof(cookie) + "." + nameof(cookie.Domain)); + nameof(cookie)); } Uri? uri; diff --git a/src/libraries/System.Net.Primitives/tests/UnitTests/CookieContainerTest.cs b/src/libraries/System.Net.Primitives/tests/UnitTests/CookieContainerTest.cs index d3ce1f523d0ec..7bd84309abf0c 100644 --- a/src/libraries/System.Net.Primitives/tests/UnitTests/CookieContainerTest.cs +++ b/src/libraries/System.Net.Primitives/tests/UnitTests/CookieContainerTest.cs @@ -486,7 +486,7 @@ public void Ctor_Capacity_Success() [Fact] public void Ctor_Capacity_Invalid() { - AssertExtensions.Throws("Capacity", () => new CookieContainer(0)); // Capacity <= 0 + AssertExtensions.Throws("capacity", () => new CookieContainer(0)); // Capacity <= 0 } [Fact] @@ -595,7 +595,7 @@ public void Add_Cookie_Invalid() { CookieContainer cc = new CookieContainer(); Assert.Throws(() => cc.Add((Cookie)null)); // Null cookie - AssertExtensions.Throws("cookie.Domain", () => cc.Add(new Cookie("name", "value", "", ""))); // Empty domain + AssertExtensions.Throws("cookie", () => cc.Add(new Cookie("name", "value", "", ""))); // Empty domain cc.MaxCookieSize = 1; Assert.Throws(() => cc.Add(new Cookie("name", "long-text", "", "contoso.com"))); // Value.Length > MaxCookieSize @@ -625,11 +625,11 @@ public void Capacity_ShrinkNoneExpired_RemovesAll() [Fact] public void Ctor_CapacityPerDomainCapacityMaxCookieSize_Invalid() { - AssertExtensions.Throws("Capacity", () => new CookieContainer(0, 10, 5)); // Capacity <= 0 + AssertExtensions.Throws("capacity", () => new CookieContainer(0, 10, 5)); // Capacity <= 0 Assert.Throws(() => new CookieContainer(5, 0, 5)); // Per domain capacity <= 0 Assert.Throws(() => new CookieContainer(5, 10, 5)); // Per domain capacity > Capacity - AssertExtensions.Throws("MaxCookieSize", () => new CookieContainer(15, 10, 0)); // Max cookie size <= 0 + AssertExtensions.Throws("maxCookieSize", () => new CookieContainer(15, 10, 0)); // Max cookie size <= 0 } [Fact] diff --git a/src/libraries/System.Net.Sockets/src/Resources/Strings.resx b/src/libraries/System.Net.Sockets/src/Resources/Strings.resx index 3078fabf5d5fd..62f9bb2b41db9 100644 --- a/src/libraries/System.Net.Sockets/src/Resources/Strings.resx +++ b/src/libraries/System.Net.Sockets/src/Resources/Strings.resx @@ -1,4 +1,5 @@ - + + @@ -192,8 +193,8 @@ The specified value cannot be negative. - - Argument must be between {0} and {1}. + + Argument '{2}' must be between {0} and {1}. Sockets on this platform are invalid for use after a failed connection attempt. @@ -258,4 +259,7 @@ Asynchronous operations are not allowed on this socket. The underlying OS handle might have been already bound to an IO completion port. - + + Null is not a valid value for {0}. + + \ No newline at end of file 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 2e3f3d50ada63..e5eda8e009823 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 @@ -1908,7 +1908,7 @@ public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName opti } if (lingerOption.LingerTime < 0 || lingerOption.LingerTime > (int)ushort.MaxValue) { - throw new ArgumentException(SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, 0, (int)ushort.MaxValue), "optionValue.LingerTime"); + throw new ArgumentException(SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper_Named, 0, (int)ushort.MaxValue, "optionValue.LingerTime"), nameof(optionValue)); } SetLingerOption(lingerOption); } @@ -3816,7 +3816,7 @@ public bool AcceptAsync(SocketAsyncEventArgs e) } if (e.HasMultipleBuffers) { - throw new ArgumentException(SR.net_multibuffernotsupported, "BufferList"); + throw new ArgumentException(SR.net_multibuffernotsupported, nameof(e)); } if (_rightEndPoint == null) { @@ -3979,11 +3979,11 @@ public static bool ConnectAsync(SocketType socketType, ProtocolType protocolType } if (e.HasMultipleBuffers) { - throw new ArgumentException(SR.net_multibuffernotsupported, "BufferList"); + throw new ArgumentException(SR.net_multibuffernotsupported, nameof(e)); } if (e.RemoteEndPoint == null) { - throw new ArgumentNullException("remoteEP"); + throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "e.RemoteEndPoint"), nameof(e)); } EndPoint endPointSnapshot = e.RemoteEndPoint; @@ -4116,11 +4116,11 @@ public bool ReceiveFromAsync(SocketAsyncEventArgs e) } if (e.RemoteEndPoint == null) { - throw new ArgumentNullException(nameof(e.RemoteEndPoint)); + throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "e.RemoteEndPoint"), nameof(e)); } if (!CanTryAddressFamily(e.RemoteEndPoint.AddressFamily)) { - throw new ArgumentException(SR.Format(SR.net_InvalidEndPointAddressFamily, e.RemoteEndPoint.AddressFamily, _addressFamily), "RemoteEndPoint"); + throw new ArgumentException(SR.Format(SR.net_InvalidEndPointAddressFamily, e.RemoteEndPoint.AddressFamily, _addressFamily), nameof(e)); } SocketPal.CheckDualModeReceiveSupport(this); @@ -4166,11 +4166,11 @@ public bool ReceiveMessageFromAsync(SocketAsyncEventArgs e) } if (e.RemoteEndPoint == null) { - throw new ArgumentNullException(nameof(e.RemoteEndPoint)); + throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "e.RemoteEndPoint"), nameof(e)); } if (!CanTryAddressFamily(e.RemoteEndPoint.AddressFamily)) { - throw new ArgumentException(SR.Format(SR.net_InvalidEndPointAddressFamily, e.RemoteEndPoint.AddressFamily, _addressFamily), "RemoteEndPoint"); + throw new ArgumentException(SR.Format(SR.net_InvalidEndPointAddressFamily, e.RemoteEndPoint.AddressFamily, _addressFamily), nameof(e)); } SocketPal.CheckDualModeReceiveSupport(this); @@ -4250,7 +4250,7 @@ public bool SendPacketsAsync(SocketAsyncEventArgs e) } if (e.SendPacketsElements == null) { - throw new ArgumentNullException("e.SendPacketsElements"); + throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "e.SendPacketsElements"), nameof(e)); } if (!Connected) { @@ -4288,7 +4288,7 @@ public bool SendToAsync(SocketAsyncEventArgs e) } if (e.RemoteEndPoint == null) { - throw new ArgumentNullException(nameof(RemoteEndPoint)); + throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "e.RemoteEndPoint"), nameof(e)); } // Prepare SocketAddress diff --git a/src/libraries/System.Net.Sockets/tests/FunctionalTests/ArgumentValidationTests.cs b/src/libraries/System.Net.Sockets/tests/FunctionalTests/ArgumentValidationTests.cs index 655534f857ca0..8c3af3465b9df 100644 --- a/src/libraries/System.Net.Sockets/tests/FunctionalTests/ArgumentValidationTests.cs +++ b/src/libraries/System.Net.Sockets/tests/FunctionalTests/ArgumentValidationTests.cs @@ -454,8 +454,8 @@ public void SetSocketOption_Linger_NotLingerOption_Throws_Argument() [Fact] public void SetSocketOption_Linger_InvalidLingerTime_Throws_Argument() { - AssertExtensions.Throws("optionValue.LingerTime", () => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, -1))); - AssertExtensions.Throws("optionValue.LingerTime", () => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, (int)ushort.MaxValue + 1))); + AssertExtensions.Throws("optionValue", () => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, -1))); + AssertExtensions.Throws("optionValue", () => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, (int)ushort.MaxValue + 1))); } [Fact] @@ -516,7 +516,7 @@ public void AcceptAsync_BufferList_Throws_Argument() BufferList = s_buffers }; - AssertExtensions.Throws("BufferList", () => GetSocket().AcceptAsync(eventArgs)); + AssertExtensions.Throws("e", () => GetSocket().AcceptAsync(eventArgs)); } [Fact] @@ -598,13 +598,13 @@ public void ConnectAsync_Static_BufferList_Throws_Argument() BufferList = s_buffers }; - AssertExtensions.Throws("BufferList", () => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, eventArgs)); + AssertExtensions.Throws("e", () => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, eventArgs)); } [Fact] - public void ConnectAsync_Static_NullRemoteEndPoint_Throws_ArgumentNull() + public void ConnectAsync_Static_NullRemoteEndPoint_Throws_ArgumentException() { - Assert.Throws(() => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, s_eventArgs)); + Assert.Throws("e", () => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, s_eventArgs)); } [Fact] @@ -620,9 +620,9 @@ public void ReceiveFromAsync_NullAsyncEventArgs_Throws_ArgumentNull() } [Fact] - public void ReceiveFromAsync_NullRemoteEndPoint_Throws_ArgumentNull() + public void ReceiveFromAsync_NullRemoteEndPoint_Throws_ArgumentException() { - Assert.Throws(() => GetSocket().ReceiveFromAsync(s_eventArgs)); + Assert.Throws("e", () => GetSocket().ReceiveFromAsync(s_eventArgs)); } [Fact] @@ -632,7 +632,7 @@ public void ReceiveFromAsync_AddressFamily_Throws_Argument() RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, 1) }; - AssertExtensions.Throws("RemoteEndPoint", () => GetSocket(AddressFamily.InterNetwork).ReceiveFromAsync(eventArgs)); + AssertExtensions.Throws("e", () => GetSocket(AddressFamily.InterNetwork).ReceiveFromAsync(eventArgs)); } [Fact] @@ -642,9 +642,9 @@ public void ReceiveMessageFromAsync_NullAsyncEventArgs_Throws_ArgumentNull() } [Fact] - public void ReceiveMessageFromAsync_NullRemoteEndPoint_Throws_ArgumentNull() + public void ReceiveMessageFromAsync_NullRemoteEndPoint_Throws_ArgumentException() { - Assert.Throws(() => GetSocket().ReceiveMessageFromAsync(s_eventArgs)); + Assert.Throws("e", () => GetSocket().ReceiveMessageFromAsync(s_eventArgs)); } [Fact] @@ -654,7 +654,7 @@ public void ReceiveMessageFromAsync_AddressFamily_Throws_Argument() RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, 1) }; - AssertExtensions.Throws("RemoteEndPoint", () => GetSocket(AddressFamily.InterNetwork).ReceiveMessageFromAsync(eventArgs)); + AssertExtensions.Throws("e", () => GetSocket(AddressFamily.InterNetwork).ReceiveMessageFromAsync(eventArgs)); } [Fact] @@ -670,9 +670,9 @@ public void SendPacketsAsync_NullAsyncEventArgs_Throws_ArgumentNull() } [Fact] - public void SendPacketsAsync_NullSendPacketsElements_Throws_ArgumentNull() + public void SendPacketsAsync_NullSendPacketsElements_Throws_ArgumentException() { - Assert.Throws(() => GetSocket().SendPacketsAsync(s_eventArgs)); + Assert.Throws("e", () => GetSocket().SendPacketsAsync(s_eventArgs)); } [Fact] @@ -694,7 +694,7 @@ public void SendToAsync_NullAsyncEventArgs_Throws_ArgumentNull() [Fact] public void SendToAsync_NullRemoteEndPoint_Throws_ArgumentNull() { - Assert.Throws(() => GetSocket().SendToAsync(s_eventArgs)); + Assert.Throws(() => GetSocket().SendToAsync(s_eventArgs)); } [Theory] diff --git a/src/libraries/System.Net.Sockets/tests/FunctionalTests/SendTo.cs b/src/libraries/System.Net.Sockets/tests/FunctionalTests/SendTo.cs index c767e30b8f143..d10c877558277 100644 --- a/src/libraries/System.Net.Sockets/tests/FunctionalTests/SendTo.cs +++ b/src/libraries/System.Net.Sockets/tests/FunctionalTests/SendTo.cs @@ -47,7 +47,7 @@ public async Task NullEndpoint_Throws() { using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); - await Assert.ThrowsAsync(() => SendToAsync(socket, new byte[1], null)); + await Assert.ThrowsAnyAsync(() => SendToAsync(socket, new byte[1], null)); } [Fact] diff --git a/src/libraries/System.Net.WebHeaderCollection/src/System/Net/WebHeaderCollection.cs b/src/libraries/System.Net.WebHeaderCollection/src/System/Net/WebHeaderCollection.cs index ae3a1a4e5ffcf..2214534a9d5ab 100644 --- a/src/libraries/System.Net.WebHeaderCollection/src/System/Net/WebHeaderCollection.cs +++ b/src/libraries/System.Net.WebHeaderCollection/src/System/Net/WebHeaderCollection.cs @@ -378,7 +378,7 @@ public void Add(string header) { if (value != null && value.Length > ushort.MaxValue) { - throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(CultureInfo.InvariantCulture, SR.net_headers_toolong, ushort.MaxValue)); + throw new ArgumentOutOfRangeException(nameof(header), value, SR.Format(CultureInfo.InvariantCulture, SR.net_headers_toolong, ushort.MaxValue)); } } InvalidateCachedArrays(); diff --git a/src/libraries/System.Private.CoreLib/src/System/DateTime.cs b/src/libraries/System.Private.CoreLib/src/System/DateTime.cs index 023d795019d41..1561e99a72434 100644 --- a/src/libraries/System.Private.CoreLib/src/System/DateTime.cs +++ b/src/libraries/System.Private.CoreLib/src/System/DateTime.cs @@ -581,9 +581,7 @@ public DateTime AddYears(int value) { if (value < -10000 || value > 10000) { - // DateTimeOffset.AddYears(int years) is implemented on top of DateTime.AddYears(int value). Use the more appropriate - // parameter name out of the two for the exception. - throw new ArgumentOutOfRangeException("years", SR.ArgumentOutOfRange_DateTimeBadYears); + throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_DateTimeBadYears); } return AddMonths(value * 12); } 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 0075e697cd63f..71011882bd9e3 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureInfo.cs @@ -1103,7 +1103,9 @@ public static CultureInfo GetCultureInfo(string name, string altName) } catch (ArgumentException) { +#pragma warning disable CA2208 // Instantiate argument exceptions correctly, combination of arguments used throw new CultureNotFoundException("name/altName", SR.Format(SR.Argument_OneOfCulturesNotSupported, name, altName)); +#pragma warning restore CA2208 } lock (nameTable) 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 80fd193b5824b..b4393da162f44 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/BinaryWriter.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/BinaryWriter.cs @@ -394,7 +394,7 @@ public virtual unsafe void Write(string value) { if (charStart < 0 || charCount < 0 || charStart > value.Length - charCount) { - throw new ArgumentOutOfRangeException(nameof(charCount)); + throw new ArgumentOutOfRangeException(nameof(value)); } fixed (char* pChars = value) { diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryStream.cs b/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryStream.cs index 6c17ca92ac85a..20fc078c95467 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryStream.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryStream.cs @@ -408,7 +408,7 @@ public unsafe byte* PositionPointer throw new IOException(SR.IO_SeekBeforeBegin); long newPosition = (long)value - (long)_mem; if (newPosition < 0) - throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_UnmanagedMemStreamLength); + throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_UnmanagedMemStreamLength); Interlocked.Exchange(ref _position, newPosition); } 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 1b18fd5eca51f..bdff2d05df01e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs @@ -1144,7 +1144,9 @@ public StringBuilder Remove(int startIndex, int length) return this; } +#pragma warning disable CA1830 // Prefer strongly-typed Append and Insert method overloads on StringBuilder. No need to fix for the builder itself public StringBuilder Append(bool value) => Append(value.ToString()); +#pragma warning restore CA1830 public StringBuilder Append(char value) { 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 8bdf89070a9ad..9abd9ac2aa98a 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Thread.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Thread.cs @@ -243,7 +243,7 @@ public bool TrySetApartmentState(ApartmentState state) break; default: - throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_Enum, nameof(state)); + throw new ArgumentOutOfRangeException(nameof(state), SR.ArgumentOutOfRange_Enum); } return TrySetApartmentStateUnchecked(state); diff --git a/src/libraries/System.Private.CoreLib/src/System/Type.Enum.cs b/src/libraries/System.Private.CoreLib/src/System/Type.Enum.cs index 59f244f6c3477..d041c32b7b534 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Type.Enum.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Type.Enum.cs @@ -23,7 +23,7 @@ public virtual bool IsEnumDefined(object value) throw new ArgumentNullException(nameof(value)); if (!IsEnum) - throw new ArgumentException(SR.Arg_MustBeEnum, "enumType"); + throw new ArgumentException(SR.Arg_MustBeEnum, nameof(value)); // Check if both of them are of the same type Type valueType = value.GetType(); @@ -70,7 +70,7 @@ public virtual bool IsEnumDefined(object value) throw new ArgumentNullException(nameof(value)); if (!IsEnum) - throw new ArgumentException(SR.Arg_MustBeEnum, "enumType"); + throw new ArgumentException(SR.Arg_MustBeEnum, nameof(value)); Type valueType = value.GetType(); diff --git a/src/libraries/System.Private.CoreLib/src/System/Type.cs b/src/libraries/System.Private.CoreLib/src/System/Type.cs index aeb60457d9741..76aa11bc20491 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Type.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Type.cs @@ -267,7 +267,7 @@ public static Type[] GetTypeArray(object[] args) for (int i = 0; i < cls.Length; i++) { if (args[i] == null) - throw new ArgumentNullException(); + throw new ArgumentException(SR.ArgumentNull_ArrayValue, nameof(args)); cls[i] = args[i].GetType(); } return cls; diff --git a/src/libraries/System.Private.Uri/src/Resources/Strings.resx b/src/libraries/System.Private.Uri/src/Resources/Strings.resx index 16e3b576da63a..92a87cd44ccaa 100644 --- a/src/libraries/System.Private.Uri/src/Resources/Strings.resx +++ b/src/libraries/System.Private.Uri/src/Resources/Strings.resx @@ -192,6 +192,9 @@ The given key '{0}' was not present in the dictionary. + + Null is not a valid value for {0}. + UriParser's base InitializeAndValidate may only be called once on a single Uri instance and only from an override of InitializeAndValidate. diff --git a/src/libraries/System.Private.Uri/src/System/Uri.cs b/src/libraries/System.Private.Uri/src/System/Uri.cs index a13566ee3415b..2ed3c4ec70146 100644 --- a/src/libraries/System.Private.Uri/src/System/Uri.cs +++ b/src/libraries/System.Private.Uri/src/System/Uri.cs @@ -436,7 +436,7 @@ protected Uri(SerializationInfo serializationInfo, StreamingContext streamingCon uriString = serializationInfo.GetString("RelativeUri"); // Do not rename (binary serialization) if ((object?)uriString == null) - throw new ArgumentNullException(nameof(uriString)); + throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "RelativeUri"), nameof(serializationInfo)); CreateThis(uriString, false, UriKind.Relative); DebugSetLeftCtor(); @@ -1504,7 +1504,7 @@ public static int FromHex(char digit) => (uint)(digit - '0') <= '9' - '0' ? digit - '0' : (uint)(digit - 'A') <= 'F' - 'A' ? digit - 'A' + 10 : (uint)(digit - 'a') <= 'f' - 'a' ? digit - 'a' + 10 : - throw new ArgumentException(nameof(digit)); + throw new ArgumentException(null, nameof(digit)); public override int GetHashCode() { diff --git a/src/libraries/System.Private.Uri/tests/ExtendedFunctionalTests/UriTests.cs b/src/libraries/System.Private.Uri/tests/ExtendedFunctionalTests/UriTests.cs index 3aeb6238fbf48..2561e785c6e66 100644 --- a/src/libraries/System.Private.Uri/tests/ExtendedFunctionalTests/UriTests.cs +++ b/src/libraries/System.Private.Uri/tests/ExtendedFunctionalTests/UriTests.cs @@ -180,7 +180,7 @@ public static void TestHexMethods() [Fact] public static void TestHexMethods_Invalid() { - AssertExtensions.Throws(null, () => Uri.FromHex('?')); + AssertExtensions.Throws("digit", () => Uri.FromHex('?')); Assert.Throws(() => Uri.HexEscape('\x100')); int index = -1; Assert.Throws(() => Uri.HexUnescape("%75", ref index)); 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 5bb3c734340a7..0ee36591cc7d7 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/NameTable.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/NameTable.cs @@ -103,7 +103,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(); + throw new ArgumentOutOfRangeException(nameof(len)); } int hashCode = ComputeHash32(key, start, len); diff --git a/src/libraries/System.Reflection.Extensions/tests/RuntimeReflectionExtensionTests.cs b/src/libraries/System.Reflection.Extensions/tests/RuntimeReflectionExtensionTests.cs index f3ca59bbca687..5464877b54c54 100644 --- a/src/libraries/System.Reflection.Extensions/tests/RuntimeReflectionExtensionTests.cs +++ b/src/libraries/System.Reflection.Extensions/tests/RuntimeReflectionExtensionTests.cs @@ -165,7 +165,7 @@ public void GetRuntimeEvent() }); - Assert.Throws(null, () => + Assert.Throws("name", () => { typeof(RuntimeReflectionExtensionsTests).GetRuntimeEvent(null); }); diff --git a/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/ComAwareEventInfoTests.cs b/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/ComAwareEventInfoTests.cs index f3513d414c075..243133c3b3cb0 100644 --- a/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/ComAwareEventInfoTests.cs +++ b/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/ComAwareEventInfoTests.cs @@ -39,7 +39,7 @@ public void Ctor_NullType_ThrowsNullReferenceException() [Fact] public void Ctor_NullEventName_ThrowsArgumentNullException() { - AssertExtensions.Throws(null, () => new ComAwareEventInfo(typeof(NonComObject), null)); + AssertExtensions.Throws("name", () => new ComAwareEventInfo(typeof(NonComObject), null)); } [Fact] diff --git a/src/libraries/System.Runtime/tests/System/DateTimeOffsetTests.cs b/src/libraries/System.Runtime/tests/System/DateTimeOffsetTests.cs index d62cb75547c15..0d146b4cd2c6f 100644 --- a/src/libraries/System.Runtime/tests/System/DateTimeOffsetTests.cs +++ b/src/libraries/System.Runtime/tests/System/DateTimeOffsetTests.cs @@ -357,8 +357,8 @@ public static void AddYears(DateTimeOffset dateTimeOffset, int years, DateTimeOf [Fact] public static void AddYears_NewDateOutOfRange_ThrowsArgumentOutOfRangeException() { - AssertExtensions.Throws("years", () => DateTimeOffset.Now.AddYears(10001)); - AssertExtensions.Throws("years", () => DateTimeOffset.Now.AddYears(-10001)); + AssertExtensions.Throws("value", () => DateTimeOffset.Now.AddYears(10001)); + AssertExtensions.Throws("value", () => DateTimeOffset.Now.AddYears(-10001)); AssertExtensions.Throws("months", () => DateTimeOffset.MaxValue.AddYears(1)); AssertExtensions.Throws("months", () => DateTimeOffset.MinValue.AddYears(-1)); diff --git a/src/libraries/System.Runtime/tests/System/DateTimeTests.cs b/src/libraries/System.Runtime/tests/System/DateTimeTests.cs index 654a103cc9af0..c1d68a264deec 100644 --- a/src/libraries/System.Runtime/tests/System/DateTimeTests.cs +++ b/src/libraries/System.Runtime/tests/System/DateTimeTests.cs @@ -383,8 +383,8 @@ public void AddYears_Invoke_ReturnsExpected(DateTime dateTime, int years, DateTi public static IEnumerable AddYears_OutOfRange_TestData() { - yield return new object[] { DateTime.Now, 10001, "years" }; - yield return new object[] { DateTime.Now, -10001, "years" }; + yield return new object[] { DateTime.Now, 10001, "value" }; + yield return new object[] { DateTime.Now, -10001, "value" }; yield return new object[] { DateTime.MaxValue, 1, "months" }; yield return new object[] { DateTime.MinValue, -1, "months" }; } diff --git a/src/libraries/System.Runtime/tests/System/GCTests.cs b/src/libraries/System.Runtime/tests/System/GCTests.cs index 097f2dcac805b..4c8c309167735 100644 --- a/src/libraries/System.Runtime/tests/System/GCTests.cs +++ b/src/libraries/System.Runtime/tests/System/GCTests.cs @@ -25,7 +25,7 @@ public static void AddMemoryPressure_InvalidBytesAllocated_ThrowsArgumentOutOfRa if (s_is32Bits) { - AssertExtensions.Throws("pressure", () => GC.AddMemoryPressure((long)int.MaxValue + 1)); // Bytes allocated > int.MaxValue on 32 bit platforms + AssertExtensions.Throws("bytesAllocated", () => GC.AddMemoryPressure((long)int.MaxValue + 1)); // Bytes allocated > int.MaxValue on 32 bit platforms } } diff --git a/src/libraries/System.Runtime/tests/System/Type/TypeTests.Get.cs b/src/libraries/System.Runtime/tests/System/Type/TypeTests.Get.cs index 5f19479bc6211..9e3e3d2c2372d 100644 --- a/src/libraries/System.Runtime/tests/System/Type/TypeTests.Get.cs +++ b/src/libraries/System.Runtime/tests/System/Type/TypeTests.Get.cs @@ -71,7 +71,7 @@ public void GetInterface_Invoke_ReturnsExpected(Type type, string name, bool ign [Fact] public void GetInterface_NullName_ThrowsArgumentNullException() { - AssertExtensions.Throws(null, () => typeof(int).GetInterface(null)); + AssertExtensions.Throws("fullname", () => typeof(int).GetInterface(null)); } [Fact] diff --git a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/CommonObjectSecurity.cs b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/CommonObjectSecurity.cs index 1ff7c7c416486..a1665aa92070c 100644 --- a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/CommonObjectSecurity.cs +++ b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/CommonObjectSecurity.cs @@ -336,7 +336,7 @@ protected override bool ModifyAccess(AccessControlModification modification, Acc else { Debug.Fail("rule.AccessControlType unrecognized"); - throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)rule.AccessControlType), "rule.AccessControlType"); + throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)rule.AccessControlType), nameof(rule)); } modified = result; diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/DSA.Xml.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/DSA.Xml.cs index cfa242d50fb96..f32e384c70e94 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/DSA.Xml.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/DSA.Xml.cs @@ -127,10 +127,12 @@ public override string ToXmlString(bool includePrivateParameters) { if (keyParameters.X == null) { +#pragma warning disable CA2208 // Instantiate argument exceptions correctly // .NET Framework compat when a 3rd party type lets X be null when // includePrivateParameters is true // (the exception would have been from Convert.ToBase64String) throw new ArgumentNullException("inArray"); +#pragma warning restore CA2208 } XmlKeyHelper.WriteCryptoBinary(nameof(DSAParameters.X), keyParameters.X, builder); diff --git a/src/libraries/System.Security.Cryptography.Encoding/src/System/Security/Cryptography/PemEncoding.cs b/src/libraries/System.Security.Cryptography.Encoding/src/System/Security/Cryptography/PemEncoding.cs index 7232a72205c9c..0315d5ba4b3e0 100644 --- a/src/libraries/System.Security.Cryptography.Encoding/src/System/Security/Cryptography/PemEncoding.cs +++ b/src/libraries/System.Security.Cryptography.Encoding/src/System/Security/Cryptography/PemEncoding.cs @@ -438,7 +438,7 @@ static int WriteBase64(ReadOnlySpan bytes, Span dest, int offset) if (!success) { Debug.Fail("Convert.TryToBase64Chars failed with a pre-sized buffer"); - throw new ArgumentException(); + throw new ArgumentException(null, nameof(destination)); } return base64Written; @@ -528,7 +528,7 @@ public static char[] Write(ReadOnlySpan label, ReadOnlySpan data) if (!TryWrite(label, data, buffer, out int charsWritten)) { Debug.Fail("TryWrite failed with a pre-sized buffer"); - throw new ArgumentException(); + throw new ArgumentException(null, nameof(data)); } Debug.Assert(charsWritten == encodedSize); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/Resources/Strings.resx b/src/libraries/System.Security.Cryptography.Pkcs/src/Resources/Strings.resx index 117980b01ba6e..aa366d559ef7d 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/Resources/Strings.resx +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/Resources/Strings.resx @@ -1,4 +1,5 @@ - + + @@ -57,8 +58,8 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - String cannot be empty or null. + + The `{0}` string cannot be empty or null. Only single dimensional arrays are supported for the requested action. @@ -214,10 +215,10 @@ New Pkcs12SafeBag values cannot be added to a Pkcs12SafeContents that was read from existing data. - This decryption operation applies to 'Pkcs12ConfidentialityMode.{0}', but the target object is in 'Pkcs12ConfidentialityMode.{1}'. + This decryption operation applies to 'Pkcs12ConfidentialityMode.{0}', but the target object is in 'Pkcs12ConfidentialityMode.{1}'. - This verification operation applies to 'Pkcs12IntegrityMode.{0}', but the target object is in 'Pkcs12IntegrityMode.{1}'. + This verification operation applies to 'Pkcs12IntegrityMode.{0}', but the target object is in 'Pkcs12IntegrityMode.{1}'. Invalid signature paramters. @@ -294,4 +295,4 @@ Certificate already present in the collection. - + \ No newline at end of file diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12Builder.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12Builder.cs index 4290deb59336b..be3874b32d4bb 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12Builder.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12Builder.cs @@ -41,7 +41,7 @@ public void AddSafeContentsEncrypted( if (pbeParameters == null) throw new ArgumentNullException(nameof(pbeParameters)); if (pbeParameters.IterationCount < 1) - throw new ArgumentOutOfRangeException(nameof(pbeParameters.IterationCount)); + throw new ArgumentOutOfRangeException(nameof(pbeParameters)); if (safeContents.ConfidentialityMode != Pkcs12ConfidentialityMode.None) throw new ArgumentException(SR.Cryptography_Pkcs12_CannotProcessEncryptedSafeContents, nameof(safeContents)); if (IsSealed) @@ -89,7 +89,7 @@ public void AddSafeContentsEncrypted( if (pbeParameters == null) throw new ArgumentNullException(nameof(pbeParameters)); if (pbeParameters.IterationCount < 1) - throw new ArgumentOutOfRangeException(nameof(pbeParameters.IterationCount)); + throw new ArgumentOutOfRangeException(nameof(pbeParameters)); if (safeContents.ConfidentialityMode != Pkcs12ConfidentialityMode.None) throw new ArgumentException(SR.Cryptography_Pkcs12_CannotProcessEncryptedSafeContents, nameof(safeContents)); if (IsSealed) diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9AttributeObject.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9AttributeObject.cs index 11bb644cafa87..cb86b388484ea 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9AttributeObject.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9AttributeObject.cs @@ -32,12 +32,12 @@ public Pkcs9AttributeObject(AsnEncodedData asnEncodedData) : base(asnEncodedData) { if (asnEncodedData.Oid == null) - throw new ArgumentNullException(nameof(asnEncodedData.Oid)); + throw new ArgumentException(SR.Format(SR.Arg_EmptyOrNullString_Named, "asnEncodedData.Oid"), nameof(asnEncodedData)); string? szOid = base.Oid!.Value; if (szOid == null) - throw new ArgumentNullException("oid.Value"); + throw new ArgumentException(SR.Format(SR.Arg_EmptyOrNullString_Named, "oid.Value"), nameof(asnEncodedData)); if (szOid.Length == 0) - throw new ArgumentException(SR.Arg_EmptyOrNullString, "oid.Value"); + throw new ArgumentException(SR.Format(SR.Arg_EmptyOrNullString_Named, "oid.Value"), nameof(asnEncodedData)); } internal Pkcs9AttributeObject(Oid oid) diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignedCms.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignedCms.cs index d45d274e7639b..74646c7186cd3 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignedCms.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignedCms.cs @@ -45,7 +45,7 @@ public SignedCms(SubjectIdentifierType signerIdentifierType, ContentInfo content if (contentInfo == null) throw new ArgumentNullException(nameof(contentInfo)); if (contentInfo.Content == null) - throw new ArgumentNullException("contentInfo.Content"); + throw new ArgumentException(SR.Format(SR.Arg_EmptyOrNullString_Named, "contentInfo.Content"), nameof(contentInfo)); // Normalize the subject identifier type the same way as .NET Framework. // This value is only used in the zero-argument ComputeSignature overload, diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfo.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfo.cs index 9247ae50b14bf..3d1e349f52985 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfo.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfo.cs @@ -358,9 +358,7 @@ public void RemoveCounterSignature(int index) { if (index < 0) { - // In .NET Framework RemoveCounterSignature doesn't bounds check, but the helper it calls does. - // In the helper the argument is called "childIndex". - throw new ArgumentOutOfRangeException("childIndex"); + throw new ArgumentOutOfRangeException(nameof(index)); } // The SignerInfo class is a projection of data contained within the SignedCms. diff --git a/src/libraries/System.Security.Cryptography.Pkcs/tests/Pkcs9AttributeTests.cs b/src/libraries/System.Security.Cryptography.Pkcs/tests/Pkcs9AttributeTests.cs index 9591a1bce1a5b..79aa1a42805f5 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/tests/Pkcs9AttributeTests.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/tests/Pkcs9AttributeTests.cs @@ -24,7 +24,7 @@ public static void Pkcs9AttributeAsnEncodedDataCtorNullOid() { AsnEncodedData a = new AsnEncodedData(new byte[3]); object ign; - Assert.Throws(() => ign = new Pkcs9AttributeObject(a)); + AssertExtensions.Throws("asnEncodedData", "asnEncodedData.Oid", () => ign = new Pkcs9AttributeObject(a)); } [Fact] @@ -112,7 +112,7 @@ public static void Pkcs9AttributeAsnEncodedDataCtorNullOidValue() AsnEncodedData a = new AsnEncodedData(oid, new byte[3]); object ign; - Assert.Throws(() => ign = new Pkcs9AttributeObject(a)); + AssertExtensions.Throws("asnEncodedData", "oid.Value", () => ign = new Pkcs9AttributeObject(a)); } [Fact] @@ -123,7 +123,7 @@ public static void Pkcs9AttributeAsnEncodedDataCtorEmptyOidValue() AsnEncodedData a = new AsnEncodedData(oid, new byte[3]); object ign; - AssertExtensions.Throws("oid.Value", () => ign = new Pkcs9AttributeObject(a)); + AssertExtensions.Throws("asnEncodedData", "oid.Value", () => ign = new Pkcs9AttributeObject(a)); } [Fact] diff --git a/src/libraries/System.Security.Cryptography.Pkcs/tests/SignedCms/SignerInfoTests.cs b/src/libraries/System.Security.Cryptography.Pkcs/tests/SignedCms/SignerInfoTests.cs index 34a48544a868b..ddfa1dd7f7976 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/tests/SignedCms/SignerInfoTests.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/tests/SignedCms/SignerInfoTests.cs @@ -481,6 +481,7 @@ public static void RemoveCounterSignature_Negative() SignerInfo signer = cms.SignerInfos[0]; ArgumentOutOfRangeException ex = AssertExtensions.Throws( + "index", "childIndex", () => signer.RemoveCounterSignature(-1)); diff --git a/src/libraries/System.Security.Cryptography.X509Certificates/src/Resources/Strings.resx b/src/libraries/System.Security.Cryptography.X509Certificates/src/Resources/Strings.resx index 37fc7642786bc..d5e8ac308897f 100644 --- a/src/libraries/System.Security.Cryptography.X509Certificates/src/Resources/Strings.resx +++ b/src/libraries/System.Security.Cryptography.X509Certificates/src/Resources/Strings.resx @@ -1,4 +1,5 @@ - + + @@ -66,6 +67,9 @@ String cannot be empty or null. + + The '{0}' string cannot be empty or null. + Illegal enum value: {0}. @@ -74,7 +78,7 @@ Invalid type. - + Non-negative number required. @@ -223,7 +227,7 @@ The provided hash value is not the expected size for the specified hash algorithm. - The Disallowed store is not supported on this platform, but already has data. All files under '{0}' must be removed. + The Disallowed store is not supported on this platform, but already has data. All files under '{0}' must be removed. Unix LocalMachine X509Stores are read-only for all users. @@ -235,7 +239,7 @@ The Disallowed store is not supported on this platform. - The {0} value cannot be set on Unix. + The {0} value cannot be set on Unix. '{0}' is not a known hash algorithm. @@ -286,7 +290,7 @@ The X509 certificate store is read-only. - The platform does not have a definition for an X509 certificate store named '{0}' with a StoreLocation of '{1}', and does not support creating it. + The platform does not have a definition for an X509 certificate store named '{0}' with a StoreLocation of '{1}', and does not support creating it. Enumeration has not started. Call MoveNext. @@ -417,4 +421,4 @@ Key is not a valid private key. - + \ No newline at end of file diff --git a/src/libraries/System.Security.Cryptography.X509Certificates/src/System/Security/Cryptography/X509Certificates/X509Extension.cs b/src/libraries/System.Security.Cryptography.X509Certificates/src/System/Security/Cryptography/X509Certificates/X509Extension.cs index af33813026922..84d5cb3eae3e9 100644 --- a/src/libraries/System.Security.Cryptography.X509Certificates/src/System/Security/Cryptography/X509Certificates/X509Extension.cs +++ b/src/libraries/System.Security.Cryptography.X509Certificates/src/System/Security/Cryptography/X509Certificates/X509Extension.cs @@ -31,7 +31,7 @@ public X509Extension(Oid oid, byte[] rawData, bool critical) if (base.Oid == null || base.Oid.Value == null) throw new ArgumentNullException(nameof(oid)); if (base.Oid.Value.Length == 0) - throw new ArgumentException(SR.Arg_EmptyOrNullString, "oid.Value"); + throw new ArgumentException(SR.Format(SR.Arg_EmptyOrNullString_Named, "oid.Value"), nameof(oid)); Critical = critical; } 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 81da0b439bb03..19782152c0169 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 @@ -640,7 +640,9 @@ public SecurityIdentifier(WellKnownSidType sidType, SecurityIdentifier? domainSi if (error == Interop.Errors.ERROR_INVALID_PARAMETER) { +#pragma warning disable CA2208 // Instantiate argument exceptions correctly, combination of arguments used throw new ArgumentException(new Win32Exception(error).Message, "sidType/domainSid"); +#pragma warning restore CS2208 } else if (error != Interop.Errors.ERROR_SUCCESS) { diff --git a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/WindowsIdentity.cs b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/WindowsIdentity.cs index be5c623b29967..0c4e03d627194 100644 --- a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/WindowsIdentity.cs +++ b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/WindowsIdentity.cs @@ -134,11 +134,8 @@ public WindowsIdentity(string sUserPrincipalName) sourceContext.SourceName = new byte[TOKEN_SOURCE.TOKEN_SOURCE_LENGTH]; Buffer.BlockCopy(sourceName, 0, sourceContext.SourceName, 0, sourceName.Length); - // .NET Framework compat: Desktop never null-checks sUserPrincipalName. Actual behavior is that the null makes it down to Encoding.Unicode.GetBytes() which then throws - // the ArgumentNullException (provided that the prior LSA calls didn't fail first.) To make this compat decision explicit, we'll null check ourselves - // and simulate the exception from Encoding.Unicode.GetBytes(). if (sUserPrincipalName == null) - throw new ArgumentNullException("s"); + throw new ArgumentNullException(nameof(sUserPrincipalName)); byte[] upnBytes = Encoding.Unicode.GetBytes(sUserPrincipalName); if (upnBytes.Length > ushort.MaxValue) 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 71e2285e792a5..acd51f7c186fc 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionScope.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionScope.cs @@ -211,7 +211,7 @@ TransactionScopeAsyncFlowOption asyncFlowOption // If the requested IsolationLevel is stronger than that of the specified transaction, throw. if ((IsolationLevel.Unspecified != transactionOptions.IsolationLevel) && (_expectedCurrent.IsolationLevel != transactionOptions.IsolationLevel)) { - throw new ArgumentException(SR.TransactionScopeIsolationLevelDifferentFromTransaction, "transactionOptions.IsolationLevel"); + throw new ArgumentException(SR.TransactionScopeIsolationLevelDifferentFromTransaction, nameof(transactionOptions)); } } } @@ -293,7 +293,7 @@ public TransactionScope( // If the requested IsolationLevel is stronger than that of the specified transaction, throw. if ((IsolationLevel.Unspecified != transactionOptions.IsolationLevel) && (_expectedCurrent.IsolationLevel != transactionOptions.IsolationLevel)) { - throw new ArgumentException(SR.TransactionScopeIsolationLevelDifferentFromTransaction, "transactionOptions.IsolationLevel"); + throw new ArgumentException(SR.TransactionScopeIsolationLevelDifferentFromTransaction, nameof(transactionOptions)); } } } diff --git a/src/libraries/System.Windows.Extensions/src/System/Drawing/FontConverter.cs b/src/libraries/System.Windows.Extensions/src/System/Drawing/FontConverter.cs index aaea6553cf598..af1308e860eac 100644 --- a/src/libraries/System.Windows.Extensions/src/System/Drawing/FontConverter.cs +++ b/src/libraries/System.Windows.Extensions/src/System/Drawing/FontConverter.cs @@ -173,7 +173,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c catch { // Exception from converter is too generic. - throw new ArgumentException(SR.Format(SR.TextParseFailedFormat, font, $"name{separator} size[units[{separator} style=style1[{separator} style2{separator} ...]]]"), nameof(sizeStr)); + throw new ArgumentException(SR.Format(SR.TextParseFailedFormat, font, $"name{separator} size[units[{separator} style=style1[{separator} style2{separator} ...]]]"), nameof(value)); } } diff --git a/src/libraries/System.Windows.Extensions/tests/System/Drawing/FontConverterTests.cs b/src/libraries/System.Windows.Extensions/tests/System/Drawing/FontConverterTests.cs index 02a01346d208f..951ccfaeb9193 100644 --- a/src/libraries/System.Windows.Extensions/tests/System/Drawing/FontConverterTests.cs +++ b/src/libraries/System.Windows.Extensions/tests/System/Drawing/FontConverterTests.cs @@ -131,7 +131,7 @@ private static bool EmptyFontPresent public static TheoryData ArgumentExceptionFontConverterData() => new TheoryData() { { $"Courier New{s_Separator} 11 px{s_Separator} type=Bold{s_Separator} Italic", "units", null }, - { $"Courier New{s_Separator} {s_Separator} Style=Bold", "sizeStr", null }, + { $"Courier New{s_Separator} {s_Separator} Style=Bold", "value", null }, { $"Courier New{s_Separator} 11{s_Separator} Style=", "value", null }, { $"Courier New{s_Separator} 11{s_Separator} Style=RandomEnum", null, null }, { $"Arial{s_Separator} 10{s_Separator} style=bold{s_Separator}", "value", null }, diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/GC.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/GC.Mono.cs index 945356c17dec5..b7ac9cfaf4cdf 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/GC.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/GC.Mono.cs @@ -113,7 +113,7 @@ public static int GetGeneration(WeakReference wo) { object? obj = wo.Target; if (obj == null) - throw new ArgumentException(); + throw new ArgumentException(null, nameof(wo)); return GetGeneration(obj); } diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.Mono.cs index 00bcc90d59bf8..4ee8768fcb03a 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.Mono.cs @@ -261,7 +261,7 @@ public void AddInterfaceImplementation(Type interfaceType) if (interfaceType == null) throw new ArgumentNullException(nameof(interfaceType)); if (interfaceType.IsByRef) - throw new ArgumentException(nameof(interfaceType)); + throw new ArgumentException(SR.Argument_CannotGetTypeTokenForByRef); check_not_created(); if (interfaces != null) @@ -479,7 +479,7 @@ public ConstructorBuilder DefineDefaultConstructor(MethodAttributes attributes) if (IsInterface) throw new InvalidOperationException(); if ((attributes & (MethodAttributes.Static | MethodAttributes.Virtual)) > 0) - throw new ArgumentException(nameof(attributes)); + throw new ArgumentException(SR.Arg_NoStaticVirtual); if (parent != null) parent_type = parent; @@ -1515,7 +1515,7 @@ public EventBuilder DefineEvent(string name, EventAttributes attributes, Type ev { check_name(nameof(name), name); if (eventtype == null) - throw new ArgumentNullException("type"); + throw new ArgumentNullException(nameof(eventtype)); check_not_created(); if (eventtype.IsByRef) throw new ArgumentException(SR.Argument_CannotGetTypeTokenForByRef); @@ -1597,7 +1597,7 @@ public void SetParent(Type? parent) else { if (parent.IsInterface) - throw new ArgumentException(nameof(parent)); + throw new ArgumentException(SR.Argument_CannotSetParentToInterface); this.parent = parent; } this.parent = ResolveUserType(this.parent); @@ -1878,7 +1878,7 @@ public static FieldInfo GetField(Type type, FieldInfo field) throw new ArgumentException("The specified field must be declared on a generic type definition.", nameof(field)); if (field.DeclaringType != type.GetGenericTypeDefinition()) - throw new ArgumentException("field declaring type is not the generic type definition of type", "method"); + throw new ArgumentException("field declaring type is not the generic type definition of type", nameof(field)); FieldInfo res = type.GetField(field); if (res == null) diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.Mono.cs index 5dcda6d90fed6..7c80ba8fb5c6b 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.Mono.cs @@ -8,8 +8,10 @@ public partial class RuntimeHelpers { public static void InitializeArray(Array array, RuntimeFieldHandle fldHandle) { - if (array == null || fldHandle.Value == IntPtr.Zero) - throw new ArgumentNullException(); + if (array == null) + throw new ArgumentNullException(nameof(array)); + if (fldHandle.Value == IntPtr.Zero) + throw new ArgumentNullException(nameof(fldHandle)); InitializeArray(array, fldHandle.Value); } diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/RuntimeType.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/RuntimeType.Mono.cs index 9628d4956bcf0..71ff174e23d24 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/RuntimeType.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/RuntimeType.Mono.cs @@ -873,7 +873,7 @@ public override MemberInfo[] GetMembers(BindingFlags bindingAttr) protected override PropertyInfo? GetPropertyImpl( string name, BindingFlags bindingAttr, Binder? binder, Type? returnType, Type[]? types, ParameterModifier[]? modifiers) { - if (name == null) throw new ArgumentNullException(); + if (name == null) throw new ArgumentNullException(nameof(name)); ListBuilder candidates = GetPropertyCandidates(name, bindingAttr, types, false); @@ -911,7 +911,7 @@ public override MemberInfo[] GetMembers(BindingFlags bindingAttr) public override EventInfo? GetEvent(string name, BindingFlags bindingAttr) { - if (name == null) throw new ArgumentNullException(); + if (name == null) throw new ArgumentNullException(nameof(name)); bool ignoreCase; MemberListType listType; @@ -978,7 +978,7 @@ public override MemberInfo[] GetMembers(BindingFlags bindingAttr) public override Type? GetInterface(string fullname, bool ignoreCase) { - if (fullname == null) throw new ArgumentNullException(); + if (fullname == null) throw new ArgumentNullException(nameof(fullname)); BindingFlags bindingAttr = BindingFlags.Public | BindingFlags.NonPublic; @@ -1031,7 +1031,7 @@ public override MemberInfo[] GetMembers(BindingFlags bindingAttr) public override Type? GetNestedType(string fullname, BindingFlags bindingAttr) { - if (fullname == null) throw new ArgumentNullException(); + if (fullname == null) throw new ArgumentNullException(nameof(fullname)); bool ignoreCase; bindingAttr &= ~BindingFlags.Static; @@ -1059,7 +1059,7 @@ public override MemberInfo[] GetMembers(BindingFlags bindingAttr) public override MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr) { - if (name == null) throw new ArgumentNullException(); + if (name == null) throw new ArgumentNullException(nameof(name)); ListBuilder methods = default; ListBuilder constructors = default;