From 5c7015324490dcb948a7aca2cb4a8448858378ae Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Tue, 15 Apr 2025 08:58:16 -0400 Subject: [PATCH] Use extension everything to polyfill ArgumentNullException.ThrowIfNull --- .../src/System/Reflection/MethodInvoker.cs | 2 +- .../InteropServices/Marshal.NativeAot.cs | 2 +- .../NonCapturingTimer/NonCapturingTimer.cs | 5 +- .../src/System/CodeDom/CodeTypeReference.cs | 7 - .../CodeDom/CodeTypeReferenceCollection.cs | 14 -- .../Diagnostics/CompositionTrace.cs | 60 ++---- .../Common/src/System/ExceptionPolyfills.cs | 27 +++ .../src/System/IO/ReadOnlyMemoryStream.cs | 5 +- .../System/IO/StreamHelpers.CopyValidation.cs | 5 +- .../src/System/Resources/ResourceWriter.cs | 30 +-- .../System/Security/Cryptography/AesGcm.cs | 28 --- .../Cryptography/Asn1/AttributeAsn.manual.cs | 6 +- .../Asn1/X509ExtensionAsn.manual.cs | 7 - .../CryptographicAttributeObjectCollection.cs | 25 +-- .../src/System/Security/Cryptography/MLDsa.cs | 25 +-- .../src/System/Security/Cryptography/MLKem.cs | 66 +++---- .../Cryptography/Pkcs/Pkcs12Builder.cs | 25 +-- .../Cryptography/Pkcs/Pkcs12CertBag.cs | 5 +- .../Cryptography/Pkcs/Pkcs12SafeContents.cs | 35 +--- .../Cryptography/Pkcs/Pkcs8PrivateKeyInfo.cs | 30 +-- .../Cryptography/Pkcs/Pkcs9AttributeObject.cs | 5 +- .../Pkcs/Pkcs9DocumentDescription.cs | 5 +- .../Cryptography/Pkcs/Pkcs9DocumentName.cs | 5 +- .../Cryptography/SP800108HmacCounterKdf.cs | 39 ++-- .../System/Security/Cryptography/SlhDsa.cs | 31 +--- .../X509Certificates/Pkcs12LoaderLimits.cs | 5 - .../X509Certificates/X509CertificateLoader.cs | 16 +- .../Threading/Tasks/TaskToAsyncResult.cs | 19 +- .../Common/src/System/ThrowHelper.cs | 51 ----- .../Common/src/System/TimeProvider.cs | 5 +- .../System/Net/WebSockets/WebSocketStream.cs | 5 +- .../CompilerServices/RuntimeHelpers.cs | 2 +- src/libraries/Directory.Build.targets | 14 +- .../Sources/ManualResetValueTaskSourceCore.cs | 5 +- .../Security/Cryptography/NetStandardShims.cs | 14 -- .../X509CertificateLoader.netfx.cs | 2 +- .../Tasks/TimeProviderTaskExtensions.cs | 20 +- .../src/CacheEntryExtensions.cs | 6 +- .../src/DistributedCacheExtensions.cs | 16 +- .../src/MemoryCacheEntryExtensions.cs | 6 +- ...oft.Extensions.Caching.Abstractions.csproj | 1 - .../src/CacheEntry.cs | 4 +- .../src/MemoryCache.cs | 10 +- .../MemoryCacheServiceCollectionExtensions.cs | 12 +- .../src/MemoryDistributedCache.cs | 28 +-- ...Microsoft.Extensions.Caching.Memory.csproj | 2 - .../src/ConfigurationExtensions.cs | 2 +- .../src/ConfigurationPath.cs | 4 +- ...tensions.Configuration.Abstractions.csproj | 4 +- .../src/ConfigurationBinder.cs | 16 +- ...oft.Extensions.Configuration.Binder.csproj | 1 - .../src/Properties/InternalsVisibleTo.cs | 7 - ...ation.Binder.SourceGeneration.Tests.csproj | 4 +- ...tensions.Configuration.Binder.Tests.csproj | 1 + .../src/CommandLineConfigurationProvider.cs | 2 +- ...xtensions.Configuration.CommandLine.csproj | 2 - .../src/FileConfigurationExtensions.cs | 14 +- .../src/FileConfigurationProvider.cs | 2 +- ...nsions.Configuration.FileExtensions.csproj | 2 - .../src/IniConfigurationExtensions.cs | 4 +- ...rosoft.Extensions.Configuration.Ini.csproj | 2 - .../src/JsonConfigurationExtensions.cs | 4 +- ...osoft.Extensions.Configuration.Json.csproj | 2 - ...xtensions.Configuration.UserSecrets.csproj | 2 - .../src/UserSecretsConfigurationExtensions.cs | 8 +- ...rosoft.Extensions.Configuration.Xml.csproj | 5 - .../src/XmlConfigurationElement.cs | 2 +- .../XmlConfigurationElementAttributeValue.cs | 4 +- .../src/XmlConfigurationElementTextContent.cs | 2 +- .../src/XmlConfigurationExtensions.cs | 4 +- .../src/ChainedBuilderExtensions.cs | 4 +- .../src/ChainedConfigurationProvider.cs | 2 +- .../src/ConfigurationBuilder.cs | 2 +- .../src/ConfigurationManager.cs | 2 +- .../src/ConfigurationRoot.cs | 2 +- .../src/ConfigurationSection.cs | 4 +- .../MemoryConfigurationBuilderExtensions.cs | 4 +- .../src/MemoryConfigurationProvider.cs | 2 +- .../Microsoft.Extensions.Configuration.csproj | 4 +- .../src/StreamConfigurationProvider.cs | 2 +- .../src/ActivatorUtilities.cs | 31 +--- .../src/AsyncServiceScope.cs | 2 +- ...iceCollectionDescriptorExtensions.Keyed.cs | 66 +++---- .../ServiceCollectionDescriptorExtensions.cs | 94 +++++----- ...ns.DependencyInjection.Abstractions.csproj | 2 - ...erviceCollectionServiceExtensions.Keyed.cs | 94 +++++----- .../src/ServiceCollectionServiceExtensions.cs | 94 +++++----- .../src/ServiceDescriptor.cs | 92 ++++----- .../ServiceProviderKeyedServiceExtensions.cs | 18 +- .../src/ServiceProviderServiceExtensions.cs | 14 +- ...crosoft.Extensions.DependencyInjection.sln | 30 +-- ...iceCollectionContainerBuilderExtensions.cs | 10 +- .../src/ServiceLookup/CallSiteFactory.cs | 5 +- .../src/CompilationLibrary.cs | 2 +- .../src/CompilationOptions.cs | 2 +- .../src/DependencyContext.cs | 12 +- .../src/DependencyContextExtensions.cs | 44 ++--- .../src/DependencyContextJsonReader.cs | 2 +- .../src/DependencyContextLoader.cs | 2 +- .../src/DependencyContextWriter.cs | 4 +- .../src/Library.cs | 2 +- ...icrosoft.Extensions.DependencyModel.csproj | 2 - .../AppBaseCompilationAssemblyResolver.cs | 8 +- .../CompositeCompilationAssemblyResolver.cs | 2 +- .../PackageCompilationAssemblyResolver.cs | 6 +- .../ReferenceAssemblyPathResolver.cs | 6 +- .../src/RuntimeFallbacks.cs | 2 +- .../src/RuntimeLibrary.cs | 6 +- .../MetricsBuilderExtensions.Listeners.cs | 6 +- .../Metrics/MetricsBuilderExtensions.Rules.cs | 4 +- ...Extensions.Diagnostics.Abstractions.csproj | 1 - .../MetricListenerConfigurationFactory.cs | 2 +- .../MetricsBuilderConfigurationExtensions.cs | 10 +- .../src/Metrics/DefaultMeterFactory.cs | 5 +- .../src/Metrics/MetricsServiceExtensions.cs | 10 +- .../Microsoft.Extensions.Diagnostics.csproj | 1 - .../src/CompositeDirectoryContents.cs | 2 +- .../src/CompositeFileProvider.cs | 2 +- ....Extensions.FileProviders.Composite.csproj | 2 - .../src/Internal/PhysicalDirectoryContents.cs | 2 +- ...t.Extensions.FileProviders.Physical.csproj | 2 - .../src/PhysicalFilesWatcher.cs | 2 +- .../src/Abstractions/FileInfoWrapper.cs | 2 +- .../src/FilePatternMatch.cs | 2 +- .../PathSegments/LiteralPathSegment.cs | 2 +- .../PathSegments/WildcardPathSegment.cs | 6 +- .../PatternContexts/PatternContextLinear.cs | 2 +- .../PatternContexts/PatternContextRagged.cs | 2 +- .../src/Internal/Patterns/PatternBuilder.cs | 2 +- .../src/Matcher.cs | 2 +- .../src/MatcherExtensions.cs | 2 +- ...osoft.Extensions.FileSystemGlobbing.csproj | 2 - .../src/PatternMatchingResult.cs | 2 +- .../src/HostBuilderContext.cs | 2 +- .../src/HostEnvironmentEnvExtensions.cs | 8 +- .../src/HostingEnvironmentExtensions.cs | 8 +- ...oft.Extensions.Hosting.Abstractions.csproj | 1 - ...icrosoft.Extensions.Hosting.Systemd.csproj | 1 - .../src/ServiceState.cs | 2 +- .../src/SystemdHostBuilderExtensions.cs | 4 +- .../src/SystemdLifetime.cs | 8 +- ....Extensions.Hosting.WindowsServices.csproj | 2 - .../src/WindowsServiceLifetime.cs | 10 +- ...owsServiceLifetimeHostBuilderExtensions.cs | 4 +- .../src/HostApplicationBuilder.cs | 12 +- .../src/HostBuilder.cs | 12 +- .../src/HostingHostBuilderExtensions.cs | 4 +- .../src/Internal/ConfigureContainerAdapter.cs | 2 +- .../src/Internal/ConsoleLifetime.cs | 10 +- .../src/Internal/Host.cs | 8 +- .../src/Internal/ServiceFactoryAdapter.cs | 6 +- .../src/Microsoft.Extensions.Hosting.csproj | 4 - .../src/DefaultHttpClientFactory.cs | 12 +- .../src/DefaultHttpMessageHandlerBuilder.cs | 2 +- .../src/DefaultTypedHttpClientFactory.cs | 4 +- .../HttpClientBuilderExtensions.Logging.cs | 10 +- .../HttpClientBuilderExtensions.cs | 74 ++++---- ...lientFactoryServiceCollectionExtensions.cs | 94 +++++----- .../HttpClientKeyedLifetime.cs | 2 +- .../src/HttpClientFactoryExtensions.cs | 2 +- .../src/HttpMessageHandlerBuilder.cs | 4 +- .../HttpMessageHandlerFactoryExtensions.cs | 2 +- .../src/Logging/HttpClientLoggerHandler.cs | 6 +- .../src/Logging/LoggingHttpMessageHandler.cs | 8 +- .../LoggingHttpMessageHandlerBuilderFilter.cs | 6 +- .../Logging/LoggingScopeHttpMessageHandler.cs | 8 +- .../MetricsFactoryHttpMessageHandlerFilter.cs | 4 +- .../src/Microsoft.Extensions.Http.csproj | 2 - .../src/LogValuesFormatter.cs | 2 +- .../src/LoggerExtensions.cs | 4 +- .../src/LoggerFactoryExtensions.cs | 6 +- .../src/LoggerT.cs | 2 +- ...oft.Extensions.Logging.Abstractions.csproj | 2 - .../src/LoggerProviderConfigurationFactory.cs | 2 +- ...ft.Extensions.Logging.Configuration.csproj | 2 - .../src/AnsiParser.cs | 2 +- .../src/ConsoleFormatter.cs | 2 +- .../src/ConsoleLogger.cs | 6 +- .../src/ConsoleLoggerExtensions.cs | 7 +- ...icrosoft.Extensions.Logging.Console.csproj | 1 - .../src/DebugLogger.cs | 2 +- .../Microsoft.Extensions.Logging.Debug.csproj | 2 - .../src/EventLogLogger.cs | 6 +- .../src/EventLoggerFactoryExtensions.cs | 12 +- ...crosoft.Extensions.Logging.EventLog.csproj | 2 - .../src/EventSourceLoggerFactoryExtensions.cs | 4 +- .../src/EventSourceLoggerProvider.cs | 2 +- ...soft.Extensions.Logging.EventSource.csproj | 2 - ...soft.Extensions.Logging.TraceSource.csproj | 4 - .../src/TraceSourceFactoryExtensions.cs | 40 ++-- .../src/TraceSourceLoggerProvider.cs | 2 +- .../src/LoggerFactory.cs | 2 +- .../src/LoggingServiceCollectionExtensions.cs | 2 +- .../src/Microsoft.Extensions.Logging.csproj | 2 - .../DI.Common/Common/src/LogValuesAssert.cs | 5 +- .../src/ConfigurationChangeTokenSource.cs | 2 +- .../src/ConfigureFromConfigurationOptions.cs | 2 +- ...ons.Options.ConfigurationExtensions.csproj | 4 - .../NamedConfigureFromConfigurationOptions.cs | 2 +- .../OptionsBuilderConfigurationExtensions.cs | 6 +- ...onfigurationServiceCollectionExtensions.cs | 4 +- .../src/DataAnnotationValidateOptions.cs | 2 +- ....Extensions.Options.DataAnnotations.csproj | 4 - .../src/ConfigureNamedOptions.cs | 12 +- .../src/ConfigureOptions.cs | 2 +- .../src/Microsoft.Extensions.Options.csproj | 4 - .../src/OptionsBuilder.cs | 38 ++-- .../src/OptionsBuilderExtensions.cs | 2 +- .../src/OptionsCache.cs | 4 +- .../src/OptionsServiceCollectionExtensions.cs | 12 +- .../src/OptionsValidationException.cs | 4 +- .../src/PostConfigureOptions.cs | 12 +- .../src/ValidateOptions.cs | 12 +- .../src/ValidateOptionsResultBuilder.cs | 4 +- ...ions.Options.SourceGeneration.Tests.csproj | 1 - .../Microsoft/Win32/RegistryAclExtensions.cs | 15 +- .../src/Sgen.cs | 5 +- .../Microsoft/CSharp/CSharpCodeGenerator.cs | 100 ++-------- .../Microsoft/CSharp/CSharpCodeProvider.cs | 5 +- .../CSharpModifierAttributeConverter.cs | 5 +- .../Microsoft/VisualBasic/VBCodeProvider.cs | 5 +- .../VBModifierAttributeConverter.cs | 5 +- .../CodeAttributeArgumentCollection.cs | 10 +- .../CodeAttributeDeclarationCollection.cs | 10 +- .../CodeDom/CodeCatchClauseCollection.cs | 10 +- .../CodeDom/CodeCommentStatementCollection.cs | 10 +- .../System/CodeDom/CodeDirectiveCollection.cs | 10 +- .../CodeDom/CodeExpressionCollection.cs | 10 +- .../System/CodeDom/CodeNamespaceCollection.cs | 10 +- .../CodeDom/CodeNamespaceImportCollection.cs | 5 +- ...arameterDeclarationExpressionCollection.cs | 10 +- .../System/CodeDom/CodeStatementCollection.cs | 10 +- .../CodeDom/CodeTypeDeclarationCollection.cs | 10 +- .../CodeDom/CodeTypeMemberCollection.cs | 10 +- .../CodeDom/CodeTypeParameterCollection.cs | 10 +- .../System/CodeDom/Compiler/CodeCompiler.cs | 85 ++------- .../CodeDom/Compiler/CodeDomProvider.cs | 10 +- .../System/CodeDom/Compiler/CodeGenerator.cs | 115 +++--------- .../System/CodeDom/Compiler/CodeValidator.cs | 20 +- .../Compiler/CompilerErrorCollection.cs | 10 +- .../System/CodeDom/Compiler/CompilerInfo.cs | 5 +- .../Collections/Frozen/FrozenDictionary.cs | 10 +- .../System/Collections/Frozen/FrozenSet.cs | 16 +- .../src/System/Collections/ThrowHelper.cs | 8 - .../src/System/Polyfills.cs | 13 -- .../Collections/Generic/OrderedDictionary.cs | 55 +++--- .../src/System/Collections/ThrowHelper.cs | 11 -- .../Composition/Registration/PartBuilder.cs | 45 +---- .../Registration/PartBuilderOfT.cs | 35 +--- .../Registration/RegistrationBuilder.cs | 20 +- .../CatalogReflectionContextAttribute.cs | 5 +- .../Composition/ExceptionBuilder.cs | 5 +- .../Composition/ExportServices.cs | 10 +- .../Hosting/CatalogExportProvider.cs | 11 +- .../GenericSpecializationPartCreationInfo.cs | 10 +- .../ReflectionModel/ReflectionExtensions.cs | 5 +- .../Convention/ConventionBuilder.cs | 30 +-- .../Convention/ExportConventionBuilder.cs | 30 +-- .../Convention/ImportConventionBuilder.cs | 25 +-- .../Convention/PartConventionBuilder.cs | 115 +++--------- .../Convention/PartConventionBuilderOfT.cs | 45 +---- .../Composition/Hosting/CompositionHost.cs | 5 +- .../Hosting/Core/CompositionDependency.cs | 40 +--- .../Hosting/Core/CompositionOperation.cs | 20 +- .../Hosting/Core/DirectExportDescriptor.cs | 10 +- .../Composition/Hosting/Util/Formatters.cs | 15 +- .../Hosting/Core/CompositionContract.cs | 5 +- .../CompositionContextExtensions.cs | 15 +- .../Hosting/ContainerConfiguration.cs | 50 +---- .../OnImportsSatisfiedFeature.cs | 5 +- .../TypedParts/Util/DirectAttributeContext.cs | 5 +- .../System/Configuration/AppSettingsReader.cs | 10 +- .../Configuration/ApplicationSettingsBase.cs | 5 +- .../System/Configuration/CallbackValidator.cs | 5 +- .../ConfigurationElementCollection.cs | 5 +- .../ConfigurationElementProperty.cs | 5 +- .../ConfigurationSectionCollection.cs | 5 +- .../ConfigurationSectionGroupCollection.cs | 5 +- .../PositiveTimeSpanValidator.cs | 5 +- .../PropertyInformationCollection.cs | 5 +- ...rotectedConfigurationProviderCollection.cs | 5 +- .../SettingsProviderCollection.cs | 5 +- .../src/System/Diagnostics/Activity.cs | 5 +- .../src/System/Diagnostics/ActivityContext.cs | 5 +- .../src/System/Diagnostics/ActivitySource.cs | 5 +- .../Diagnostics/ActivityTagsCollection.cs | 20 +- .../Diagnostics/Metrics/InstrumentAdvice.cs | 5 +- .../src/System/Diagnostics/Metrics/Meter.cs | 5 +- .../Metrics/MeterFactoryExtensions.cs | 5 +- .../Diagnostics/Metrics/TagList.netfx.cs | 5 +- ...ystem.Diagnostics.EventLog.Messages.csproj | 2 + .../CounterSetInstanceCounterDataSet.cs | 5 +- .../Protocols/common/DirectoryAttribute.cs | 12 +- .../Protocols/common/DirectoryControl.cs | 5 +- .../Protocols/ldap/LdapConnection.cs | 25 +-- .../ActiveDirectory/ADAMInstance.cs | 25 +-- .../ActiveDirectory/ADAMInstanceCollection.cs | 10 +- .../ActiveDirectory/ActiveDirectorySchema.cs | 10 +- .../ActiveDirectorySchemaClass.cs | 10 +- .../ActiveDirectorySchemaClassCollection.cs | 5 +- .../ActiveDirectory/ApplicationPartition.cs | 40 +--- .../ApplicationPartitionCollection.cs | 10 +- .../ActiveDirectory/ConfigSet.cs | 20 +- .../ActiveDirectory/DirectoryContext.cs | 10 +- .../ActiveDirectory/DirectoryServer.cs | 5 +- .../ActiveDirectory/Domain.cs | 20 +- .../ActiveDirectory/DomainController.cs | 45 +---- .../ActiveDirectory/Forest.cs | 20 +- .../ActiveDirectory/GlobalCatalog.cs | 45 +---- .../ReadOnlyStringCollection.cs | 10 +- .../ActiveDirectory/Utils.cs | 20 +- .../DirectoryServices/DirectoryEntry.cs | 5 +- .../PropertyValueCollection.cs | 10 +- .../DirectoryServices/SchemaNameCollection.cs | 10 +- .../Formats/Asn1/AsnWriter.Enumerated.cs | 5 +- .../Formats/Asn1/AsnWriter.NamedBitList.cs | 10 +- .../src/System/Formats/Asn1/AsnWriter.Oid.cs | 5 +- .../src/System/Formats/Asn1/AsnWriter.Text.cs | 5 +- .../src/System/Formats/Asn1/AsnWriter.cs | 19 +- .../Formats/Cbor/Writer/CborWriter.String.cs | 10 +- .../src/System/Formats/Nrbf/ArrayRecord.cs | 8 +- .../src/System/Formats/Nrbf/NrbfDecoder.cs | 15 +- .../Formats/Nrbf/SerializationRecord.cs | 7 - .../src/System/IO/Hashing/Crc32.cs | 5 +- .../src/System/IO/Hashing/Crc64.cs | 5 +- .../Hashing/NonCryptographicHashAlgorithm.cs | 15 +- .../src/System/IO/Hashing/XxHash128.cs | 7 - .../src/System/IO/Hashing/XxHash3.cs | 7 - .../src/System/IO/Hashing/XxHash32.cs | 10 +- .../src/System/IO/Hashing/XxHash64.cs | 10 +- .../src/System/IO/Packaging/ContentType.cs | 5 +- .../InternalRelationshipCollection.cs | 10 +- .../src/System/IO/Packaging/PackUriHelper.cs | 50 +---- .../src/System/IO/Packaging/Package.cs | 10 +- .../src/System/IO/Packaging/PackagePart.cs | 10 +- .../IO/Packaging/PackageRelationship.cs | 20 +- .../Packaging/PackageRelationshipSelector.cs | 15 +- .../IO/Packaging/ZipPackagePartPiece.cs | 11 +- .../src/System.Linq.AsyncEnumerable.csproj | 6 +- .../src/System/Linq/AggregateAsync.cs | 28 +-- .../src/System/Linq/AggregateBy.cs | 28 +-- .../src/System/Linq/AllAsync.cs | 8 +- .../src/System/Linq/AnyAsync.cs | 10 +- .../src/System/Linq/Append.cs | 2 +- .../src/System/Linq/AverageAsync.cs | 20 +- .../src/System/Linq/Cast.cs | 2 +- .../src/System/Linq/Chunk.cs | 2 +- .../src/System/Linq/Concat.cs | 4 +- .../src/System/Linq/ContainsAsync.cs | 2 +- .../src/System/Linq/CountAsync.cs | 20 +- .../src/System/Linq/CountBy.cs | 8 +- .../src/System/Linq/DefaultIfEmpty.cs | 2 +- .../src/System/Linq/Distinct.cs | 2 +- .../src/System/Linq/DistinctBy.cs | 8 +- .../src/System/Linq/ElementAtAsync.cs | 8 +- .../src/System/Linq/Empty.cs | 4 +- .../src/System/Linq/Except.cs | 4 +- .../src/System/Linq/ExceptBy.cs | 12 +- .../src/System/Linq/FirstAsync.cs | 20 +- .../src/System/Linq/GroupBy.cs | 48 ++--- .../src/System/Linq/GroupJoin.cs | 20 +- .../src/System/Linq/Index.cs | 2 +- .../src/System/Linq/Intersect.cs | 4 +- .../src/System/Linq/IntersectBy.cs | 12 +- .../src/System/Linq/Join.cs | 20 +- .../src/System/Linq/LastAsync.cs | 20 +- .../src/System/Linq/LeftJoin.cs | 20 +- .../src/System/Linq/MaxAsync.cs | 2 +- .../src/System/Linq/MaxByAsync.cs | 8 +- .../src/System/Linq/MinAsync.cs | 2 +- .../src/System/Linq/MinByAsync.cs | 8 +- .../src/System/Linq/OfType.cs | 2 +- .../src/System/Linq/OrderBy.cs | 24 +-- .../src/System/Linq/Prepend.cs | 2 +- .../src/System/Linq/Reverse.cs | 2 +- .../src/System/Linq/RightJoin.cs | 20 +- .../src/System/Linq/Select.cs | 16 +- .../src/System/Linq/SelectMany.cs | 66 +++---- .../src/System/Linq/SequenceEqualAsync.cs | 4 +- .../src/System/Linq/Shuffle.cs | 2 +- .../src/System/Linq/SingleAsync.cs | 20 +- .../src/System/Linq/Skip.cs | 2 +- .../src/System/Linq/SkipLast.cs | 2 +- .../src/System/Linq/SkipWhile.cs | 16 +- .../src/System/Linq/SumAsync.cs | 20 +- .../src/System/Linq/Take.cs | 4 +- .../src/System/Linq/TakeLast.cs | 2 +- .../src/System/Linq/TakeWhile.cs | 16 +- .../src/System/Linq/ThrowHelper.cs | 11 -- .../src/System/Linq/ToArrayAsync.cs | 2 +- .../src/System/Linq/ToAsyncEnumerable.cs | 2 +- .../src/System/Linq/ToDictionaryAsync.cs | 22 +-- .../src/System/Linq/ToHashSetAsync.cs | 2 +- .../src/System/Linq/ToListAsync.cs | 2 +- .../src/System/Linq/ToLookupAsync.cs | 22 +-- .../src/System/Linq/Union.cs | 4 +- .../src/System/Linq/UnionBy.cs | 12 +- .../src/System/Linq/Where.cs | 16 +- .../src/System/Linq/Zip.cs | 22 +-- .../tests/ILReader/ILReader.cs | 3 +- .../src/System/Management/ManagementPath.cs | 5 +- .../src/System/Management/ManagementQuery.cs | 5 +- .../src/System/Management/ManagementScope.cs | 5 +- .../src/System/BinaryData.cs | 25 +-- .../src/System.Net.Http.Json.csproj | 2 - ...lientJsonExtensions.Get.AsyncEnumerable.cs | 5 +- .../Json/HttpClientJsonExtensions.Patch.cs | 20 +- .../Json/HttpClientJsonExtensions.Post.cs | 20 +- .../Http/Json/HttpClientJsonExtensions.Put.cs | 20 +- .../Net/Http/Json/HttpClientJsonExtensions.cs | 5 +- ...tpContentJsonExtensions.AsyncEnumerable.cs | 10 +- .../Http/Json/HttpContentJsonExtensions.cs | 20 +- .../src/System/Net/Http/Json/JsonContent.cs | 6 +- .../src/System/Net/Http/WinHttpHandler.cs | 5 +- .../System/Net/Http/WinHttpRequestStream.cs | 5 +- .../System/Net/Http/WinHttpResponseStream.cs | 5 +- .../BrowserHttpHandler/BrowserHttpHandler.cs | 2 +- .../src/System/Net/Sockets/Socket.Tasks.cs | 2 +- .../src/System/Net/Sockets/Socket.cs | 2 +- .../Generic/ICollectionDebugView.cs | 7 - .../ObjectModel/CollectionHelpers.cs | 5 +- .../Numerics/TotalOrderIeee754Comparer.cs | 2 +- .../System/Reflection/ConstructorInvoker.cs | 2 +- .../src/System/Reflection/MethodInvoker.cs | 2 +- .../Reflection/NullabilityInfoContext.cs | 31 +--- .../src/System/Resources/ResourceReader.cs | 5 +- .../System/Resources/RuntimeResourceSet.cs | 10 +- .../Context/CustomReflectionContext.cs | 15 +- .../Context/Virtual/VirtualParameter.cs | 10 +- .../Context/Virtual/VirtualPropertyBase.cs | 3 +- .../Reflection/Emit/MethodBuilderImpl.cs | 2 +- .../Ecma335/Encoding/InstructionEncoder.cs | 5 +- .../Encoding/MethodBodyStreamEncoder.cs | 5 +- .../Metadata/MetadataStringComparer.cs | 20 +- .../src/System/Reflection/Throw.cs | 12 -- .../src/System/Reflection/DefaultBinder.cs | 10 +- .../Reflection/MetadataLoadContext.Apis.cs | 18 +- .../System/Reflection/PathAssemblyResolver.cs | 3 +- .../Ecma/EcmaAssembly.ManifestResources.cs | 6 +- .../Assemblies/RoAssembly.Modules.cs | 10 +- .../TypeLoading/Assemblies/RoAssembly.cs | 5 +- .../Reflection/TypeLoading/General/Helpers.cs | 3 +- .../TypeLoading/Methods/RoDefinitionMethod.cs | 3 +- .../RuntimeTypeInfo.BindingFlags.cs | 5 +- .../TypeLoading/RuntimeTypeInfo.GetMember.cs | 10 +- .../TypeLoading/Types/RoDefinitionType.cs | 3 +- .../TypeLoading/Types/RoType.GetInterface.cs | 5 +- .../Extensions/PreserializedResourceWriter.cs | 55 ++---- .../Caching/CacheEntryRemovedArguments.cs | 10 +- .../Caching/CacheEntryUpdateArguments.cs | 10 +- .../System/Runtime/Caching/ChangeMonitor.cs | 5 +- .../Caching/FileChangeNotificationSystem.cs | 20 +- .../Runtime/Caching/HostFileChangeMonitor.cs | 5 +- .../src/System/Runtime/Caching/MemoryCache.cs | 65 ++----- .../Runtime/Caching/MemoryCacheEntry.cs | 5 +- .../src/System/Runtime/Caching/ObjectCache.cs | 5 +- .../tests/BinaryFormatterTests.cs | 5 +- .../System.Runtime.Tests.csproj | 1 - .../CESchedulerPairTests.cs | 3 +- .../Cryptography/Cose/CoseHeaderLabel.cs | 5 +- .../Cryptography/Cose/CoseHeaderValue.cs | 15 +- .../Security/Cryptography/Cose/CoseMessage.cs | 6 +- .../Cryptography/Cose/CoseMultiSignMessage.cs | 52 ++---- .../Cryptography/Cose/CoseSign1Message.cs | 82 ++------ .../Cryptography/Cose/CoseSignature.cs | 45 +---- .../Security/Cryptography/Cose/CoseSigner.cs | 10 +- .../Cryptography/Pkcs/CmsRecipient.cs | 15 +- .../Pkcs/CmsRecipientCollection.cs | 20 +- .../Security/Cryptography/Pkcs/ContentInfo.cs | 15 +- .../Cryptography/Pkcs/EnvelopedCms.cs | 50 +---- .../Pkcs/RecipientInfoCollection.cs | 10 +- .../Pkcs/Rfc3161TimestampRequest.cs | 5 +- .../Pkcs/Rfc3161TimestampToken.cs | 10 +- .../Pkcs/Rfc3161TimestampTokenInfo.cs | 10 +- .../Security/Cryptography/Pkcs/SignedCms.cs | 20 +- .../Security/Cryptography/Pkcs/SignerInfo.cs | 10 +- .../Cryptography/Pkcs/SignerInfoCollection.cs | 5 +- .../Security/Cryptography/ProtectedData.cs | 6 +- .../Security/Cryptography/Xml/CanonicalXml.cs | 15 +- .../Xml/CanonicalizationDispatcher.cs | 10 +- .../Security/Cryptography/Xml/CipherData.cs | 5 +- .../Cryptography/Xml/CipherReference.cs | 5 +- .../Security/Cryptography/Xml/DSAKeyValue.cs | 15 +- .../Security/Cryptography/Xml/DataObject.cs | 10 +- .../Cryptography/Xml/EncryptedData.cs | 5 +- .../Security/Cryptography/Xml/EncryptedKey.cs | 5 +- .../Cryptography/Xml/EncryptedReference.cs | 5 +- .../Security/Cryptography/Xml/EncryptedXml.cs | 140 +++----------- .../Cryptography/Xml/EncryptionMethod.cs | 5 +- .../Cryptography/Xml/EncryptionProperty.cs | 10 +- .../Cryptography/Xml/ExcCanonicalXml.cs | 15 +- .../Security/Cryptography/Xml/KeyInfo.cs | 5 +- .../Security/Cryptography/Xml/KeyInfoName.cs | 5 +- .../Xml/KeyInfoRetrievalMethod.cs | 5 +- .../Cryptography/Xml/KeyInfoX509Data.cs | 15 +- .../Security/Cryptography/Xml/RSAKeyValue.cs | 15 +- .../Security/Cryptography/Xml/Reference.cs | 10 +- .../Cryptography/Xml/ReferenceList.cs | 10 +- .../Security/Cryptography/Xml/Signature.cs | 5 +- .../Security/Cryptography/Xml/SignedInfo.cs | 10 +- .../Security/Cryptography/Xml/SignedXml.cs | 30 +-- .../Cryptography/Xml/TransformChain.cs | 5 +- .../System/Security/Cryptography/Xml/Utils.cs | 20 +- .../Xml/XmlDecryptionTransform.cs | 10 +- .../Xml/XmlDsigEnvelopedSignatureTransform.cs | 10 +- .../Cryptography/ECDiffieHellmanCng.cs | 2 +- .../X509CertificateLoader.netcore.cs | 2 +- .../Permissions/PrincipalPermission.cs | 5 +- .../Syndication/Atom10FeedFormatter.cs | 45 +---- .../Syndication/Atom10ItemFormatter.cs | 25 +-- .../AtomPub10CategoriesDocumentFormatter.cs | 35 +--- .../AtomPub10ServiceDocumentFormatter.cs | 30 +-- .../CategoriesDocumentFormatter.cs | 5 +- .../ExtensibleSyndicationObject.cs | 15 +- .../Syndication/NullNotAllowedCollection.cs | 10 +- .../ReferencedCategoriesDocument.cs | 5 +- .../Syndication/ResourceCollectionInfo.cs | 10 +- .../Syndication/Rss20FeedFormatter.cs | 45 +---- .../Syndication/Rss20ItemFormatter.cs | 25 +-- .../Syndication/ServiceDocumentFormatter.cs | 125 +++---------- .../Syndication/SyndicationCategory.cs | 5 +- .../Syndication/SyndicationContent.cs | 10 +- .../SyndicationElementExtension.cs | 30 +-- .../SyndicationElementExtensionCollection.cs | 35 +--- .../Syndication/SyndicationFeed.cs | 10 +- .../Syndication/SyndicationFeedFormatter.cs | 175 ++++-------------- .../Syndication/SyndicationItem.cs | 15 +- .../Syndication/SyndicationItemFormatter.cs | 10 +- .../Syndication/SyndicationLink.cs | 5 +- .../Syndication/SyndicationPerson.cs | 5 +- .../Syndication/UrlSyndicationContent.cs | 5 +- .../Syndication/XmlSyndicationContent.cs | 15 +- .../ServiceProcess/ServiceController.cs | 5 +- .../System.Speech/src/Internal/Helpers.cs | 9 - .../Internal/SrgsCompiler/GrammarElement.cs | 2 +- .../src/Internal/Synthesis/VoiceSynthesis.cs | 6 +- .../System.Speech/src/Recognition/Choices.cs | 10 +- .../System.Speech/src/Recognition/Grammar.cs | 10 +- .../src/Recognition/GrammarBuilder.cs | 37 ++-- .../src/Recognition/RecognizerBase.cs | 6 +- .../src/Recognition/SemanticResultKey.cs | 4 +- .../src/Recognition/SemanticResultValue.cs | 8 +- .../Recognition/SpeechRecognitionEngine.cs | 24 +-- .../src/Recognition/SpeechRecognizer.cs | 16 +- .../System.Speech/src/Recognition/SpeechUI.cs | 2 +- .../Recognition/SrgsGrammar/SrgsDocument.cs | 10 +- .../SrgsGrammar/SrgsElementList.cs | 2 +- .../Recognition/SrgsGrammar/SrgsGrammar.cs | 2 +- .../SrgsGrammar/SrgsGrammarCompiler.cs | 16 +- .../src/Recognition/SrgsGrammar/SrgsItem.cs | 4 +- .../Recognition/SrgsGrammar/SrgsItemList.cs | 2 +- .../SrgsGrammar/SrgsNameValueTag.cs | 4 +- .../src/Recognition/SrgsGrammar/SrgsOneOf.cs | 6 +- .../src/Recognition/SrgsGrammar/SrgsRule.cs | 4 +- .../Recognition/SrgsGrammar/SrgsRuleRef.cs | 4 +- .../SrgsGrammar/SrgsRulesCollection.cs | 2 +- .../SrgsSemanticInterpretationTag.cs | 4 +- .../src/Recognition/SrgsGrammar/SrgsText.cs | 4 +- .../src/Result/RecognitionResult.cs | 6 +- .../src/Result/RecognizedAudio.cs | 4 +- .../System.Speech/src/Result/SemanticValue.cs | 2 +- .../System.Speech/src/Synthesis/Prompt.cs | 6 +- .../src/Synthesis/PromptBuilder.cs | 39 ++-- .../src/Synthesis/SpeechSynthesizer.cs | 60 +++--- .../src/Synthesis/TTSEngine/TTSEngineTypes.cs | 8 +- .../System.Speech/src/Synthesis/VoiceInfo.cs | 2 +- .../src/System/Text/DecoderNLS.cs | 17 +- .../src/System/Text/EncoderNLS.cs | 17 +- .../src/System/Text/EncodingNLS.cs | 33 +--- .../Common/JsonSeparatorNamingPolicy.cs | 5 +- .../src/System.Text.Json.csproj | 1 - .../Text/Json/Document/JsonDocument.Parse.cs | 15 +- .../System/Text/Json/Document/JsonDocument.cs | 5 +- .../System/Text/Json/Document/JsonElement.cs | 15 +- .../System/Text/Json/Document/JsonProperty.cs | 5 +- .../src/System/Text/Json/JsonEncodedText.cs | 5 +- .../System/Text/Json/Nodes/JsonArray.IList.cs | 5 +- .../src/System/Text/Json/Nodes/JsonArray.cs | 5 +- .../System/Text/Json/Nodes/JsonNode.Parse.cs | 15 +- .../Text/Json/Nodes/JsonObject.IDictionary.cs | 20 +- .../Text/Json/Nodes/JsonObject.IList.cs | 15 +- .../src/System/Text/Json/Nodes/JsonObject.cs | 20 +- .../src/System/Text/Json/Nodes/JsonValue.cs | 5 +- .../Text/Json/Nodes/JsonValueOfElement.cs | 5 +- .../Text/Json/Nodes/JsonValueOfTCustomized.cs | 5 +- .../Text/Json/Nodes/JsonValueOfTPrimitive.cs | 5 +- .../Text/Json/Schema/JsonSchemaExporter.cs | 16 +- .../Json/Serialization/ConfigurationList.cs | 15 +- .../Converters/Object/ObjectConverter.cs | 5 +- .../Value/JsonPrimitiveConverter.cs | 5 +- .../Converters/Value/StringConverter.cs | 5 +- .../Converters/Value/UriConverter.cs | 5 +- .../Converters/Value/VersionConverter.cs | 5 +- .../Json/Serialization/JsonConverterOfT.cs | 5 +- .../JsonResumableConverterOfT.cs | 10 +- .../Serialization/JsonSerializer.Helpers.cs | 5 +- .../JsonSerializer.Read.Document.cs | 50 +---- .../JsonSerializer.Read.Element.cs | 25 +-- .../Serialization/JsonSerializer.Read.Node.cs | 25 +-- .../Serialization/JsonSerializer.Read.Span.cs | 25 +-- .../JsonSerializer.Read.Stream.cs | 116 +++--------- .../JsonSerializer.Read.String.cs | 75 ++------ .../JsonSerializer.Read.Utf8JsonReader.cs | 25 +-- .../JsonSerializer.Write.ByteArray.cs | 15 +- .../JsonSerializer.Write.Document.cs | 15 +- .../JsonSerializer.Write.Element.cs | 15 +- .../JsonSerializer.Write.Node.cs | 15 +- .../JsonSerializer.Write.Pipe.cs | 42 +---- .../JsonSerializer.Write.Stream.cs | 80 ++------ .../JsonSerializer.Write.String.cs | 15 +- .../JsonSerializer.Write.Utf8JsonWriter.cs | 40 +--- .../JsonSerializerOptions.Caching.cs | 10 +- .../JsonSerializerOptions.Converters.cs | 5 +- .../Serialization/JsonSerializerOptions.cs | 5 +- .../Metadata/DefaultJsonTypeInfoResolver.cs | 11 +- .../JsonMetadataServices.Collections.cs | 15 +- .../JsonMetadataServices.Converters.cs | 15 +- .../Metadata/JsonMetadataServices.Helpers.cs | 5 +- .../Metadata/JsonMetadataServices.cs | 30 +-- .../Metadata/JsonPropertyInfo.cs | 5 +- .../Serialization/Metadata/JsonTypeInfo.cs | 27 +-- .../Metadata/JsonTypeInfoResolver.cs | 15 +- .../Utf8JsonWriter.WriteProperties.Bytes.cs | 5 +- ...Utf8JsonWriter.WriteProperties.DateTime.cs | 5 +- ...onWriter.WriteProperties.DateTimeOffset.cs | 5 +- .../Utf8JsonWriter.WriteProperties.Decimal.cs | 5 +- .../Utf8JsonWriter.WriteProperties.Double.cs | 5 +- .../Utf8JsonWriter.WriteProperties.Float.cs | 5 +- .../Utf8JsonWriter.WriteProperties.Guid.cs | 5 +- .../Utf8JsonWriter.WriteProperties.Literal.cs | 10 +- ...JsonWriter.WriteProperties.SignedNumber.cs | 10 +- .../Utf8JsonWriter.WriteProperties.String.cs | 25 +-- ...onWriter.WriteProperties.UnsignedNumber.cs | 10 +- .../Utf8JsonWriter.WriteValues.Comment.cs | 5 +- .../Writer/Utf8JsonWriter.WriteValues.Raw.cs | 5 +- .../System/Text/Json/Writer/Utf8JsonWriter.cs | 20 +- .../src/System/Threading/Channels/Channel.cs | 10 +- .../RateLimiting/ConcurrencyLimiter.cs | 5 +- .../RateLimiting/FixedWindowRateLimiter.cs | 5 +- .../RateLimiting/PartitionedRateLimiter.cs | 5 +- .../Threading/RateLimiting/RateLimiter.cs | 5 +- .../RateLimiting/SlidingWindowRateLimiter.cs | 5 +- .../RateLimiting/TokenBucketRateLimiter.cs | 5 +- .../Base/DataflowBlock.IAsyncEnumerable.cs | 5 +- .../src/Base/DataflowBlock.cs | 150 +++------------ .../src/Blocks/ActionBlock.cs | 15 +- .../src/Blocks/BatchBlock.cs | 5 +- .../src/Blocks/BatchedJoinBlock.cs | 15 +- .../src/Blocks/BroadcastBlock.cs | 20 +- .../src/Blocks/BufferBlock.cs | 10 +- .../src/Blocks/JoinBlock.cs | 25 +-- .../src/Blocks/TransformBlock.cs | 10 +- .../TransformManyBlock.IAsyncEnumerable.cs | 5 +- .../src/Blocks/TransformManyBlock.cs | 5 +- .../src/Blocks/WriteOnceBlock.cs | 20 +- .../src/Internal/SourceCore.cs | 10 +- .../System/Transactions/TransactionInterop.cs | 2 +- .../Linker.Steps/ProcessLinkerXmlBase.cs | 8 +- .../illink/src/linker/Linker/LinkContext.cs | 4 +- 659 files changed, 2517 insertions(+), 6229 deletions(-) create mode 100644 src/libraries/Common/src/System/ExceptionPolyfills.cs delete mode 100644 src/libraries/Common/src/System/ThrowHelper.cs delete mode 100644 src/libraries/Microsoft.Extensions.Configuration.Binder/src/Properties/InternalsVisibleTo.cs diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/MethodInvoker.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/MethodInvoker.cs index 661f7f28535280..bf8331776d7a32 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/MethodInvoker.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/MethodInvoker.cs @@ -29,7 +29,7 @@ internal MethodInvoker(RuntimeConstructorInfo constructor) public static MethodInvoker Create(MethodBase method) { - ArgumentNullException.ThrowIfNull(method, nameof(method)); + ArgumentNullException.ThrowIfNull(method); if (method is RuntimeMethodInfo rmi) { diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.NativeAot.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.NativeAot.cs index f354e92fcd9aca..18e7c9a9596dfe 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.NativeAot.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.NativeAot.cs @@ -90,7 +90,7 @@ internal static unsafe void PtrToStructureImpl(IntPtr ptr, object structure) public static unsafe void DestroyStructure(IntPtr ptr, Type structuretype) { ArgumentNullException.ThrowIfNull(ptr); - ArgumentNullException.ThrowIfNull(structuretype, nameof(structuretype)); + ArgumentNullException.ThrowIfNull(structuretype); RuntimeTypeHandle structureTypeHandle = structuretype.TypeHandle; diff --git a/src/libraries/Common/src/Extensions/NonCapturingTimer/NonCapturingTimer.cs b/src/libraries/Common/src/Extensions/NonCapturingTimer/NonCapturingTimer.cs index 45d5bb2a694a54..15f6624e6a4e4f 100644 --- a/src/libraries/Common/src/Extensions/NonCapturingTimer/NonCapturingTimer.cs +++ b/src/libraries/Common/src/Extensions/NonCapturingTimer/NonCapturingTimer.cs @@ -13,10 +13,7 @@ internal static class NonCapturingTimer { public static Timer Create(TimerCallback callback, object state, TimeSpan dueTime, TimeSpan period) { - if (callback is null) - { - throw new ArgumentNullException(nameof(callback)); - } + ArgumentNullException.ThrowIfNull(callback); // Don't capture the current ExecutionContext and its AsyncLocals onto the timer bool restoreFlow = false; diff --git a/src/libraries/Common/src/System/CodeDom/CodeTypeReference.cs b/src/libraries/Common/src/System/CodeDom/CodeTypeReference.cs index cb75ff887f6871..347b233a0d97f7 100644 --- a/src/libraries/Common/src/System/CodeDom/CodeTypeReference.cs +++ b/src/libraries/Common/src/System/CodeDom/CodeTypeReference.cs @@ -42,14 +42,7 @@ public CodeTypeReference() public CodeTypeReference(Type type) { -#if NET ArgumentNullException.ThrowIfNull(type); -#else - if (type is null) - { - throw new ArgumentNullException(nameof(type)); - } -#endif if (type.IsArray) { diff --git a/src/libraries/Common/src/System/CodeDom/CodeTypeReferenceCollection.cs b/src/libraries/Common/src/System/CodeDom/CodeTypeReferenceCollection.cs index 55119bc720664b..d632a5f5c7f068 100644 --- a/src/libraries/Common/src/System/CodeDom/CodeTypeReferenceCollection.cs +++ b/src/libraries/Common/src/System/CodeDom/CodeTypeReferenceCollection.cs @@ -41,14 +41,7 @@ public CodeTypeReference this[int index] public void AddRange(CodeTypeReference[] value) { -#if NET ArgumentNullException.ThrowIfNull(value); -#else - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } -#endif for (int i = 0; i < value.Length; i++) { @@ -58,14 +51,7 @@ public void AddRange(CodeTypeReference[] value) public void AddRange(CodeTypeReferenceCollection value) { -#if NET ArgumentNullException.ThrowIfNull(value); -#else - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } -#endif int currentCount = value.Count; for (int i = 0; i < currentCount; i++) diff --git a/src/libraries/Common/src/System/Composition/Diagnostics/CompositionTrace.cs b/src/libraries/Common/src/System/Composition/Diagnostics/CompositionTrace.cs index 2049ff60f36aad..31cce3c597f1e5 100644 --- a/src/libraries/Common/src/System/Composition/Diagnostics/CompositionTrace.cs +++ b/src/libraries/Common/src/System/Composition/Diagnostics/CompositionTrace.cs @@ -35,14 +35,8 @@ public static void Registration_TypeExportConventionOverridden(Type type) public static void Registration_MemberExportConventionOverridden(Type type, MemberInfo member) { - if (type is null) - { - throw new ArgumentNullException(nameof(type)); - } - if (member is null) - { - throw new ArgumentNullException(nameof(member)); - } + ArgumentNullException.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(member); if (CompositionTraceSource.CanWriteWarning) { @@ -54,14 +48,8 @@ public static void Registration_MemberExportConventionOverridden(Type type, Memb public static void Registration_MemberImportConventionOverridden(Type type, MemberInfo member) { - if (type is null) - { - throw new ArgumentNullException(nameof(type)); - } - if (member is null) - { - throw new ArgumentNullException(nameof(member)); - } + ArgumentNullException.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(member); if (CompositionTraceSource.CanWriteWarning) { @@ -73,14 +61,8 @@ public static void Registration_MemberImportConventionOverridden(Type type, Memb public static void Registration_OnSatisfiedImportNotificationOverridden(Type type, MemberInfo member) { - if (type is null) - { - throw new ArgumentNullException(nameof(type)); - } - if (member is null) - { - throw new ArgumentNullException(nameof(member)); - } + ArgumentNullException.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(member); if (CompositionTraceSource.CanWriteWarning) { @@ -92,10 +74,7 @@ public static void Registration_OnSatisfiedImportNotificationOverridden(Type typ public static void Registration_PartCreationConventionOverridden(Type type) { - if (type is null) - { - throw new ArgumentNullException(nameof(type)); - } + ArgumentNullException.ThrowIfNull(type); if (CompositionTraceSource.CanWriteWarning) { @@ -107,14 +86,8 @@ public static void Registration_PartCreationConventionOverridden(Type type) public static void Registration_MemberImportConventionMatchedTwice(Type type, MemberInfo member) { - if (type is null) - { - throw new ArgumentNullException(nameof(type)); - } - if (member is null) - { - throw new ArgumentNullException(nameof(member)); - } + ArgumentNullException.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(member); if (CompositionTraceSource.CanWriteWarning) { @@ -126,10 +99,7 @@ public static void Registration_MemberImportConventionMatchedTwice(Type type, Me public static void Registration_PartMetadataConventionOverridden(Type type) { - if (type is null) - { - throw new ArgumentNullException(nameof(type)); - } + ArgumentNullException.ThrowIfNull(type); if (CompositionTraceSource.CanWriteWarning) { @@ -141,14 +111,8 @@ public static void Registration_PartMetadataConventionOverridden(Type type) public static void Registration_ParameterImportConventionOverridden(ParameterInfo parameter, ConstructorInfo constructor) { - if (parameter is null) - { - throw new ArgumentNullException(nameof(parameter)); - } - if (constructor is null) - { - throw new ArgumentNullException(nameof(constructor)); - } + ArgumentNullException.ThrowIfNull(parameter); + ArgumentNullException.ThrowIfNull(constructor); if (CompositionTraceSource.CanWriteWarning) { diff --git a/src/libraries/Common/src/System/ExceptionPolyfills.cs b/src/libraries/Common/src/System/ExceptionPolyfills.cs new file mode 100644 index 00000000000000..50095d901f6728 --- /dev/null +++ b/src/libraries/Common/src/System/ExceptionPolyfills.cs @@ -0,0 +1,27 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; + +namespace System +{ + /// Provides downlevel polyfills for static methods on Exception-derived types. + internal static class ExceptionPolyfills + { + extension(ArgumentNullException) + { + public static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression(nameof(argument))] string? paramName = null) + { + if (argument is null) + { + ThrowArgumentNullException(paramName); + } + } + } + + [DoesNotReturn] + private static void ThrowArgumentNullException(string? paramName) => + throw new ArgumentNullException(paramName); + } +} diff --git a/src/libraries/Common/src/System/IO/ReadOnlyMemoryStream.cs b/src/libraries/Common/src/System/IO/ReadOnlyMemoryStream.cs index 8bc8320478e187..d8863db558c1a8 100644 --- a/src/libraries/Common/src/System/IO/ReadOnlyMemoryStream.cs +++ b/src/libraries/Common/src/System/IO/ReadOnlyMemoryStream.cs @@ -198,10 +198,7 @@ protected override void Dispose(bool disposing) #if NETFRAMEWORK || NETSTANDARD2_0 private static void ValidateBufferArguments(byte[] buffer, int offset, int count) { - if (buffer is null) - { - throw new ArgumentNullException(nameof(buffer)); - } + ArgumentNullException.ThrowIfNull(buffer); if (offset < 0) { diff --git a/src/libraries/Common/src/System/IO/StreamHelpers.CopyValidation.cs b/src/libraries/Common/src/System/IO/StreamHelpers.CopyValidation.cs index 835048efb1626f..95dd7c16fb8be0 100644 --- a/src/libraries/Common/src/System/IO/StreamHelpers.CopyValidation.cs +++ b/src/libraries/Common/src/System/IO/StreamHelpers.CopyValidation.cs @@ -9,10 +9,7 @@ internal static partial class StreamHelpers /// Validate the arguments to CopyTo, as would Stream.CopyTo. public static void ValidateCopyToArgs(Stream source, Stream destination, int bufferSize) { - if (destination is null) - { - throw new ArgumentNullException(nameof(destination)); - } + ArgumentNullException.ThrowIfNull(destination); if (bufferSize <= 0) { diff --git a/src/libraries/Common/src/System/Resources/ResourceWriter.cs b/src/libraries/Common/src/System/Resources/ResourceWriter.cs index 81a70e7ae2f521..8515cdcb565535 100644 --- a/src/libraries/Common/src/System/Resources/ResourceWriter.cs +++ b/src/libraries/Common/src/System/Resources/ResourceWriter.cs @@ -48,10 +48,7 @@ public sealed partial class ResourceWriter(string fileName) #endif { - if (fileName is null) - { - throw new ArgumentNullException(nameof(fileName)); - } + ArgumentNullException.ThrowIfNull(fileName); _output = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None); _resourceList = new SortedDictionary(FastResourceComparer.Default); @@ -65,10 +62,7 @@ public sealed partial class ResourceWriter(Stream stream) #endif { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } + ArgumentNullException.ThrowIfNull(stream); if (!stream.CanWrite) { @@ -85,10 +79,7 @@ public sealed partial class // public void AddResource(string name, string? value) { - if (name is null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); if (_resourceList == null) { @@ -105,10 +96,7 @@ public void AddResource(string name, string? value) // public void AddResource(string name, object? value) { - if (name is null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); if (_resourceList == null) { @@ -134,10 +122,7 @@ public void AddResource(string name, object? value) // public void AddResource(string name, Stream? value, bool closeAfterWrite = false) { - if (name is null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); if (_resourceList == null) { @@ -174,10 +159,7 @@ private void AddResourceInternal(string name, Stream? value, bool closeAfterWrit // public void AddResource(string name, byte[]? value) { - if (name is null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); if (_resourceList == null) { diff --git a/src/libraries/Common/src/System/Security/Cryptography/AesGcm.cs b/src/libraries/Common/src/System/Security/Cryptography/AesGcm.cs index c29307afd1aef4..6728fb1fa088ea 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/AesGcm.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/AesGcm.cs @@ -156,24 +156,10 @@ private partial void EncryptCore( /// The encryption operation failed. public void Encrypt(byte[] nonce, byte[] plaintext, byte[] ciphertext, byte[] tag, byte[]? associatedData = null) { -#if NET ArgumentNullException.ThrowIfNull(nonce); ArgumentNullException.ThrowIfNull(plaintext); ArgumentNullException.ThrowIfNull(ciphertext); ArgumentNullException.ThrowIfNull(tag); -#else - if (nonce is null) - throw new ArgumentNullException(nameof(nonce)); - - if (plaintext is null) - throw new ArgumentNullException(nameof(plaintext)); - - if (ciphertext is null) - throw new ArgumentNullException(nameof(ciphertext)); - - if (tag is null) - throw new ArgumentNullException(nameof(tag)); -#endif Encrypt((ReadOnlySpan)nonce, plaintext, ciphertext, tag, associatedData); } @@ -249,24 +235,10 @@ public void Encrypt( /// The tag value could not be verified. public void Decrypt(byte[] nonce, byte[] ciphertext, byte[] tag, byte[] plaintext, byte[]? associatedData = null) { -#if NET ArgumentNullException.ThrowIfNull(nonce); ArgumentNullException.ThrowIfNull(ciphertext); ArgumentNullException.ThrowIfNull(tag); ArgumentNullException.ThrowIfNull(plaintext); -#else - if (nonce is null) - throw new ArgumentNullException(nameof(nonce)); - - if (ciphertext is null) - throw new ArgumentNullException(nameof(ciphertext)); - - if (tag is null) - throw new ArgumentNullException(nameof(tag)); - - if (plaintext is null) - throw new ArgumentNullException(nameof(plaintext)); -#endif Decrypt((ReadOnlySpan)nonce, ciphertext, tag, plaintext, associatedData); } diff --git a/src/libraries/Common/src/System/Security/Cryptography/Asn1/AttributeAsn.manual.cs b/src/libraries/Common/src/System/Security/Cryptography/Asn1/AttributeAsn.manual.cs index da7c9d3d8d0d80..acf03c1a82b8cc 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/Asn1/AttributeAsn.manual.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/Asn1/AttributeAsn.manual.cs @@ -1,20 +1,18 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#pragma warning disable CA1510 + namespace System.Security.Cryptography.Asn1 { internal partial struct AttributeAsn { public AttributeAsn(AsnEncodedData attribute) { -#if NET - ArgumentNullException.ThrowIfNull(attribute); -#else if (attribute is null) { throw new ArgumentNullException(nameof(attribute)); } -#endif AttrType = attribute.Oid!.Value!; AttrValues = new[] { new ReadOnlyMemory(attribute.RawData) }; diff --git a/src/libraries/Common/src/System/Security/Cryptography/Asn1/X509ExtensionAsn.manual.cs b/src/libraries/Common/src/System/Security/Cryptography/Asn1/X509ExtensionAsn.manual.cs index 543656905c4f7c..09594e98d228cd 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/Asn1/X509ExtensionAsn.manual.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/Asn1/X509ExtensionAsn.manual.cs @@ -9,14 +9,7 @@ internal partial struct X509ExtensionAsn { public X509ExtensionAsn(X509Extension extension) { -#if NET ArgumentNullException.ThrowIfNull(extension); -#else - if (extension is null) - { - throw new ArgumentNullException(nameof(extension)); - } -#endif ExtnId = extension.Oid!.Value!; Critical = extension.Critical; diff --git a/src/libraries/Common/src/System/Security/Cryptography/CryptographicAttributeObjectCollection.cs b/src/libraries/Common/src/System/Security/Cryptography/CryptographicAttributeObjectCollection.cs index 8868b30afbddd9..b26c3f00b667c5 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/CryptographicAttributeObjectCollection.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/CryptographicAttributeObjectCollection.cs @@ -31,20 +31,14 @@ public CryptographicAttributeObjectCollection(CryptographicAttributeObject attri public int Add(AsnEncodedData asnEncodedData) { - if (asnEncodedData is null) - { - throw new ArgumentNullException(nameof(asnEncodedData)); - } + ArgumentNullException.ThrowIfNull(asnEncodedData); return Add(new CryptographicAttributeObject(asnEncodedData.Oid!, new AsnEncodedDataCollection(asnEncodedData))); } public int Add(CryptographicAttributeObject attribute) { - if (attribute is null) - { - throw new ArgumentNullException(nameof(attribute)); - } + ArgumentNullException.ThrowIfNull(attribute); // // Merge with existing attribute, if already existed, else add as new. @@ -89,10 +83,7 @@ internal void AddWithoutMerge(CryptographicAttributeObject attribute) public void Remove(CryptographicAttributeObject attribute) { - if (attribute is null) - { - throw new ArgumentNullException(nameof(attribute)); - } + ArgumentNullException.ThrowIfNull(attribute); _list.Remove(attribute); } @@ -141,10 +132,7 @@ IEnumerator IEnumerable.GetEnumerator() void ICollection.CopyTo(Array array, int index) { - if (array is null) - { - throw new ArgumentNullException(nameof(array)); - } + ArgumentNullException.ThrowIfNull(array); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); @@ -162,10 +150,7 @@ void ICollection.CopyTo(Array array, int index) public void CopyTo(CryptographicAttributeObject[] array, int index) { - if (array is null) - { - throw new ArgumentNullException(nameof(array)); - } + ArgumentNullException.ThrowIfNull(array); if (index < 0 || index >= array.Length) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexMustBeLess); diff --git a/src/libraries/Common/src/System/Security/Cryptography/MLDsa.cs b/src/libraries/Common/src/System/Security/Cryptography/MLDsa.cs index 6909aee7755277..1b1972b3eb27b0 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/MLDsa.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/MLDsa.cs @@ -49,10 +49,7 @@ public abstract partial class MLDsa : IDisposable /// protected MLDsa(MLDsaAlgorithm algorithm) { - if (algorithm is null) - { - throw new ArgumentNullException(nameof(algorithm)); - } + ArgumentNullException.ThrowIfNull(algorithm); Algorithm = algorithm; } @@ -709,10 +706,7 @@ public int ExportMLDsaPrivateSeed(Span destination) /// public static MLDsa GenerateKey(MLDsaAlgorithm algorithm) { - if (algorithm is null) - { - throw new ArgumentNullException(nameof(algorithm)); - } + ArgumentNullException.ThrowIfNull(algorithm); ThrowIfNotSupported(); return MLDsaImplementation.GenerateKeyImpl(algorithm); @@ -1032,10 +1026,7 @@ public static MLDsa ImportFromEncryptedPem(ReadOnlySpan source, ReadOnlySp /// public static MLDsa ImportMLDsaPublicKey(MLDsaAlgorithm algorithm, ReadOnlySpan source) { - if (algorithm is null) - { - throw new ArgumentNullException(nameof(algorithm)); - } + ArgumentNullException.ThrowIfNull(algorithm); if (source.Length != algorithm.PublicKeySizeInBytes) { @@ -1073,10 +1064,7 @@ public static MLDsa ImportMLDsaPublicKey(MLDsaAlgorithm algorithm, ReadOnlySpan< /// public static MLDsa ImportMLDsaSecretKey(MLDsaAlgorithm algorithm, ReadOnlySpan source) { - if (algorithm is null) - { - throw new ArgumentNullException(nameof(algorithm)); - } + ArgumentNullException.ThrowIfNull(algorithm); if (source.Length != algorithm.SecretKeySizeInBytes) { @@ -1114,10 +1102,7 @@ public static MLDsa ImportMLDsaSecretKey(MLDsaAlgorithm algorithm, ReadOnlySpan< /// public static MLDsa ImportMLDsaPrivateSeed(MLDsaAlgorithm algorithm, ReadOnlySpan source) { - if (algorithm is null) - { - throw new ArgumentNullException(nameof(algorithm)); - } + ArgumentNullException.ThrowIfNull(algorithm); if (source.Length != algorithm.PrivateSeedSizeInBytes) { diff --git a/src/libraries/Common/src/System/Security/Cryptography/MLKem.cs b/src/libraries/Common/src/System/Security/Cryptography/MLKem.cs index efc74d3c0b338e..4d830326d9c3ce 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/MLKem.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/MLKem.cs @@ -60,7 +60,7 @@ public abstract class MLKem : IDisposable /// protected MLKem(MLKemAlgorithm algorithm) { - ThrowIfNull(algorithm); + ArgumentNullException.ThrowIfNull(algorithm); Algorithm = algorithm; } @@ -85,7 +85,7 @@ protected MLKem(MLKemAlgorithm algorithm) /// public static MLKem GenerateKey(MLKemAlgorithm algorithm) { - ThrowIfNull(algorithm); + ArgumentNullException.ThrowIfNull(algorithm); ThrowIfNotSupported(); return MLKemImplementation.GenerateKeyImpl(algorithm); } @@ -233,7 +233,7 @@ public void Decapsulate(ReadOnlySpan ciphertext, Span sharedSecret) /// The object has already been disposed. public byte[] Decapsulate(byte[] ciphertext) { - ThrowIfNull(ciphertext); + ArgumentNullException.ThrowIfNull(ciphertext); if (ciphertext.Length != Algorithm.CiphertextSizeInBytes) throw new ArgumentException(SR.Argument_KemInvalidCiphertextLength, nameof(ciphertext)); @@ -337,7 +337,7 @@ public byte[] ExportPrivateSeed() /// public static MLKem ImportPrivateSeed(MLKemAlgorithm algorithm, ReadOnlySpan source) { - ThrowIfNull(algorithm); + ArgumentNullException.ThrowIfNull(algorithm); if (source.Length != algorithm.PrivateSeedSizeInBytes) throw new ArgumentException(SR.Argument_KemInvalidSeedLength, nameof(source)); @@ -370,7 +370,7 @@ public static MLKem ImportPrivateSeed(MLKemAlgorithm algorithm, ReadOnlySpan public static MLKem ImportPrivateSeed(MLKemAlgorithm algorithm, byte[] source) { - ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return ImportPrivateSeed(algorithm, new ReadOnlySpan(source)); } @@ -396,7 +396,7 @@ public static MLKem ImportPrivateSeed(MLKemAlgorithm algorithm, byte[] source) /// public static MLKem ImportDecapsulationKey(MLKemAlgorithm algorithm, ReadOnlySpan source) { - ThrowIfNull(algorithm); + ArgumentNullException.ThrowIfNull(algorithm); if (source.Length != algorithm.DecapsulationKeySizeInBytes) throw new ArgumentException(SR.Argument_KemInvalidDecapsulationKeyLength, nameof(source)); @@ -428,7 +428,7 @@ public static MLKem ImportDecapsulationKey(MLKemAlgorithm algorithm, ReadOnlySpa /// public static MLKem ImportDecapsulationKey(MLKemAlgorithm algorithm, byte[] source) { - ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return ImportDecapsulationKey(algorithm, new ReadOnlySpan(source)); } @@ -453,7 +453,7 @@ public static MLKem ImportDecapsulationKey(MLKemAlgorithm algorithm, byte[] sour /// public static MLKem ImportEncapsulationKey(MLKemAlgorithm algorithm, ReadOnlySpan source) { - ThrowIfNull(algorithm); + ArgumentNullException.ThrowIfNull(algorithm); if (source.Length != algorithm.EncapsulationKeySizeInBytes) throw new ArgumentException(SR.Argument_KemInvalidEncapsulationKeyLength, nameof(source)); @@ -485,7 +485,7 @@ public static MLKem ImportEncapsulationKey(MLKemAlgorithm algorithm, ReadOnlySpa /// public static MLKem ImportEncapsulationKey(MLKemAlgorithm algorithm, byte[] source) { - ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return ImportEncapsulationKey(algorithm, new ReadOnlySpan(source)); } @@ -803,7 +803,7 @@ public bool TryExportEncryptedPkcs8PrivateKey( Span destination, out int bytesWritten) { - ThrowIfNull(pbeParameters); + ArgumentNullException.ThrowIfNull(pbeParameters); PasswordBasedEncryption.ValidatePbeParameters(pbeParameters, password, ReadOnlySpan.Empty); ThrowIfDisposed(); @@ -856,7 +856,7 @@ public bool TryExportEncryptedPkcs8PrivateKey( Span destination, out int bytesWritten) { - ThrowIfNull(password); + ArgumentNullException.ThrowIfNull(password); return TryExportEncryptedPkcs8PrivateKey(password.AsSpan(), pbeParameters, destination, out bytesWritten); } @@ -902,7 +902,7 @@ public bool TryExportEncryptedPkcs8PrivateKey( Span destination, out int bytesWritten) { - ThrowIfNull(pbeParameters); + ArgumentNullException.ThrowIfNull(pbeParameters); PasswordBasedEncryption.ValidatePbeParameters(pbeParameters, ReadOnlySpan.Empty, passwordBytes); ThrowIfDisposed(); @@ -942,7 +942,7 @@ public bool TryExportEncryptedPkcs8PrivateKey( /// public byte[] ExportEncryptedPkcs8PrivateKey(ReadOnlySpan passwordBytes, PbeParameters pbeParameters) { - ThrowIfNull(pbeParameters); + ArgumentNullException.ThrowIfNull(pbeParameters); PasswordBasedEncryption.ValidatePbeParameters(pbeParameters, ReadOnlySpan.Empty, passwordBytes); ThrowIfDisposed(); @@ -982,7 +982,7 @@ public byte[] ExportEncryptedPkcs8PrivateKey(ReadOnlySpan passwordBytes, P /// public byte[] ExportEncryptedPkcs8PrivateKey(ReadOnlySpan password, PbeParameters pbeParameters) { - ThrowIfNull(pbeParameters); + ArgumentNullException.ThrowIfNull(pbeParameters); PasswordBasedEncryption.ValidatePbeParameters(pbeParameters, password, ReadOnlySpan.Empty); ThrowIfDisposed(); @@ -1022,7 +1022,7 @@ public byte[] ExportEncryptedPkcs8PrivateKey(ReadOnlySpan password, PbePar /// public byte[] ExportEncryptedPkcs8PrivateKey(string password, PbeParameters pbeParameters) { - ThrowIfNull(password); + ArgumentNullException.ThrowIfNull(password); return ExportEncryptedPkcs8PrivateKey(password.AsSpan(), pbeParameters); } @@ -1056,7 +1056,7 @@ public byte[] ExportEncryptedPkcs8PrivateKey(string password, PbeParameters pbeP /// public string ExportEncryptedPkcs8PrivateKeyPem(ReadOnlySpan passwordBytes, PbeParameters pbeParameters) { - ThrowIfNull(pbeParameters); + ArgumentNullException.ThrowIfNull(pbeParameters); PasswordBasedEncryption.ValidatePbeParameters(pbeParameters, ReadOnlySpan.Empty, passwordBytes); ThrowIfDisposed(); @@ -1097,7 +1097,7 @@ public string ExportEncryptedPkcs8PrivateKeyPem(ReadOnlySpan passwordBytes /// public string ExportEncryptedPkcs8PrivateKeyPem(ReadOnlySpan password, PbeParameters pbeParameters) { - ThrowIfNull(pbeParameters); + ArgumentNullException.ThrowIfNull(pbeParameters); PasswordBasedEncryption.ValidatePbeParameters(pbeParameters, password, ReadOnlySpan.Empty); ThrowIfDisposed(); @@ -1138,7 +1138,7 @@ public string ExportEncryptedPkcs8PrivateKeyPem(ReadOnlySpan password, Pbe /// public string ExportEncryptedPkcs8PrivateKeyPem(string password, PbeParameters pbeParameters) { - ThrowIfNull(password); + ArgumentNullException.ThrowIfNull(password); return ExportEncryptedPkcs8PrivateKeyPem(password.AsSpan(), pbeParameters); } @@ -1200,7 +1200,7 @@ public static MLKem ImportSubjectPublicKeyInfo(ReadOnlySpan source) /// public static MLKem ImportSubjectPublicKeyInfo(byte[] source) { - ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return ImportSubjectPublicKeyInfo(new ReadOnlySpan(source)); } @@ -1250,7 +1250,7 @@ public static MLKem ImportPkcs8PrivateKey(ReadOnlySpan source) /// public static MLKem ImportPkcs8PrivateKey(byte[] source) { - ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return ImportPkcs8PrivateKey(new ReadOnlySpan(source)); } @@ -1387,7 +1387,7 @@ public static MLKem ImportEncryptedPkcs8PrivateKey(ReadOnlySpan password, /// public static MLKem ImportEncryptedPkcs8PrivateKey(string password, ReadOnlySpan source) { - ThrowIfNull(password); + ArgumentNullException.ThrowIfNull(password); ThrowIfTrailingData(source); ThrowIfNotSupported(); @@ -1449,7 +1449,7 @@ public static MLKem ImportFromPem(ReadOnlySpan source) /// public static MLKem ImportFromPem(string source) { - ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return ImportFromPem(source.AsSpan()); } @@ -1580,8 +1580,8 @@ public static MLKem ImportFromEncryptedPem(ReadOnlySpan source, ReadOnlySp /// public static MLKem ImportFromEncryptedPem(string source, string password) { - ThrowIfNull(source); - ThrowIfNull(password); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(password); return ImportFromEncryptedPem(source.AsSpan(), password.AsSpan()); } @@ -1592,8 +1592,8 @@ public static MLKem ImportFromEncryptedPem(string source, string password) /// public static MLKem ImportFromEncryptedPem(string source, byte[] passwordBytes) { - ThrowIfNull(source); - ThrowIfNull(passwordBytes); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(passwordBytes); return ImportFromEncryptedPem(source.AsSpan(), new ReadOnlySpan(passwordBytes)); } @@ -1750,20 +1750,6 @@ private static void ThrowIfTrailingData(ReadOnlySpan data) } } - private static void ThrowIfNull( - [NotNull] object? argument, - [CallerArgumentExpression(nameof(argument))] string? paramName = null) - { -#if NET - ArgumentNullException.ThrowIfNull(argument, paramName); -#else - if (argument is null) - { - throw new ArgumentNullException(paramName); - } -#endif - } - private protected void ThrowIfDisposed() { #if NET diff --git a/src/libraries/Common/src/System/Security/Cryptography/Pkcs/Pkcs12Builder.cs b/src/libraries/Common/src/System/Security/Cryptography/Pkcs/Pkcs12Builder.cs index fdd5657543a655..c8dc35a5980910 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/Pkcs/Pkcs12Builder.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/Pkcs/Pkcs12Builder.cs @@ -40,14 +40,8 @@ public void AddSafeContentsEncrypted( ReadOnlySpan passwordBytes, PbeParameters pbeParameters) { - if (safeContents is null) - { - throw new ArgumentNullException(nameof(safeContents)); - } - if (pbeParameters is null) - { - throw new ArgumentNullException(nameof(pbeParameters)); - } + ArgumentNullException.ThrowIfNull(safeContents); + ArgumentNullException.ThrowIfNull(pbeParameters); if (pbeParameters.IterationCount < 1) throw new ArgumentOutOfRangeException(nameof(pbeParameters)); @@ -90,14 +84,8 @@ public void AddSafeContentsEncrypted( ReadOnlySpan password, PbeParameters pbeParameters) { - if (safeContents is null) - { - throw new ArgumentNullException(nameof(safeContents)); - } - if (pbeParameters is null) - { - throw new ArgumentNullException(nameof(pbeParameters)); - } + ArgumentNullException.ThrowIfNull(safeContents); + ArgumentNullException.ThrowIfNull(pbeParameters); if (pbeParameters.IterationCount < 1) throw new ArgumentOutOfRangeException(nameof(pbeParameters)); @@ -125,10 +113,7 @@ public void AddSafeContentsEncrypted( public void AddSafeContentsUnencrypted(Pkcs12SafeContents safeContents) { - if (safeContents is null) - { - throw new ArgumentNullException(nameof(safeContents)); - } + ArgumentNullException.ThrowIfNull(safeContents); if (IsSealed) throw new InvalidOperationException(SR.Cryptography_Pkcs12_PfxIsSealed); diff --git a/src/libraries/Common/src/System/Security/Cryptography/Pkcs/Pkcs12CertBag.cs b/src/libraries/Common/src/System/Security/Cryptography/Pkcs/Pkcs12CertBag.cs index eacd4bc7cd2c84..9421e834d2c7bc 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/Pkcs/Pkcs12CertBag.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/Pkcs/Pkcs12CertBag.cs @@ -89,10 +89,7 @@ public X509Certificate2 GetCertificate() private static byte[] EncodeBagValue(Oid certificateType, ReadOnlyMemory encodedCertificate) { - if (certificateType is null) - { - throw new ArgumentNullException(nameof(certificateType)); - } + ArgumentNullException.ThrowIfNull(certificateType); if (certificateType.Value == null) throw new CryptographicException(SR.Argument_InvalidOidValue); diff --git a/src/libraries/Common/src/System/Security/Cryptography/Pkcs/Pkcs12SafeContents.cs b/src/libraries/Common/src/System/Security/Cryptography/Pkcs/Pkcs12SafeContents.cs index e189dabdcc2aab..2fca4a8208ddb3 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/Pkcs/Pkcs12SafeContents.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/Pkcs/Pkcs12SafeContents.cs @@ -62,10 +62,7 @@ internal Pkcs12SafeContents(ContentInfoAsn contentInfoAsn) public void AddSafeBag(Pkcs12SafeBag safeBag) { - if (safeBag is null) - { - throw new ArgumentNullException(nameof(safeBag)); - } + ArgumentNullException.ThrowIfNull(safeBag); if (IsReadOnly) throw new InvalidOperationException(SR.Cryptography_Pkcs12_SafeContentsIsReadOnly); @@ -77,10 +74,7 @@ public void AddSafeBag(Pkcs12SafeBag safeBag) public Pkcs12CertBag AddCertificate(X509Certificate2 certificate) { - if (certificate is null) - { - throw new ArgumentNullException(nameof(certificate)); - } + ArgumentNullException.ThrowIfNull(certificate); if (IsReadOnly) throw new InvalidOperationException(SR.Cryptography_Pkcs12_SafeContentsIsReadOnly); @@ -92,10 +86,7 @@ public Pkcs12CertBag AddCertificate(X509Certificate2 certificate) public Pkcs12KeyBag AddKeyUnencrypted(AsymmetricAlgorithm key) { - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); if (IsReadOnly) throw new InvalidOperationException(SR.Cryptography_Pkcs12_SafeContentsIsReadOnly); @@ -108,10 +99,7 @@ public Pkcs12KeyBag AddKeyUnencrypted(AsymmetricAlgorithm key) public Pkcs12SafeContentsBag AddNestedContents(Pkcs12SafeContents safeContents) { - if (safeContents is null) - { - throw new ArgumentNullException(nameof(safeContents)); - } + ArgumentNullException.ThrowIfNull(safeContents); if (safeContents.ConfidentialityMode != Pkcs12ConfidentialityMode.None) throw new ArgumentException(SR.Cryptography_Pkcs12_CannotProcessEncryptedSafeContents, nameof(safeContents)); @@ -140,10 +128,7 @@ public Pkcs12ShroudedKeyBag AddShroudedKey( ReadOnlySpan passwordBytes, PbeParameters pbeParameters) { - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); if (IsReadOnly) throw new InvalidOperationException(SR.Cryptography_Pkcs12_SafeContentsIsReadOnly); @@ -171,10 +156,7 @@ public Pkcs12ShroudedKeyBag AddShroudedKey( ReadOnlySpan password, PbeParameters pbeParameters) { - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); if (IsReadOnly) throw new InvalidOperationException(SR.Cryptography_Pkcs12_SafeContentsIsReadOnly); @@ -187,10 +169,7 @@ public Pkcs12ShroudedKeyBag AddShroudedKey( public Pkcs12SecretBag AddSecret(Oid secretType, ReadOnlyMemory secretValue) { - if (secretType is null) - { - throw new ArgumentNullException(nameof(secretType)); - } + ArgumentNullException.ThrowIfNull(secretType); // Read to ensure that there is precisely one legally encoded value. PkcsHelpers.EnsureSingleBerValue(secretValue.Span); diff --git a/src/libraries/Common/src/System/Security/Cryptography/Pkcs/Pkcs8PrivateKeyInfo.cs b/src/libraries/Common/src/System/Security/Cryptography/Pkcs/Pkcs8PrivateKeyInfo.cs index b4c4745d8e7f3d..b70f34ab20d8df 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/Pkcs/Pkcs8PrivateKeyInfo.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/Pkcs/Pkcs8PrivateKeyInfo.cs @@ -28,10 +28,7 @@ public Pkcs8PrivateKeyInfo( ReadOnlyMemory privateKey, bool skipCopies = false) { - if (algorithmId is null) - { - throw new ArgumentNullException(nameof(algorithmId)); - } + ArgumentNullException.ThrowIfNull(algorithmId); if (algorithmParameters?.Length > 0) { @@ -61,10 +58,7 @@ private Pkcs8PrivateKeyInfo( public static Pkcs8PrivateKeyInfo Create(AsymmetricAlgorithm privateKey) { - if (privateKey is null) - { - throw new ArgumentNullException(nameof(privateKey)); - } + ArgumentNullException.ThrowIfNull(privateKey); byte[] pkcs8 = privateKey.ExportPkcs8PrivateKey(); return Decode(pkcs8, out _, skipCopy: true); @@ -106,10 +100,7 @@ public byte[] Encode() public byte[] Encrypt(ReadOnlySpan password, PbeParameters pbeParameters) { - if (pbeParameters is null) - { - throw new ArgumentNullException(nameof(pbeParameters)); - } + ArgumentNullException.ThrowIfNull(pbeParameters); PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, @@ -125,10 +116,7 @@ public byte[] Encrypt(ReadOnlySpan password, PbeParameters pbeParameters) public byte[] Encrypt(ReadOnlySpan passwordBytes, PbeParameters pbeParameters) { - if (pbeParameters is null) - { - throw new ArgumentNullException(nameof(pbeParameters)); - } + ArgumentNullException.ThrowIfNull(pbeParameters); PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, @@ -152,10 +140,7 @@ public bool TryEncrypt( Span destination, out int bytesWritten) { - if (pbeParameters is null) - { - throw new ArgumentNullException(nameof(pbeParameters)); - } + ArgumentNullException.ThrowIfNull(pbeParameters); PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, @@ -173,10 +158,7 @@ public bool TryEncrypt( Span destination, out int bytesWritten) { - if (pbeParameters is null) - { - throw new ArgumentNullException(nameof(pbeParameters)); - } + ArgumentNullException.ThrowIfNull(pbeParameters); PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, diff --git a/src/libraries/Common/src/System/Security/Cryptography/Pkcs/Pkcs9AttributeObject.cs b/src/libraries/Common/src/System/Security/Cryptography/Pkcs/Pkcs9AttributeObject.cs index a2f7cef4bd5b64..a57f06fc3b9db1 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/Pkcs/Pkcs9AttributeObject.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/Pkcs/Pkcs9AttributeObject.cs @@ -73,10 +73,7 @@ internal Pkcs9AttributeObject(Oid oid) public override void CopyFrom(AsnEncodedData asnEncodedData) { - if (asnEncodedData is null) - { - throw new ArgumentNullException(nameof(asnEncodedData)); - } + ArgumentNullException.ThrowIfNull(asnEncodedData); if (!(asnEncodedData is Pkcs9AttributeObject)) throw new ArgumentException(SR.Cryptography_Pkcs9_AttributeMismatch); diff --git a/src/libraries/Common/src/System/Security/Cryptography/Pkcs/Pkcs9DocumentDescription.cs b/src/libraries/Common/src/System/Security/Cryptography/Pkcs/Pkcs9DocumentDescription.cs index fc3f13d96db692..6f28e8f43752e3 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/Pkcs/Pkcs9DocumentDescription.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/Pkcs/Pkcs9DocumentDescription.cs @@ -75,10 +75,7 @@ public override void CopyFrom(AsnEncodedData asnEncodedData) private static byte[] Encode(string documentDescription) { - if (documentDescription is null) - { - throw new ArgumentNullException(nameof(documentDescription)); - } + ArgumentNullException.ThrowIfNull(documentDescription); byte[] octets = documentDescription.UnicodeToOctetString(); return PkcsHelpers.EncodeOctetString(octets); diff --git a/src/libraries/Common/src/System/Security/Cryptography/Pkcs/Pkcs9DocumentName.cs b/src/libraries/Common/src/System/Security/Cryptography/Pkcs/Pkcs9DocumentName.cs index 2589151d1cae29..1968a4b2eb6085 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/Pkcs/Pkcs9DocumentName.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/Pkcs/Pkcs9DocumentName.cs @@ -75,10 +75,7 @@ public override void CopyFrom(AsnEncodedData asnEncodedData) private static byte[] Encode(string documentName) { - if (documentName is null) - { - throw new ArgumentNullException(nameof(documentName)); - } + ArgumentNullException.ThrowIfNull(documentName); byte[] octets = documentName.UnicodeToOctetString(); return PkcsHelpers.EncodeOctetString(octets); diff --git a/src/libraries/Common/src/System/Security/Cryptography/SP800108HmacCounterKdf.cs b/src/libraries/Common/src/System/Security/Cryptography/SP800108HmacCounterKdf.cs index 234ae82ed7d501..523f99be26051b 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/SP800108HmacCounterKdf.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/SP800108HmacCounterKdf.cs @@ -92,8 +92,7 @@ public SP800108HmacCounterKdf(byte[] key, HashAlgorithmName hashAlgorithm) // This constructor doesn't defer to the span constructor because SP800108HmacCounterKdfImplementationCng // has a constructor for byte[] key to avoid a byte[]->span->byte[] conversion. - if (key is null) - throw new ArgumentNullException(nameof(key)); + ArgumentNullException.ThrowIfNull(key); CheckHashAlgorithm(hashAlgorithm); _implementation = CreateImplementation(key, hashAlgorithm); @@ -140,14 +139,9 @@ public SP800108HmacCounterKdf(byte[] key, HashAlgorithmName hashAlgorithm) /// public static byte[] DeriveBytes(byte[] key, HashAlgorithmName hashAlgorithm, byte[] label, byte[] context, int derivedKeyLengthInBytes) { - if (key is null) - throw new ArgumentNullException(nameof(key)); - - if (label is null) - throw new ArgumentNullException(nameof(label)); - - if (context is null) - throw new ArgumentNullException(nameof(context)); + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(label); + ArgumentNullException.ThrowIfNull(context); CheckPrfOutputLength(derivedKeyLengthInBytes, nameof(derivedKeyLengthInBytes)); CheckHashAlgorithm(hashAlgorithm); @@ -206,14 +200,9 @@ public static byte[] DeriveBytes(byte[] key, HashAlgorithmName hashAlgorithm, by /// public static byte[] DeriveBytes(byte[] key, HashAlgorithmName hashAlgorithm, string label, string context, int derivedKeyLengthInBytes) { - if (key is null) - throw new ArgumentNullException(nameof(key)); - - if (label is null) - throw new ArgumentNullException(nameof(label)); - - if (context is null) - throw new ArgumentNullException(nameof(context)); + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(label); + ArgumentNullException.ThrowIfNull(context); CheckPrfOutputLength(derivedKeyLengthInBytes, nameof(derivedKeyLengthInBytes)); CheckHashAlgorithm(hashAlgorithm); @@ -389,11 +378,8 @@ public static void DeriveBytes(ReadOnlySpan key, HashAlgorithmName hashAlg /// public byte[] DeriveKey(byte[] label, byte[] context, int derivedKeyLengthInBytes) { - if (label is null) - throw new ArgumentNullException(nameof(label)); - - if (context is null) - throw new ArgumentNullException(nameof(context)); + ArgumentNullException.ThrowIfNull(label); + ArgumentNullException.ThrowIfNull(context); CheckPrfOutputLength(derivedKeyLengthInBytes, nameof(derivedKeyLengthInBytes)); @@ -527,11 +513,8 @@ public void DeriveKey(ReadOnlySpan label, ReadOnlySpan context, Span /// public byte[] DeriveKey(string label, string context, int derivedKeyLengthInBytes) { - if (label is null) - throw new ArgumentNullException(nameof(label)); - - if (context is null) - throw new ArgumentNullException(nameof(context)); + ArgumentNullException.ThrowIfNull(label); + ArgumentNullException.ThrowIfNull(context); return DeriveKey(label.AsSpan(), context.AsSpan(), derivedKeyLengthInBytes); } diff --git a/src/libraries/Common/src/System/Security/Cryptography/SlhDsa.cs b/src/libraries/Common/src/System/Security/Cryptography/SlhDsa.cs index c70c5effb3fe3d..25c3c2c7941610 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/SlhDsa.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/SlhDsa.cs @@ -366,7 +366,7 @@ public string ExportPkcs8PrivateKeyPem() /// public byte[] ExportEncryptedPkcs8PrivateKey(ReadOnlySpan password, PbeParameters pbeParameters) { - ThrowIfNull(pbeParameters); + ArgumentNullException.ThrowIfNull(pbeParameters); ThrowIfDisposed(); // TODO: Validation on pbeParameters. @@ -409,7 +409,7 @@ public byte[] ExportEncryptedPkcs8PrivateKey(ReadOnlySpan password, PbePar /// public byte[] ExportEncryptedPkcs8PrivateKey(ReadOnlySpan passwordBytes, PbeParameters pbeParameters) { - ThrowIfNull(pbeParameters); + ArgumentNullException.ThrowIfNull(pbeParameters); ThrowIfDisposed(); // TODO: Validation on pbeParameters. @@ -462,7 +462,7 @@ public bool TryExportEncryptedPkcs8PrivateKey( Span destination, out int bytesWritten) { - ThrowIfNull(pbeParameters); + ArgumentNullException.ThrowIfNull(pbeParameters); ThrowIfDisposed(); AsnWriter writer = ExportEncryptedPkcs8PrivateKeyCore(password, pbeParameters); @@ -515,7 +515,7 @@ public bool TryExportEncryptedPkcs8PrivateKey( Span destination, out int bytesWritten) { - ThrowIfNull(pbeParameters); + ArgumentNullException.ThrowIfNull(pbeParameters); ThrowIfDisposed(); AsnWriter writer = ExportEncryptedPkcs8PrivateKeyCore(passwordBytes, pbeParameters); @@ -557,7 +557,7 @@ public string ExportEncryptedPkcs8PrivateKeyPem( ReadOnlySpan password, PbeParameters pbeParameters) { - ThrowIfNull(pbeParameters); + ArgumentNullException.ThrowIfNull(pbeParameters); ThrowIfDisposed(); // TODO: Validation on pbeParameters. @@ -603,7 +603,7 @@ public string ExportEncryptedPkcs8PrivateKeyPem( ReadOnlySpan passwordBytes, PbeParameters pbeParameters) { - ThrowIfNull(pbeParameters); + ArgumentNullException.ThrowIfNull(pbeParameters); ThrowIfDisposed(); // TODO: Validation on pbeParameters. @@ -685,7 +685,7 @@ public int ExportSlhDsaSecretKey(Span destination) /// public static SlhDsa GenerateKey(SlhDsaAlgorithm algorithm) { - ThrowIfNull(algorithm); + ArgumentNullException.ThrowIfNull(algorithm); ThrowIfNotSupported(); return SlhDsaImplementation.GenerateKeyCore(algorithm); @@ -995,7 +995,7 @@ public static SlhDsa ImportFromEncryptedPem(ReadOnlySpan source, ReadOnlyS /// public static SlhDsa ImportSlhDsaPublicKey(SlhDsaAlgorithm algorithm, ReadOnlySpan source) { - ThrowIfNull(algorithm); + ArgumentNullException.ThrowIfNull(algorithm); if (source.Length != algorithm.PublicKeySizeInBytes) { @@ -1034,7 +1034,7 @@ public static SlhDsa ImportSlhDsaPublicKey(SlhDsaAlgorithm algorithm, ReadOnlySp /// public static SlhDsa ImportSlhDsaSecretKey(SlhDsaAlgorithm algorithm, ReadOnlySpan source) { - ThrowIfNull(algorithm); + ArgumentNullException.ThrowIfNull(algorithm); if (source.Length != algorithm.SecretKeySizeInBytes) { @@ -1209,19 +1209,6 @@ internal static void ThrowIfNotSupported() } } - private static void ThrowIfNull( - [NotNull] object? argument, - [CallerArgumentExpression(nameof(argument))] string? paramName = null) - { -#if NET - ArgumentNullException.ThrowIfNull(argument, paramName); -#else - if (argument is null) - { - throw new ArgumentNullException(paramName); - } -#endif - } internal static string GetEncodedPemString(AsnWriter writer, string label) { diff --git a/src/libraries/Common/src/System/Security/Cryptography/X509Certificates/Pkcs12LoaderLimits.cs b/src/libraries/Common/src/System/Security/Cryptography/X509Certificates/Pkcs12LoaderLimits.cs index f19859c54b0352..678e8ea6d78a34 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/X509Certificates/Pkcs12LoaderLimits.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/X509Certificates/Pkcs12LoaderLimits.cs @@ -99,12 +99,7 @@ public Pkcs12LoaderLimits() /// public Pkcs12LoaderLimits(Pkcs12LoaderLimits copyFrom) { -#if NET ArgumentNullException.ThrowIfNull(copyFrom); -#else - if (copyFrom is null) - throw new ArgumentNullException(nameof(copyFrom)); -#endif // Do not copy _isReadOnly. diff --git a/src/libraries/Common/src/System/Security/Cryptography/X509Certificates/X509CertificateLoader.cs b/src/libraries/Common/src/System/Security/Cryptography/X509Certificates/X509CertificateLoader.cs index e53ad3fe0bd236..4f801a56862bb6 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/X509Certificates/X509CertificateLoader.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/X509Certificates/X509CertificateLoader.cs @@ -132,7 +132,7 @@ public static X509Certificate2 LoadPkcs12( X509KeyStorageFlags keyStorageFlags = X509KeyStorageFlags.DefaultKeySet, Pkcs12LoaderLimits? loaderLimits = null) { - ThrowIfNull(data); + ArgumentNullException.ThrowIfNull(data); ValidateKeyStorageFlagsCore(keyStorageFlags); return LoadPkcs12( @@ -373,7 +373,7 @@ public static X509Certificate2Collection LoadPkcs12Collection( X509KeyStorageFlags keyStorageFlags = X509KeyStorageFlags.DefaultKeySet, Pkcs12LoaderLimits? loaderLimits = null) { - ThrowIfNull(data); + ArgumentNullException.ThrowIfNull(data); ValidateKeyStorageFlagsCore(keyStorageFlags); return LoadPkcs12Collection( @@ -708,16 +708,6 @@ private static void ThrowWithHResult(string message, int hResult, Exception inne #endif } - private static void ThrowIfNull( - [NotNull] object? argument, - [CallerArgumentExpression(nameof(argument))] string? paramName = null) - { - if (argument is null) - { - ThrowNull(paramName); - } - } - private static void ThrowIfNullOrEmpty( [NotNull] string? argument, [CallerArgumentExpression(nameof(argument))] string? paramName = null) @@ -737,7 +727,7 @@ private static void ThrowNull(string? paramName) [DoesNotReturn] private static void ThrowNullOrEmpty(string? argument, string? paramName) { - ThrowIfNull(argument, paramName); + ArgumentNullException.ThrowIfNull(argument, paramName); throw new ArgumentException(SR.Argument_EmptyString, paramName); } } diff --git a/src/libraries/Common/src/System/Threading/Tasks/TaskToAsyncResult.cs b/src/libraries/Common/src/System/Threading/Tasks/TaskToAsyncResult.cs index 8ffe3ad042fbaf..086bc40f0cbd2d 100644 --- a/src/libraries/Common/src/System/Threading/Tasks/TaskToAsyncResult.cs +++ b/src/libraries/Common/src/System/Threading/Tasks/TaskToAsyncResult.cs @@ -36,10 +36,7 @@ public static IAsyncResult Begin(Task task, AsyncCallback? callback, object? sta ArgumentNullException.ThrowIfNull(task); #else - if (task is null) - { - throw new ArgumentNullException(nameof(task)); - } + ArgumentNullException.ThrowIfNull(task); #endif return new TaskAsyncResult(task, state, callback); @@ -70,14 +67,7 @@ public static TResult End(IAsyncResult asyncResult) => /// was not produced by a call to . public static Task Unwrap(IAsyncResult asyncResult) { -#if NET ArgumentNullException.ThrowIfNull(asyncResult); -#else - if (asyncResult is null) - { - throw new ArgumentNullException(nameof(asyncResult)); - } -#endif if ((asyncResult as TaskAsyncResult)?._task is not Task task) { @@ -99,14 +89,7 @@ public static Task Unwrap(IAsyncResult asyncResult) /// public static Task Unwrap(IAsyncResult asyncResult) { -#if NET ArgumentNullException.ThrowIfNull(asyncResult); -#else - if (asyncResult is null) - { - throw new ArgumentNullException(nameof(asyncResult)); - } -#endif if ((asyncResult as TaskAsyncResult)?._task is not Task task) { diff --git a/src/libraries/Common/src/System/ThrowHelper.cs b/src/libraries/Common/src/System/ThrowHelper.cs deleted file mode 100644 index 0e9117b9e7bf69..00000000000000 --- a/src/libraries/Common/src/System/ThrowHelper.cs +++ /dev/null @@ -1,51 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using System.Diagnostics.CodeAnalysis; -using System.Runtime.CompilerServices; - -// This file is intended to be used by components that don't have access to ArgumentNullException.ThrowIfNull. -#pragma warning disable CS0436 // Type conflicts with imported type - -namespace System -{ - internal static partial class ThrowHelper - { - /// Throws an if is null. - /// The reference type argument to validate as non-null. - /// The name of the parameter with which corresponds. - internal static void ThrowIfNull( -#if NET - [NotNull] -#endif - object? argument, - [CallerArgumentExpression(nameof(argument))] string? paramName = null) - { - if (argument is null) - { - Throw(paramName); - } - } - -#if NET - [DoesNotReturn] -#endif - private static void Throw(string? paramName) => throw new ArgumentNullException(paramName); - } -} - -#if !NET -namespace System.Runtime.CompilerServices -{ - [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] - internal sealed class CallerArgumentExpressionAttribute : Attribute - { - public CallerArgumentExpressionAttribute(string parameterName) - { - ParameterName = parameterName; - } - - public string ParameterName { get; } - } -} -#endif diff --git a/src/libraries/Common/src/System/TimeProvider.cs b/src/libraries/Common/src/System/TimeProvider.cs index d16a23bf3abf84..e28275393b6ff0 100644 --- a/src/libraries/Common/src/System/TimeProvider.cs +++ b/src/libraries/Common/src/System/TimeProvider.cs @@ -162,10 +162,7 @@ public virtual ITimer CreateTimer(TimerCallback callback, object? state, TimeSpa #if SYSTEM_PRIVATE_CORELIB ArgumentNullException.ThrowIfNull(callback); #else - if (callback is null) - { - throw new ArgumentNullException(nameof(callback)); - } + ArgumentNullException.ThrowIfNull(callback); #endif // SYSTEM_PRIVATE_CORELIB return new SystemTimeProviderTimer(dueTime, period, callback, state); diff --git a/src/libraries/Common/tests/System/Net/WebSockets/WebSocketStream.cs b/src/libraries/Common/tests/System/Net/WebSockets/WebSocketStream.cs index 5666195ac8628e..84a96f15c48582 100644 --- a/src/libraries/Common/tests/System/Net/WebSockets/WebSocketStream.cs +++ b/src/libraries/Common/tests/System/Net/WebSockets/WebSocketStream.cs @@ -41,10 +41,7 @@ public WebSocketStream(WebSocket socket, FileAccess access) public WebSocketStream(WebSocket socket, FileAccess access, bool ownsSocket) { - if (socket == null) - { - throw new ArgumentNullException(nameof(socket)); - } + ArgumentNullException.ThrowIfNull(socket); if (socket.State != WebSocketState.Open) { throw new IOException("The operation is not allowed on non-connected sockets."); diff --git a/src/libraries/Common/tests/System/Runtime/CompilerServices/RuntimeHelpers.cs b/src/libraries/Common/tests/System/Runtime/CompilerServices/RuntimeHelpers.cs index 1b7fe928a7fee3..935e279f94dc2b 100644 --- a/src/libraries/Common/tests/System/Runtime/CompilerServices/RuntimeHelpers.cs +++ b/src/libraries/Common/tests/System/Runtime/CompilerServices/RuntimeHelpers.cs @@ -10,7 +10,7 @@ internal static class RuntimeHelpers /// internal static T[] GetSubArray(T[] array, Range range) { - if (array == null) + if (array is null) { throw new ArgumentNullException(nameof(array)); } diff --git a/src/libraries/Directory.Build.targets b/src/libraries/Directory.Build.targets index 0b41e5e56c78a6..2152e79891a88a 100644 --- a/src/libraries/Directory.Build.targets +++ b/src/libraries/Directory.Build.targets @@ -167,14 +167,22 @@ - + + + + + + - true + ..\..\src\Resources\Strings.resx diff --git a/src/libraries/Microsoft.Extensions.Configuration.Binder/tests/UnitTests/Microsoft.Extensions.Configuration.Binder.Tests.csproj b/src/libraries/Microsoft.Extensions.Configuration.Binder/tests/UnitTests/Microsoft.Extensions.Configuration.Binder.Tests.csproj index 209a2b10695a85..82491c7798b9e9 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Binder/tests/UnitTests/Microsoft.Extensions.Configuration.Binder.Tests.csproj +++ b/src/libraries/Microsoft.Extensions.Configuration.Binder/tests/UnitTests/Microsoft.Extensions.Configuration.Binder.Tests.csproj @@ -3,6 +3,7 @@ $(NetCoreAppCurrent);$(NetFrameworkCurrent) true + ..\..\src\Resources\Strings.resx diff --git a/src/libraries/Microsoft.Extensions.Configuration.CommandLine/src/CommandLineConfigurationProvider.cs b/src/libraries/Microsoft.Extensions.Configuration.CommandLine/src/CommandLineConfigurationProvider.cs index 7afcfc40fa68fd..2623233e69243b 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.CommandLine/src/CommandLineConfigurationProvider.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.CommandLine/src/CommandLineConfigurationProvider.cs @@ -20,7 +20,7 @@ public class CommandLineConfigurationProvider : ConfigurationProvider /// The switch mappings. public CommandLineConfigurationProvider(IEnumerable args, IDictionary? switchMappings = null) { - ThrowHelper.ThrowIfNull(args); + ArgumentNullException.ThrowIfNull(args); Args = args; diff --git a/src/libraries/Microsoft.Extensions.Configuration.CommandLine/src/Microsoft.Extensions.Configuration.CommandLine.csproj b/src/libraries/Microsoft.Extensions.Configuration.CommandLine/src/Microsoft.Extensions.Configuration.CommandLine.csproj index 606dbd87429793..47ce845bbf01e1 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.CommandLine/src/Microsoft.Extensions.Configuration.CommandLine.csproj +++ b/src/libraries/Microsoft.Extensions.Configuration.CommandLine/src/Microsoft.Extensions.Configuration.CommandLine.csproj @@ -11,8 +11,6 @@ - diff --git a/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileConfigurationExtensions.cs b/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileConfigurationExtensions.cs index 669c9c3aee9bd1..531974d3e74123 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileConfigurationExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileConfigurationExtensions.cs @@ -22,8 +22,8 @@ public static class FileConfigurationExtensions /// The . public static IConfigurationBuilder SetFileProvider(this IConfigurationBuilder builder, IFileProvider fileProvider) { - ThrowHelper.ThrowIfNull(builder); - ThrowHelper.ThrowIfNull(fileProvider); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(fileProvider); builder.Properties[FileProviderKey] = fileProvider; return builder; @@ -36,7 +36,7 @@ public static IConfigurationBuilder SetFileProvider(this IConfigurationBuilder b /// The default . public static IFileProvider GetFileProvider(this IConfigurationBuilder builder) { - ThrowHelper.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(builder); if (builder.Properties.TryGetValue(FileProviderKey, out object? provider)) { @@ -54,8 +54,8 @@ public static IFileProvider GetFileProvider(this IConfigurationBuilder builder) /// The . public static IConfigurationBuilder SetBasePath(this IConfigurationBuilder builder, string basePath) { - ThrowHelper.ThrowIfNull(builder); - ThrowHelper.ThrowIfNull(basePath); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(basePath); return builder.SetFileProvider(new PhysicalFileProvider(basePath)); } @@ -68,7 +68,7 @@ public static IConfigurationBuilder SetBasePath(this IConfigurationBuilder build /// The . public static IConfigurationBuilder SetFileLoadExceptionHandler(this IConfigurationBuilder builder, Action handler) { - ThrowHelper.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(builder); builder.Properties[FileLoadExceptionHandlerKey] = handler; return builder; @@ -81,7 +81,7 @@ public static IConfigurationBuilder SetFileLoadExceptionHandler(this IConfigurat /// The The Action to be invoked on a file load exception, if set. public static Action? GetFileLoadExceptionHandler(this IConfigurationBuilder builder) { - ThrowHelper.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(builder); if (builder.Properties.TryGetValue(FileLoadExceptionHandlerKey, out object? handler)) { diff --git a/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileConfigurationProvider.cs b/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileConfigurationProvider.cs index d2cc8f5d85ac6f..f84ed8ead309ef 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileConfigurationProvider.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileConfigurationProvider.cs @@ -25,7 +25,7 @@ public abstract class FileConfigurationProvider : ConfigurationProvider, IDispos /// The source settings. public FileConfigurationProvider(FileConfigurationSource source) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); Source = source; diff --git a/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/Microsoft.Extensions.Configuration.FileExtensions.csproj b/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/Microsoft.Extensions.Configuration.FileExtensions.csproj index 124b99b6338bc5..7341a9a945aec0 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/Microsoft.Extensions.Configuration.FileExtensions.csproj +++ b/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/Microsoft.Extensions.Configuration.FileExtensions.csproj @@ -13,8 +13,6 @@ - diff --git a/src/libraries/Microsoft.Extensions.Configuration.Ini/src/IniConfigurationExtensions.cs b/src/libraries/Microsoft.Extensions.Configuration.Ini/src/IniConfigurationExtensions.cs index 1f17450abf4ac0..cf8accfaf85a1f 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Ini/src/IniConfigurationExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.Ini/src/IniConfigurationExtensions.cs @@ -64,7 +64,7 @@ public static IConfigurationBuilder AddIniFile(this IConfigurationBuilder builde /// The . public static IConfigurationBuilder AddIniFile(this IConfigurationBuilder builder, IFileProvider? provider, string path, bool optional, bool reloadOnChange) { - ThrowHelper.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(builder); if (string.IsNullOrEmpty(path)) { @@ -98,7 +98,7 @@ public static IConfigurationBuilder AddIniFile(this IConfigurationBuilder builde /// The . public static IConfigurationBuilder AddIniStream(this IConfigurationBuilder builder, Stream stream) { - ThrowHelper.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(builder); return builder.Add(s => s.Stream = stream); } diff --git a/src/libraries/Microsoft.Extensions.Configuration.Ini/src/Microsoft.Extensions.Configuration.Ini.csproj b/src/libraries/Microsoft.Extensions.Configuration.Ini/src/Microsoft.Extensions.Configuration.Ini.csproj index 2fda806ddefe47..66faa852a97541 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Ini/src/Microsoft.Extensions.Configuration.Ini.csproj +++ b/src/libraries/Microsoft.Extensions.Configuration.Ini/src/Microsoft.Extensions.Configuration.Ini.csproj @@ -12,8 +12,6 @@ - diff --git a/src/libraries/Microsoft.Extensions.Configuration.Json/src/JsonConfigurationExtensions.cs b/src/libraries/Microsoft.Extensions.Configuration.Json/src/JsonConfigurationExtensions.cs index c32d20f75943a5..fb2fd7799a75b5 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Json/src/JsonConfigurationExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.Json/src/JsonConfigurationExtensions.cs @@ -64,7 +64,7 @@ public static IConfigurationBuilder AddJsonFile(this IConfigurationBuilder build /// The . public static IConfigurationBuilder AddJsonFile(this IConfigurationBuilder builder, IFileProvider? provider, string path, bool optional, bool reloadOnChange) { - ThrowHelper.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(builder); if (string.IsNullOrEmpty(path)) { @@ -98,7 +98,7 @@ public static IConfigurationBuilder AddJsonFile(this IConfigurationBuilder build /// The . public static IConfigurationBuilder AddJsonStream(this IConfigurationBuilder builder, Stream stream) { - ThrowHelper.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(builder); return builder.Add(s => s.Stream = stream); } diff --git a/src/libraries/Microsoft.Extensions.Configuration.Json/src/Microsoft.Extensions.Configuration.Json.csproj b/src/libraries/Microsoft.Extensions.Configuration.Json/src/Microsoft.Extensions.Configuration.Json.csproj index 3e217a0a5cfaa4..1b1d2e7a165a4b 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Json/src/Microsoft.Extensions.Configuration.Json.csproj +++ b/src/libraries/Microsoft.Extensions.Configuration.Json/src/Microsoft.Extensions.Configuration.Json.csproj @@ -13,8 +13,6 @@ - diff --git a/src/libraries/Microsoft.Extensions.Configuration.UserSecrets/src/Microsoft.Extensions.Configuration.UserSecrets.csproj b/src/libraries/Microsoft.Extensions.Configuration.UserSecrets/src/Microsoft.Extensions.Configuration.UserSecrets.csproj index 4b200df893380c..05591d87aad651 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.UserSecrets/src/Microsoft.Extensions.Configuration.UserSecrets.csproj +++ b/src/libraries/Microsoft.Extensions.Configuration.UserSecrets/src/Microsoft.Extensions.Configuration.UserSecrets.csproj @@ -12,8 +12,6 @@ - diff --git a/src/libraries/Microsoft.Extensions.Configuration.UserSecrets/src/UserSecretsConfigurationExtensions.cs b/src/libraries/Microsoft.Extensions.Configuration.UserSecrets/src/UserSecretsConfigurationExtensions.cs index e82f5534aab449..48b2a860dbab97 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.UserSecrets/src/UserSecretsConfigurationExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.UserSecrets/src/UserSecretsConfigurationExtensions.cs @@ -118,8 +118,8 @@ public static IConfigurationBuilder AddUserSecrets(this IConfigurationBuilder co /// The configuration builder. public static IConfigurationBuilder AddUserSecrets(this IConfigurationBuilder configuration, Assembly assembly, bool optional, bool reloadOnChange) { - ThrowHelper.ThrowIfNull(configuration); - ThrowHelper.ThrowIfNull(assembly); + ArgumentNullException.ThrowIfNull(configuration); + ArgumentNullException.ThrowIfNull(assembly); UserSecretsIdAttribute? attribute = assembly.GetCustomAttribute(); if (attribute != null) @@ -166,8 +166,8 @@ public static IConfigurationBuilder AddUserSecrets(this IConfigurationBuilder co private static IConfigurationBuilder AddUserSecretsInternal(IConfigurationBuilder configuration, string userSecretsId, bool optional, bool reloadOnChange) { - ThrowHelper.ThrowIfNull(configuration); - ThrowHelper.ThrowIfNull(userSecretsId); + ArgumentNullException.ThrowIfNull(configuration); + ArgumentNullException.ThrowIfNull(userSecretsId); return AddSecretsFile(configuration, PathHelper.InternalGetSecretsPathFromSecretsId(userSecretsId, throwIfNoRoot: !optional), optional, reloadOnChange); } diff --git a/src/libraries/Microsoft.Extensions.Configuration.Xml/src/Microsoft.Extensions.Configuration.Xml.csproj b/src/libraries/Microsoft.Extensions.Configuration.Xml/src/Microsoft.Extensions.Configuration.Xml.csproj index c53df5f0c31473..3d71436cac0f28 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Xml/src/Microsoft.Extensions.Configuration.Xml.csproj +++ b/src/libraries/Microsoft.Extensions.Configuration.Xml/src/Microsoft.Extensions.Configuration.Xml.csproj @@ -7,11 +7,6 @@ XML configuration provider implementation for Microsoft.Extensions.Configuration. This package enables you to read configuration parameters from XML files. You can use XmlConfigurationExtensions.AddXmlFile extension method on IConfigurationBuilder to add XML configuration provider to the configuration builder. - - - - diff --git a/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationElement.cs b/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationElement.cs index dba4fc6947b429..3b02bea0434b93 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationElement.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationElement.cs @@ -33,7 +33,7 @@ internal sealed class XmlConfigurationElement public XmlConfigurationElement(string elementName, string? name) { - ThrowHelper.ThrowIfNull(elementName); + ArgumentNullException.ThrowIfNull(elementName); ElementName = elementName; Name = name; diff --git a/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationElementAttributeValue.cs b/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationElementAttributeValue.cs index 2eae9a3c4e701e..0ba6b4c90b3f43 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationElementAttributeValue.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationElementAttributeValue.cs @@ -9,8 +9,8 @@ internal sealed class XmlConfigurationElementAttributeValue { public XmlConfigurationElementAttributeValue(string attribute, string value, int? lineNumber, int? linePosition) { - ThrowHelper.ThrowIfNull(attribute); - ThrowHelper.ThrowIfNull(value); + ArgumentNullException.ThrowIfNull(attribute); + ArgumentNullException.ThrowIfNull(value); Attribute = attribute; Value = value; diff --git a/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationElementTextContent.cs b/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationElementTextContent.cs index ee25d5cfdb6bf8..a4e54d3da5d599 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationElementTextContent.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationElementTextContent.cs @@ -9,7 +9,7 @@ internal sealed class XmlConfigurationElementTextContent { public XmlConfigurationElementTextContent(string textContent, int? linePosition, int? lineNumber) { - ThrowHelper.ThrowIfNull(textContent); + ArgumentNullException.ThrowIfNull(textContent); TextContent = textContent; LineNumber = lineNumber; diff --git a/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationExtensions.cs b/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationExtensions.cs index 35eb1602a9e673..263f7d92ffb351 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationExtensions.cs @@ -73,7 +73,7 @@ public static IConfigurationBuilder AddXmlFile(this IConfigurationBuilder builde [RequiresUnreferencedCode(XmlDocumentDecryptor.RequiresUnreferencedCodeMessage)] public static IConfigurationBuilder AddXmlFile(this IConfigurationBuilder builder, IFileProvider? provider, string path, bool optional, bool reloadOnChange) { - ThrowHelper.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(builder); if (string.IsNullOrEmpty(path)) { @@ -111,7 +111,7 @@ public static IConfigurationBuilder AddXmlFile(this IConfigurationBuilder builde [RequiresUnreferencedCode(XmlDocumentDecryptor.RequiresUnreferencedCodeMessage)] public static IConfigurationBuilder AddXmlStream(this IConfigurationBuilder builder, Stream stream) { - ThrowHelper.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(builder); return builder.Add(s => s.Stream = stream); } diff --git a/src/libraries/Microsoft.Extensions.Configuration/src/ChainedBuilderExtensions.cs b/src/libraries/Microsoft.Extensions.Configuration/src/ChainedBuilderExtensions.cs index 53552dd9bb78bf..283227f0376d85 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/src/ChainedBuilderExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Configuration/src/ChainedBuilderExtensions.cs @@ -29,8 +29,8 @@ public static IConfigurationBuilder AddConfiguration(this IConfigurationBuilder /// The . public static IConfigurationBuilder AddConfiguration(this IConfigurationBuilder configurationBuilder, IConfiguration config, bool shouldDisposeConfiguration) { - ThrowHelper.ThrowIfNull(configurationBuilder); - ThrowHelper.ThrowIfNull(config); + ArgumentNullException.ThrowIfNull(configurationBuilder); + ArgumentNullException.ThrowIfNull(config); configurationBuilder.Add(new ChainedConfigurationSource { diff --git a/src/libraries/Microsoft.Extensions.Configuration/src/ChainedConfigurationProvider.cs b/src/libraries/Microsoft.Extensions.Configuration/src/ChainedConfigurationProvider.cs index 71a324b6bb8df0..363c4459cd8bdb 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/src/ChainedConfigurationProvider.cs +++ b/src/libraries/Microsoft.Extensions.Configuration/src/ChainedConfigurationProvider.cs @@ -21,7 +21,7 @@ public class ChainedConfigurationProvider : IConfigurationProvider, IDisposable /// The source configuration. public ChainedConfigurationProvider(ChainedConfigurationSource source) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); _config = source.Configuration ?? throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "source.Configuration"), nameof(source)); _shouldDisposeConfig = source.ShouldDisposeConfiguration; diff --git a/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationBuilder.cs b/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationBuilder.cs index ca558cc1eb7034..75b930f60f16eb 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationBuilder.cs +++ b/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationBuilder.cs @@ -31,7 +31,7 @@ public class ConfigurationBuilder : IConfigurationBuilder /// The same . public IConfigurationBuilder Add(IConfigurationSource source) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); _sources.Add(source); return this; diff --git a/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationManager.cs b/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationManager.cs index 279813ce195c87..b31c4bb0c6392e 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationManager.cs +++ b/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationManager.cs @@ -89,7 +89,7 @@ public void Dispose() IConfigurationBuilder IConfigurationBuilder.Add(IConfigurationSource source) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); _sources.Add(source); return this; diff --git a/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationRoot.cs b/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationRoot.cs index 50449bb6a2197e..bd53b747a43822 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationRoot.cs +++ b/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationRoot.cs @@ -26,7 +26,7 @@ public class ConfigurationRoot : IConfigurationRoot, IDisposable /// The s for this configuration. public ConfigurationRoot(IList providers) { - ThrowHelper.ThrowIfNull(providers); + ArgumentNullException.ThrowIfNull(providers); _providers = providers; _changeTokenRegistrations = new List(providers.Count); diff --git a/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationSection.cs b/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationSection.cs index eb888c8478ed5a..7eb7ef75339e68 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationSection.cs +++ b/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationSection.cs @@ -26,8 +26,8 @@ public class ConfigurationSection : IConfigurationSection /// The path to this section. public ConfigurationSection(IConfigurationRoot root, string path) { - ThrowHelper.ThrowIfNull(root); - ThrowHelper.ThrowIfNull(path); + ArgumentNullException.ThrowIfNull(root); + ArgumentNullException.ThrowIfNull(path); _root = root; _path = path; diff --git a/src/libraries/Microsoft.Extensions.Configuration/src/MemoryConfigurationBuilderExtensions.cs b/src/libraries/Microsoft.Extensions.Configuration/src/MemoryConfigurationBuilderExtensions.cs index 34998f40101d35..4658728bdc256c 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/src/MemoryConfigurationBuilderExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Configuration/src/MemoryConfigurationBuilderExtensions.cs @@ -19,7 +19,7 @@ public static class MemoryConfigurationBuilderExtensions /// The . public static IConfigurationBuilder AddInMemoryCollection(this IConfigurationBuilder configurationBuilder) { - ThrowHelper.ThrowIfNull(configurationBuilder); + ArgumentNullException.ThrowIfNull(configurationBuilder); configurationBuilder.Add(new MemoryConfigurationSource()); return configurationBuilder; @@ -35,7 +35,7 @@ public static IConfigurationBuilder AddInMemoryCollection( this IConfigurationBuilder configurationBuilder, IEnumerable>? initialData) { - ThrowHelper.ThrowIfNull(configurationBuilder); + ArgumentNullException.ThrowIfNull(configurationBuilder); configurationBuilder.Add(new MemoryConfigurationSource { InitialData = initialData }); return configurationBuilder; diff --git a/src/libraries/Microsoft.Extensions.Configuration/src/MemoryConfigurationProvider.cs b/src/libraries/Microsoft.Extensions.Configuration/src/MemoryConfigurationProvider.cs index 8eea6ba8da34e4..23335c62cb308e 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/src/MemoryConfigurationProvider.cs +++ b/src/libraries/Microsoft.Extensions.Configuration/src/MemoryConfigurationProvider.cs @@ -20,7 +20,7 @@ public class MemoryConfigurationProvider : ConfigurationProvider, IEnumerableThe source settings. public MemoryConfigurationProvider(MemoryConfigurationSource source) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); _source = source; diff --git a/src/libraries/Microsoft.Extensions.Configuration/src/Microsoft.Extensions.Configuration.csproj b/src/libraries/Microsoft.Extensions.Configuration/src/Microsoft.Extensions.Configuration.csproj index 4a0c67d7995964..ea25081d28cd79 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/src/Microsoft.Extensions.Configuration.csproj +++ b/src/libraries/Microsoft.Extensions.Configuration/src/Microsoft.Extensions.Configuration.csproj @@ -1,4 +1,4 @@ - + $(NetCoreAppCurrent);$(NetCoreAppPrevious);$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum) @@ -14,8 +14,6 @@ Link="Common\src\Extensions\ChangeCallbackRegistrar.cs" /> - diff --git a/src/libraries/Microsoft.Extensions.Configuration/src/StreamConfigurationProvider.cs b/src/libraries/Microsoft.Extensions.Configuration/src/StreamConfigurationProvider.cs index be9f40a65a3b08..40aee51b7193b3 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/src/StreamConfigurationProvider.cs +++ b/src/libraries/Microsoft.Extensions.Configuration/src/StreamConfigurationProvider.cs @@ -24,7 +24,7 @@ public abstract class StreamConfigurationProvider : ConfigurationProvider /// The source. public StreamConfigurationProvider(StreamConfigurationSource source) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); Source = source; } diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ActivatorUtilities.cs b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ActivatorUtilities.cs index e61a1c904039ec..652da2fbba0dc3 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ActivatorUtilities.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ActivatorUtilities.cs @@ -49,10 +49,7 @@ public static object CreateInstance( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, params object[] parameters) { - if (provider == null) - { - throw new ArgumentNullException(nameof(provider)); - } + ArgumentNullException.ThrowIfNull(provider); if (instanceType.IsAbstract) { @@ -438,12 +435,6 @@ private static BlockExpression BuildFactoryExpression( } #if NETSTANDARD2_1_OR_GREATER || NET - [DoesNotReturn] - private static void ThrowHelperArgumentNullExceptionServiceProvider() - { - throw new ArgumentNullException("serviceProvider"); - } - private static ObjectFactory CreateFactoryReflection( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type?[] argumentTypes) @@ -932,8 +923,7 @@ private static object ReflectionFactoryServiceOnlyFixed( Debug.Assert(parameters.Length >= 1 && parameters.Length <= FixedArgumentThreshold); Debug.Assert(FixedArgumentThreshold == 4); - if (serviceProvider is null) - ThrowHelperArgumentNullExceptionServiceProvider(); + ArgumentNullException.ThrowIfNull(serviceProvider); switch (parameters.Length) { @@ -969,8 +959,7 @@ private static object ReflectionFactoryServiceOnlySpan( Type declaringType, IServiceProvider serviceProvider) { - if (serviceProvider is null) - ThrowHelperArgumentNullExceptionServiceProvider(); + ArgumentNullException.ThrowIfNull(serviceProvider); object?[] arguments = new object?[parameters.Length]; for (int i = 0; i < parameters.Length; i++) @@ -991,8 +980,7 @@ private static object ReflectionFactoryCanonicalFixed( Debug.Assert(parameters.Length >= 1 && parameters.Length <= FixedArgumentThreshold); Debug.Assert(FixedArgumentThreshold == 4); - if (serviceProvider is null) - ThrowHelperArgumentNullExceptionServiceProvider(); + ArgumentNullException.ThrowIfNull(serviceProvider); ref FactoryParameterContext parameter1 = ref parameters[0]; @@ -1124,8 +1112,7 @@ private static object ReflectionFactoryCanonicalSpan( IServiceProvider serviceProvider, object?[]? arguments) { - if (serviceProvider is null) - ThrowHelperArgumentNullExceptionServiceProvider(); + ArgumentNullException.ThrowIfNull(serviceProvider); object?[] constructorArguments = new object?[parameters.Length]; for (int i = 0; i < parameters.Length; i++) @@ -1150,8 +1137,7 @@ private static object ReflectionFactoryDirect( IServiceProvider serviceProvider, object?[]? arguments) { - if (serviceProvider is null) - ThrowHelperArgumentNullExceptionServiceProvider(); + ArgumentNullException.ThrowIfNull(serviceProvider); if (arguments is null) ThrowHelperNullReferenceException(); //AsSpan() will not throw NullReferenceException. @@ -1175,8 +1161,7 @@ private static object ReflectionFactoryCanonical( IServiceProvider serviceProvider, object?[]? arguments) { - if (serviceProvider is null) - ThrowHelperArgumentNullExceptionServiceProvider(); + ArgumentNullException.ThrowIfNull(serviceProvider); object?[] constructorArguments = new object?[parameters.Length]; for (int i = 0; i < parameters.Length; i++) @@ -1221,7 +1206,7 @@ private struct StackAllocatedObjects private static object? GetKeyedService(IServiceProvider provider, Type type, object? serviceKey) { - ThrowHelper.ThrowIfNull(provider); + ArgumentNullException.ThrowIfNull(provider); if (provider is IKeyedServiceProvider keyedServiceProvider) { diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/AsyncServiceScope.cs b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/AsyncServiceScope.cs index 75df69957c92d3..230ead2bd3eed9 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/AsyncServiceScope.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/AsyncServiceScope.cs @@ -22,7 +22,7 @@ namespace Microsoft.Extensions.DependencyInjection /// The instance to wrap. public AsyncServiceScope(IServiceScope serviceScope) { - ThrowHelper.ThrowIfNull(serviceScope); + ArgumentNullException.ThrowIfNull(serviceScope); _serviceScope = serviceScope; } diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Extensions/ServiceCollectionDescriptorExtensions.Keyed.cs b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Extensions/ServiceCollectionDescriptorExtensions.Keyed.cs index 436f108e5eb5f2..ed317a6cf104c8 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Extensions/ServiceCollectionDescriptorExtensions.Keyed.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Extensions/ServiceCollectionDescriptorExtensions.Keyed.cs @@ -21,8 +21,8 @@ public static void TryAddKeyedTransient( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service, object? serviceKey) { - ThrowHelper.ThrowIfNull(collection); - ThrowHelper.ThrowIfNull(service); + ArgumentNullException.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(service); var descriptor = ServiceDescriptor.KeyedTransient(service, serviceKey, service); ServiceCollectionDescriptorExtensions.TryAdd(collection, descriptor); @@ -43,9 +43,9 @@ public static void TryAddKeyedTransient( object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { - ThrowHelper.ThrowIfNull(collection); - ThrowHelper.ThrowIfNull(service); - ThrowHelper.ThrowIfNull(implementationType); + ArgumentNullException.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(service); + ArgumentNullException.ThrowIfNull(implementationType); var descriptor = ServiceDescriptor.KeyedTransient(service, serviceKey, implementationType); ServiceCollectionDescriptorExtensions.TryAdd(collection, descriptor); @@ -66,9 +66,9 @@ public static void TryAddKeyedTransient( object? serviceKey, Func implementationFactory) { - ThrowHelper.ThrowIfNull(collection); - ThrowHelper.ThrowIfNull(service); - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(service); + ArgumentNullException.ThrowIfNull(implementationFactory); var descriptor = ServiceDescriptor.KeyedTransient(service, serviceKey, implementationFactory); ServiceCollectionDescriptorExtensions.TryAdd(collection, descriptor); @@ -84,7 +84,7 @@ public static void TryAddKeyedTransient( public static void TryAddKeyedTransient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection, object? serviceKey) where TService : class { - ThrowHelper.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(collection); TryAddKeyedTransient(collection, typeof(TService), serviceKey, typeof(TService)); } @@ -102,7 +102,7 @@ public static void TryAddKeyedTransient( where TService : class where TImplementation : class, TService { - ThrowHelper.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(collection); TryAddKeyedTransient(collection, typeof(TService), serviceKey, typeof(TImplementation)); } @@ -137,8 +137,8 @@ public static void TryAddKeyedScoped( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service, object? serviceKey) { - ThrowHelper.ThrowIfNull(collection); - ThrowHelper.ThrowIfNull(service); + ArgumentNullException.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(service); var descriptor = ServiceDescriptor.KeyedScoped(service, serviceKey, service); ServiceCollectionDescriptorExtensions.TryAdd(collection, descriptor); @@ -159,9 +159,9 @@ public static void TryAddKeyedScoped( object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { - ThrowHelper.ThrowIfNull(collection); - ThrowHelper.ThrowIfNull(service); - ThrowHelper.ThrowIfNull(implementationType); + ArgumentNullException.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(service); + ArgumentNullException.ThrowIfNull(implementationType); var descriptor = ServiceDescriptor.KeyedScoped(service, serviceKey, implementationType); ServiceCollectionDescriptorExtensions.TryAdd(collection, descriptor); @@ -182,9 +182,9 @@ public static void TryAddKeyedScoped( object? serviceKey, Func implementationFactory) { - ThrowHelper.ThrowIfNull(collection); - ThrowHelper.ThrowIfNull(service); - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(service); + ArgumentNullException.ThrowIfNull(implementationFactory); var descriptor = ServiceDescriptor.KeyedScoped(service, serviceKey, implementationFactory); ServiceCollectionDescriptorExtensions.TryAdd(collection, descriptor); @@ -200,7 +200,7 @@ public static void TryAddKeyedScoped( public static void TryAddKeyedScoped<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection, object? serviceKey) where TService : class { - ThrowHelper.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(collection); TryAddKeyedScoped(collection, typeof(TService), serviceKey, typeof(TService)); } @@ -218,7 +218,7 @@ public static void TryAddKeyedScoped( where TService : class where TImplementation : class, TService { - ThrowHelper.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(collection); TryAddKeyedScoped(collection, typeof(TService), serviceKey, typeof(TImplementation)); } @@ -253,8 +253,8 @@ public static void TryAddKeyedSingleton( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service, object? serviceKey) { - ThrowHelper.ThrowIfNull(collection); - ThrowHelper.ThrowIfNull(service); + ArgumentNullException.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(service); var descriptor = ServiceDescriptor.KeyedSingleton(service, serviceKey, service); ServiceCollectionDescriptorExtensions.TryAdd(collection, descriptor); @@ -275,9 +275,9 @@ public static void TryAddKeyedSingleton( object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { - ThrowHelper.ThrowIfNull(collection); - ThrowHelper.ThrowIfNull(service); - ThrowHelper.ThrowIfNull(implementationType); + ArgumentNullException.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(service); + ArgumentNullException.ThrowIfNull(implementationType); var descriptor = ServiceDescriptor.KeyedSingleton(service, serviceKey, implementationType); ServiceCollectionDescriptorExtensions.TryAdd(collection, descriptor); @@ -298,9 +298,9 @@ public static void TryAddKeyedSingleton( object? serviceKey, Func implementationFactory) { - ThrowHelper.ThrowIfNull(collection); - ThrowHelper.ThrowIfNull(service); - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(service); + ArgumentNullException.ThrowIfNull(implementationFactory); var descriptor = ServiceDescriptor.KeyedSingleton(service, serviceKey, implementationFactory); ServiceCollectionDescriptorExtensions.TryAdd(collection, descriptor); @@ -316,7 +316,7 @@ public static void TryAddKeyedSingleton( public static void TryAddKeyedSingleton<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection, object? serviceKey) where TService : class { - ThrowHelper.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(collection); TryAddKeyedSingleton(collection, typeof(TService), serviceKey, typeof(TService)); } @@ -334,7 +334,7 @@ public static void TryAddKeyedSingleton( where TService : class where TImplementation : class, TService { - ThrowHelper.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(collection); TryAddKeyedSingleton(collection, typeof(TService), serviceKey, typeof(TImplementation)); } @@ -351,8 +351,8 @@ public static void TryAddKeyedSingleton( public static void TryAddKeyedSingleton(this IServiceCollection collection, object? serviceKey, TService instance) where TService : class { - ThrowHelper.ThrowIfNull(collection); - ThrowHelper.ThrowIfNull(instance); + ArgumentNullException.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(instance); var descriptor = ServiceDescriptor.KeyedSingleton(serviceType: typeof(TService), serviceKey, implementationInstance: instance); ServiceCollectionDescriptorExtensions.TryAdd(collection, descriptor); @@ -396,7 +396,7 @@ public static IServiceCollection RemoveAllKeyed(this IServiceCollection colle /// The for chaining. public static IServiceCollection RemoveAllKeyed(this IServiceCollection collection, Type serviceType, object? serviceKey) { - ThrowHelper.ThrowIfNull(serviceType); + ArgumentNullException.ThrowIfNull(serviceType); for (int i = collection.Count - 1; i >= 0; i--) { diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Extensions/ServiceCollectionDescriptorExtensions.cs b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Extensions/ServiceCollectionDescriptorExtensions.cs index f8661d5565f1a4..5e2f500d76581a 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Extensions/ServiceCollectionDescriptorExtensions.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Extensions/ServiceCollectionDescriptorExtensions.cs @@ -22,8 +22,8 @@ public static IServiceCollection Add( this IServiceCollection collection, ServiceDescriptor descriptor) { - ThrowHelper.ThrowIfNull(collection); - ThrowHelper.ThrowIfNull(descriptor); + ArgumentNullException.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(descriptor); collection.Add(descriptor); return collection; @@ -39,8 +39,8 @@ public static IServiceCollection Add( this IServiceCollection collection, IEnumerable descriptors) { - ThrowHelper.ThrowIfNull(collection); - ThrowHelper.ThrowIfNull(descriptors); + ArgumentNullException.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(descriptors); foreach (ServiceDescriptor? descriptor in descriptors) { @@ -60,8 +60,8 @@ public static void TryAdd( this IServiceCollection collection, ServiceDescriptor descriptor) { - ThrowHelper.ThrowIfNull(collection); - ThrowHelper.ThrowIfNull(descriptor); + ArgumentNullException.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(descriptor); int count = collection.Count; for (int i = 0; i < count; i++) @@ -87,8 +87,8 @@ public static void TryAdd( this IServiceCollection collection, IEnumerable descriptors) { - ThrowHelper.ThrowIfNull(collection); - ThrowHelper.ThrowIfNull(descriptors); + ArgumentNullException.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(descriptors); foreach (ServiceDescriptor? d in descriptors) { @@ -106,8 +106,8 @@ public static void TryAddTransient( this IServiceCollection collection, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service) { - ThrowHelper.ThrowIfNull(collection); - ThrowHelper.ThrowIfNull(service); + ArgumentNullException.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(service); var descriptor = ServiceDescriptor.Transient(service, service); TryAdd(collection, descriptor); @@ -126,9 +126,9 @@ public static void TryAddTransient( Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { - ThrowHelper.ThrowIfNull(collection); - ThrowHelper.ThrowIfNull(service); - ThrowHelper.ThrowIfNull(implementationType); + ArgumentNullException.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(service); + ArgumentNullException.ThrowIfNull(implementationType); var descriptor = ServiceDescriptor.Transient(service, implementationType); TryAdd(collection, descriptor); @@ -147,9 +147,9 @@ public static void TryAddTransient( Type service, Func implementationFactory) { - ThrowHelper.ThrowIfNull(collection); - ThrowHelper.ThrowIfNull(service); - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(service); + ArgumentNullException.ThrowIfNull(implementationFactory); var descriptor = ServiceDescriptor.Transient(service, implementationFactory); TryAdd(collection, descriptor); @@ -164,7 +164,7 @@ public static void TryAddTransient( public static void TryAddTransient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection) where TService : class { - ThrowHelper.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(collection); TryAddTransient(collection, typeof(TService), typeof(TService)); } @@ -181,7 +181,7 @@ public static void TryAddTransient( where TService : class where TImplementation : class, TService { - ThrowHelper.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(collection); TryAddTransient(collection, typeof(TService), typeof(TImplementation)); } @@ -212,8 +212,8 @@ public static void TryAddScoped( this IServiceCollection collection, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service) { - ThrowHelper.ThrowIfNull(collection); - ThrowHelper.ThrowIfNull(service); + ArgumentNullException.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(service); var descriptor = ServiceDescriptor.Scoped(service, service); TryAdd(collection, descriptor); @@ -232,9 +232,9 @@ public static void TryAddScoped( Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { - ThrowHelper.ThrowIfNull(collection); - ThrowHelper.ThrowIfNull(service); - ThrowHelper.ThrowIfNull(implementationType); + ArgumentNullException.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(service); + ArgumentNullException.ThrowIfNull(implementationType); var descriptor = ServiceDescriptor.Scoped(service, implementationType); TryAdd(collection, descriptor); @@ -253,9 +253,9 @@ public static void TryAddScoped( Type service, Func implementationFactory) { - ThrowHelper.ThrowIfNull(collection); - ThrowHelper.ThrowIfNull(service); - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(service); + ArgumentNullException.ThrowIfNull(implementationFactory); var descriptor = ServiceDescriptor.Scoped(service, implementationFactory); TryAdd(collection, descriptor); @@ -270,7 +270,7 @@ public static void TryAddScoped( public static void TryAddScoped<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection) where TService : class { - ThrowHelper.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(collection); TryAddScoped(collection, typeof(TService), typeof(TService)); } @@ -287,7 +287,7 @@ public static void TryAddScoped( where TService : class where TImplementation : class, TService { - ThrowHelper.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(collection); TryAddScoped(collection, typeof(TService), typeof(TImplementation)); } @@ -318,8 +318,8 @@ public static void TryAddSingleton( this IServiceCollection collection, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service) { - ThrowHelper.ThrowIfNull(collection); - ThrowHelper.ThrowIfNull(service); + ArgumentNullException.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(service); var descriptor = ServiceDescriptor.Singleton(service, service); TryAdd(collection, descriptor); @@ -338,9 +338,9 @@ public static void TryAddSingleton( Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { - ThrowHelper.ThrowIfNull(collection); - ThrowHelper.ThrowIfNull(service); - ThrowHelper.ThrowIfNull(implementationType); + ArgumentNullException.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(service); + ArgumentNullException.ThrowIfNull(implementationType); var descriptor = ServiceDescriptor.Singleton(service, implementationType); TryAdd(collection, descriptor); @@ -359,9 +359,9 @@ public static void TryAddSingleton( Type service, Func implementationFactory) { - ThrowHelper.ThrowIfNull(collection); - ThrowHelper.ThrowIfNull(service); - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(service); + ArgumentNullException.ThrowIfNull(implementationFactory); var descriptor = ServiceDescriptor.Singleton(service, implementationFactory); TryAdd(collection, descriptor); @@ -376,7 +376,7 @@ public static void TryAddSingleton( public static void TryAddSingleton<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection) where TService : class { - ThrowHelper.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(collection); TryAddSingleton(collection, typeof(TService), typeof(TService)); } @@ -393,7 +393,7 @@ public static void TryAddSingleton( where TService : class where TImplementation : class, TService { - ThrowHelper.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(collection); TryAddSingleton(collection, typeof(TService), typeof(TImplementation)); } @@ -409,8 +409,8 @@ public static void TryAddSingleton( public static void TryAddSingleton(this IServiceCollection collection, TService instance) where TService : class { - ThrowHelper.ThrowIfNull(collection); - ThrowHelper.ThrowIfNull(instance); + ArgumentNullException.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(instance); var descriptor = ServiceDescriptor.Singleton(serviceType: typeof(TService), implementationInstance: instance); TryAdd(collection, descriptor); @@ -453,8 +453,8 @@ public static void TryAddEnumerable( this IServiceCollection services, ServiceDescriptor descriptor) { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(descriptor); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(descriptor); Type? implementationType = descriptor.GetImplementationType(); @@ -505,8 +505,8 @@ public static void TryAddEnumerable( this IServiceCollection services, IEnumerable descriptors) { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(descriptors); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(descriptors); foreach (ServiceDescriptor? d in descriptors) { @@ -525,8 +525,8 @@ public static IServiceCollection Replace( this IServiceCollection collection, ServiceDescriptor descriptor) { - ThrowHelper.ThrowIfNull(collection); - ThrowHelper.ThrowIfNull(descriptor); + ArgumentNullException.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(descriptor); // Remove existing int count = collection.Count; @@ -561,7 +561,7 @@ public static IServiceCollection RemoveAll(this IServiceCollection collection /// The for chaining. public static IServiceCollection RemoveAll(this IServiceCollection collection, Type serviceType) { - ThrowHelper.ThrowIfNull(serviceType); + ArgumentNullException.ThrowIfNull(serviceType); for (int i = collection.Count - 1; i >= 0; i--) { diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Microsoft.Extensions.DependencyInjection.Abstractions.csproj b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Microsoft.Extensions.DependencyInjection.Abstractions.csproj index 8042e453a1d349..052e8a512402b2 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Microsoft.Extensions.DependencyInjection.Abstractions.csproj +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Microsoft.Extensions.DependencyInjection.Abstractions.csproj @@ -13,8 +13,6 @@ Microsoft.Extensions.DependencyInjection.IServiceCollection - diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceCollectionServiceExtensions.Keyed.cs b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceCollectionServiceExtensions.Keyed.cs index 1f1f1cef1a4e8c..791c8b172ba11d 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceCollectionServiceExtensions.Keyed.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceCollectionServiceExtensions.Keyed.cs @@ -28,9 +28,9 @@ public static IServiceCollection AddKeyedTransient( object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(serviceType); - ThrowHelper.ThrowIfNull(implementationType); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(serviceType); + ArgumentNullException.ThrowIfNull(implementationType); return AddKeyed(services, serviceType, serviceKey, implementationType, ServiceLifetime.Transient); } @@ -52,9 +52,9 @@ public static IServiceCollection AddKeyedTransient( object? serviceKey, Func implementationFactory) { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(serviceType); - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(serviceType); + ArgumentNullException.ThrowIfNull(implementationFactory); return AddKeyed(services, serviceType, serviceKey, implementationFactory, ServiceLifetime.Transient); } @@ -76,7 +76,7 @@ public static IServiceCollection AddKeyedTransient( where TService : class where TImplementation : class, TService { - ThrowHelper.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(services); return services.AddKeyedTransient(typeof(TService), serviceKey, typeof(TImplementation)); } @@ -95,8 +95,8 @@ public static IServiceCollection AddKeyedTransient( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType, object? serviceKey) { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(serviceType); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(serviceType); return services.AddKeyedTransient(serviceType, serviceKey, serviceType); } @@ -115,7 +115,7 @@ public static IServiceCollection AddKeyedTransient( object? serviceKey) where TService : class { - ThrowHelper.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(services); return services.AddKeyedTransient(typeof(TService), serviceKey); } @@ -137,8 +137,8 @@ public static IServiceCollection AddKeyedTransient( Func implementationFactory) where TService : class { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(implementationFactory); return services.AddKeyedTransient(typeof(TService), serviceKey, implementationFactory); } @@ -163,8 +163,8 @@ public static IServiceCollection AddKeyedTransient( where TService : class where TImplementation : class, TService { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(implementationFactory); return services.AddKeyedTransient(typeof(TService), serviceKey, implementationFactory); } @@ -186,9 +186,9 @@ public static IServiceCollection AddKeyedScoped( object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(serviceType); - ThrowHelper.ThrowIfNull(implementationType); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(serviceType); + ArgumentNullException.ThrowIfNull(implementationType); return AddKeyed(services, serviceType, serviceKey, implementationType, ServiceLifetime.Scoped); } @@ -210,9 +210,9 @@ public static IServiceCollection AddKeyedScoped( object? serviceKey, Func implementationFactory) { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(serviceType); - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(serviceType); + ArgumentNullException.ThrowIfNull(implementationFactory); return AddKeyed(services, serviceType, serviceKey, implementationFactory, ServiceLifetime.Scoped); } @@ -234,7 +234,7 @@ public static IServiceCollection AddKeyedScoped( where TService : class where TImplementation : class, TService { - ThrowHelper.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(services); return services.AddKeyedScoped(typeof(TService), serviceKey, typeof(TImplementation)); } @@ -253,8 +253,8 @@ public static IServiceCollection AddKeyedScoped( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType, object? serviceKey) { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(serviceType); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(serviceType); return services.AddKeyedScoped(serviceType, serviceKey, serviceType); } @@ -273,7 +273,7 @@ public static IServiceCollection AddKeyedScoped( object? serviceKey) where TService : class { - ThrowHelper.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(services); return services.AddKeyedScoped(typeof(TService), serviceKey); } @@ -295,8 +295,8 @@ public static IServiceCollection AddKeyedScoped( Func implementationFactory) where TService : class { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(implementationFactory); return services.AddKeyedScoped(typeof(TService), serviceKey, implementationFactory); } @@ -321,8 +321,8 @@ public static IServiceCollection AddKeyedScoped( where TService : class where TImplementation : class, TService { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(implementationFactory); return services.AddKeyedScoped(typeof(TService), serviceKey, implementationFactory); } @@ -344,9 +344,9 @@ public static IServiceCollection AddKeyedSingleton( object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(serviceType); - ThrowHelper.ThrowIfNull(implementationType); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(serviceType); + ArgumentNullException.ThrowIfNull(implementationType); return AddKeyed(services, serviceType, serviceKey, implementationType, ServiceLifetime.Singleton); } @@ -368,9 +368,9 @@ public static IServiceCollection AddKeyedSingleton( object? serviceKey, Func implementationFactory) { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(serviceType); - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(serviceType); + ArgumentNullException.ThrowIfNull(implementationFactory); return AddKeyed(services, serviceType, serviceKey, implementationFactory, ServiceLifetime.Singleton); } @@ -392,7 +392,7 @@ public static IServiceCollection AddKeyedSingleton( where TService : class where TImplementation : class, TService { - ThrowHelper.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(services); return services.AddKeyedSingleton(typeof(TService), serviceKey, typeof(TImplementation)); } @@ -411,8 +411,8 @@ public static IServiceCollection AddKeyedSingleton( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType, object? serviceKey) { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(serviceType); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(serviceType); return services.AddKeyedSingleton(serviceType, serviceKey, serviceType); } @@ -431,7 +431,7 @@ public static IServiceCollection AddKeyedSingleton( object? serviceKey) where TService : class { - ThrowHelper.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(services); return services.AddKeyedSingleton(typeof(TService), serviceKey, typeof(TService)); } @@ -453,8 +453,8 @@ public static IServiceCollection AddKeyedSingleton( Func implementationFactory) where TService : class { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(implementationFactory); return services.AddKeyedSingleton(typeof(TService), serviceKey, implementationFactory); } @@ -479,8 +479,8 @@ public static IServiceCollection AddKeyedSingleton( where TService : class where TImplementation : class, TService { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(implementationFactory); return services.AddKeyedSingleton(typeof(TService), serviceKey, implementationFactory); } @@ -502,9 +502,9 @@ public static IServiceCollection AddKeyedSingleton( object? serviceKey, object implementationInstance) { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(serviceType); - ThrowHelper.ThrowIfNull(implementationInstance); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(serviceType); + ArgumentNullException.ThrowIfNull(implementationInstance); var serviceDescriptor = new ServiceDescriptor(serviceType, serviceKey, implementationInstance); services.Add(serviceDescriptor); @@ -527,8 +527,8 @@ public static IServiceCollection AddKeyedSingleton( TService implementationInstance) where TService : class { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(implementationInstance); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(implementationInstance); return services.AddKeyedSingleton(typeof(TService), serviceKey, implementationInstance); } diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceCollectionServiceExtensions.cs b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceCollectionServiceExtensions.cs index 15427514a23f7d..f78df8af8a6d89 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceCollectionServiceExtensions.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceCollectionServiceExtensions.cs @@ -26,9 +26,9 @@ public static IServiceCollection AddTransient( Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(serviceType); - ThrowHelper.ThrowIfNull(implementationType); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(serviceType); + ArgumentNullException.ThrowIfNull(implementationType); return Add(services, serviceType, implementationType, ServiceLifetime.Transient); } @@ -48,9 +48,9 @@ public static IServiceCollection AddTransient( Type serviceType, Func implementationFactory) { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(serviceType); - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(serviceType); + ArgumentNullException.ThrowIfNull(implementationFactory); return Add(services, serviceType, implementationFactory, ServiceLifetime.Transient); } @@ -69,7 +69,7 @@ public static IServiceCollection AddTransient( where TService : class where TImplementation : class, TService { - ThrowHelper.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(services); return services.AddTransient(typeof(TService), typeof(TImplementation)); } @@ -86,8 +86,8 @@ public static IServiceCollection AddTransient( this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType) { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(serviceType); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(serviceType); return services.AddTransient(serviceType, serviceType); } @@ -103,7 +103,7 @@ public static IServiceCollection AddTransient( public static IServiceCollection AddTransient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services) where TService : class { - ThrowHelper.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(services); return services.AddTransient(typeof(TService)); } @@ -123,8 +123,8 @@ public static IServiceCollection AddTransient( Func implementationFactory) where TService : class { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(implementationFactory); return services.AddTransient(typeof(TService), implementationFactory); } @@ -147,8 +147,8 @@ public static IServiceCollection AddTransient( where TService : class where TImplementation : class, TService { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(implementationFactory); return services.AddTransient(typeof(TService), implementationFactory); } @@ -168,9 +168,9 @@ public static IServiceCollection AddScoped( Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(serviceType); - ThrowHelper.ThrowIfNull(implementationType); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(serviceType); + ArgumentNullException.ThrowIfNull(implementationType); return Add(services, serviceType, implementationType, ServiceLifetime.Scoped); } @@ -190,9 +190,9 @@ public static IServiceCollection AddScoped( Type serviceType, Func implementationFactory) { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(serviceType); - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(serviceType); + ArgumentNullException.ThrowIfNull(implementationFactory); return Add(services, serviceType, implementationFactory, ServiceLifetime.Scoped); } @@ -211,7 +211,7 @@ public static IServiceCollection AddScoped( where TService : class where TImplementation : class, TService { - ThrowHelper.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(services); return services.AddScoped(typeof(TService), typeof(TImplementation)); } @@ -228,8 +228,8 @@ public static IServiceCollection AddScoped( this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType) { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(serviceType); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(serviceType); return services.AddScoped(serviceType, serviceType); } @@ -245,7 +245,7 @@ public static IServiceCollection AddScoped( public static IServiceCollection AddScoped<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services) where TService : class { - ThrowHelper.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(services); return services.AddScoped(typeof(TService)); } @@ -265,8 +265,8 @@ public static IServiceCollection AddScoped( Func implementationFactory) where TService : class { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(implementationFactory); return services.AddScoped(typeof(TService), implementationFactory); } @@ -289,8 +289,8 @@ public static IServiceCollection AddScoped( where TService : class where TImplementation : class, TService { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(implementationFactory); return services.AddScoped(typeof(TService), implementationFactory); } @@ -311,9 +311,9 @@ public static IServiceCollection AddSingleton( Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(serviceType); - ThrowHelper.ThrowIfNull(implementationType); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(serviceType); + ArgumentNullException.ThrowIfNull(implementationType); return Add(services, serviceType, implementationType, ServiceLifetime.Singleton); } @@ -333,9 +333,9 @@ public static IServiceCollection AddSingleton( Type serviceType, Func implementationFactory) { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(serviceType); - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(serviceType); + ArgumentNullException.ThrowIfNull(implementationFactory); return Add(services, serviceType, implementationFactory, ServiceLifetime.Singleton); } @@ -354,7 +354,7 @@ public static IServiceCollection AddSingleton( where TService : class where TImplementation : class, TService { - ThrowHelper.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(services); return services.AddSingleton(typeof(TService), typeof(TImplementation)); } @@ -371,8 +371,8 @@ public static IServiceCollection AddSingleton( this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType) { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(serviceType); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(serviceType); return services.AddSingleton(serviceType, serviceType); } @@ -388,7 +388,7 @@ public static IServiceCollection AddSingleton( public static IServiceCollection AddSingleton<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services) where TService : class { - ThrowHelper.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(services); return services.AddSingleton(typeof(TService)); } @@ -408,8 +408,8 @@ public static IServiceCollection AddSingleton( Func implementationFactory) where TService : class { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(implementationFactory); return services.AddSingleton(typeof(TService), implementationFactory); } @@ -432,8 +432,8 @@ public static IServiceCollection AddSingleton( where TService : class where TImplementation : class, TService { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(implementationFactory); return services.AddSingleton(typeof(TService), implementationFactory); } @@ -453,9 +453,9 @@ public static IServiceCollection AddSingleton( Type serviceType, object implementationInstance) { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(serviceType); - ThrowHelper.ThrowIfNull(implementationInstance); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(serviceType); + ArgumentNullException.ThrowIfNull(implementationInstance); var serviceDescriptor = new ServiceDescriptor(serviceType, implementationInstance); services.Add(serviceDescriptor); @@ -476,8 +476,8 @@ public static IServiceCollection AddSingleton( TService implementationInstance) where TService : class { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(implementationInstance); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(implementationInstance); return services.AddSingleton(typeof(TService), implementationInstance); } diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceDescriptor.cs b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceDescriptor.cs index d90f76f25a2111..19d5aa38c99dfa 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceDescriptor.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceDescriptor.cs @@ -42,8 +42,8 @@ public ServiceDescriptor( ServiceLifetime lifetime) : this(serviceType, serviceKey, lifetime) { - ThrowHelper.ThrowIfNull(serviceType); - ThrowHelper.ThrowIfNull(implementationType); + ArgumentNullException.ThrowIfNull(serviceType); + ArgumentNullException.ThrowIfNull(implementationType); _implementationType = implementationType; } @@ -74,8 +74,8 @@ public ServiceDescriptor( object instance) : this(serviceType, serviceKey, ServiceLifetime.Singleton) { - ThrowHelper.ThrowIfNull(serviceType); - ThrowHelper.ThrowIfNull(instance); + ArgumentNullException.ThrowIfNull(serviceType); + ArgumentNullException.ThrowIfNull(instance); _implementationInstance = instance; } @@ -92,8 +92,8 @@ public ServiceDescriptor( ServiceLifetime lifetime) : this(serviceType, serviceKey: null, lifetime) { - ThrowHelper.ThrowIfNull(serviceType); - ThrowHelper.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(serviceType); + ArgumentNullException.ThrowIfNull(factory); _implementationFactory = factory; } @@ -112,8 +112,8 @@ public ServiceDescriptor( ServiceLifetime lifetime) : this(serviceType, serviceKey, lifetime) { - ThrowHelper.ThrowIfNull(serviceType); - ThrowHelper.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(serviceType); + ArgumentNullException.ThrowIfNull(factory); if (serviceKey is null) { @@ -392,8 +392,8 @@ public static ServiceDescriptor Transient( Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { - ThrowHelper.ThrowIfNull(service); - ThrowHelper.ThrowIfNull(implementationType); + ArgumentNullException.ThrowIfNull(service); + ArgumentNullException.ThrowIfNull(implementationType); return Describe(service, implementationType, ServiceLifetime.Transient); } @@ -412,8 +412,8 @@ public static ServiceDescriptor KeyedTransient( object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { - ThrowHelper.ThrowIfNull(service); - ThrowHelper.ThrowIfNull(implementationType); + ArgumentNullException.ThrowIfNull(service); + ArgumentNullException.ThrowIfNull(implementationType); return DescribeKeyed(service, serviceKey, implementationType, ServiceLifetime.Transient); } @@ -433,7 +433,7 @@ public static ServiceDescriptor Transient( where TService : class where TImplementation : class, TService { - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(implementationFactory); return Describe(typeof(TService), implementationFactory, ServiceLifetime.Transient); } @@ -455,7 +455,7 @@ public static ServiceDescriptor KeyedTransient( where TService : class where TImplementation : class, TService { - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(implementationFactory); return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Transient); } @@ -471,7 +471,7 @@ public static ServiceDescriptor KeyedTransient( public static ServiceDescriptor Transient(Func implementationFactory) where TService : class { - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(implementationFactory); return Describe(typeof(TService), implementationFactory, ServiceLifetime.Transient); } @@ -488,7 +488,7 @@ public static ServiceDescriptor Transient(Func(object? serviceKey, Func implementationFactory) where TService : class { - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(implementationFactory); return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Transient); } @@ -503,8 +503,8 @@ public static ServiceDescriptor KeyedTransient(object? serviceKey, Fun /// A new instance of . public static ServiceDescriptor Transient(Type service, Func implementationFactory) { - ThrowHelper.ThrowIfNull(service); - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(service); + ArgumentNullException.ThrowIfNull(implementationFactory); return Describe(service, implementationFactory, ServiceLifetime.Transient); } @@ -520,8 +520,8 @@ public static ServiceDescriptor Transient(Type service, FuncA new instance of . public static ServiceDescriptor KeyedTransient(Type service, object? serviceKey, Func implementationFactory) { - ThrowHelper.ThrowIfNull(service); - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(service); + ArgumentNullException.ThrowIfNull(implementationFactory); return DescribeKeyed(service, serviceKey, implementationFactory, ServiceLifetime.Transient); } @@ -604,7 +604,7 @@ public static ServiceDescriptor Scoped( where TService : class where TImplementation : class, TService { - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(implementationFactory); return Describe(typeof(TService), implementationFactory, ServiceLifetime.Scoped); } @@ -626,7 +626,7 @@ public static ServiceDescriptor KeyedScoped( where TService : class where TImplementation : class, TService { - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(implementationFactory); return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Scoped); } @@ -642,7 +642,7 @@ public static ServiceDescriptor KeyedScoped( public static ServiceDescriptor Scoped(Func implementationFactory) where TService : class { - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(implementationFactory); return Describe(typeof(TService), implementationFactory, ServiceLifetime.Scoped); } @@ -659,7 +659,7 @@ public static ServiceDescriptor Scoped(Func(object? serviceKey, Func implementationFactory) where TService : class { - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(implementationFactory); return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Scoped); } @@ -674,8 +674,8 @@ public static ServiceDescriptor KeyedScoped(object? serviceKey, FuncA new instance of . public static ServiceDescriptor Scoped(Type service, Func implementationFactory) { - ThrowHelper.ThrowIfNull(service); - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(service); + ArgumentNullException.ThrowIfNull(implementationFactory); return Describe(service, implementationFactory, ServiceLifetime.Scoped); } @@ -691,8 +691,8 @@ public static ServiceDescriptor Scoped(Type service, FuncA new instance of . public static ServiceDescriptor KeyedScoped(Type service, object? serviceKey, Func implementationFactory) { - ThrowHelper.ThrowIfNull(service); - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(service); + ArgumentNullException.ThrowIfNull(implementationFactory); return DescribeKeyed(service, serviceKey, implementationFactory, ServiceLifetime.Scoped); } @@ -741,8 +741,8 @@ public static ServiceDescriptor Singleton( Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { - ThrowHelper.ThrowIfNull(service); - ThrowHelper.ThrowIfNull(implementationType); + ArgumentNullException.ThrowIfNull(service); + ArgumentNullException.ThrowIfNull(implementationType); return Describe(service, implementationType, ServiceLifetime.Singleton); } @@ -761,8 +761,8 @@ public static ServiceDescriptor KeyedSingleton( object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { - ThrowHelper.ThrowIfNull(service); - ThrowHelper.ThrowIfNull(implementationType); + ArgumentNullException.ThrowIfNull(service); + ArgumentNullException.ThrowIfNull(implementationType); return DescribeKeyed(service, serviceKey, implementationType, ServiceLifetime.Singleton); } @@ -782,7 +782,7 @@ public static ServiceDescriptor Singleton( where TService : class where TImplementation : class, TService { - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(implementationFactory); return Describe(typeof(TService), implementationFactory, ServiceLifetime.Singleton); } @@ -804,7 +804,7 @@ public static ServiceDescriptor KeyedSingleton( where TService : class where TImplementation : class, TService { - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(implementationFactory); return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Singleton); } @@ -820,7 +820,7 @@ public static ServiceDescriptor KeyedSingleton( public static ServiceDescriptor Singleton(Func implementationFactory) where TService : class { - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(implementationFactory); return Describe(typeof(TService), implementationFactory, ServiceLifetime.Singleton); } @@ -839,7 +839,7 @@ public static ServiceDescriptor KeyedSingleton( Func implementationFactory) where TService : class { - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(implementationFactory); return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Singleton); } @@ -856,8 +856,8 @@ public static ServiceDescriptor Singleton( Type serviceType, Func implementationFactory) { - ThrowHelper.ThrowIfNull(serviceType); - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(serviceType); + ArgumentNullException.ThrowIfNull(implementationFactory); return Describe(serviceType, implementationFactory, ServiceLifetime.Singleton); } @@ -876,8 +876,8 @@ public static ServiceDescriptor KeyedSingleton( object? serviceKey, Func implementationFactory) { - ThrowHelper.ThrowIfNull(serviceType); - ThrowHelper.ThrowIfNull(implementationFactory); + ArgumentNullException.ThrowIfNull(serviceType); + ArgumentNullException.ThrowIfNull(implementationFactory); return DescribeKeyed(serviceType, serviceKey, implementationFactory, ServiceLifetime.Singleton); } @@ -893,7 +893,7 @@ public static ServiceDescriptor KeyedSingleton( public static ServiceDescriptor Singleton(TService implementationInstance) where TService : class { - ThrowHelper.ThrowIfNull(implementationInstance); + ArgumentNullException.ThrowIfNull(implementationInstance); return Singleton(serviceType: typeof(TService), implementationInstance: implementationInstance); } @@ -912,7 +912,7 @@ public static ServiceDescriptor KeyedSingleton( TService implementationInstance) where TService : class { - ThrowHelper.ThrowIfNull(implementationInstance); + ArgumentNullException.ThrowIfNull(implementationInstance); return KeyedSingleton(typeof(TService), serviceKey, implementationInstance); } @@ -929,8 +929,8 @@ public static ServiceDescriptor Singleton( Type serviceType, object implementationInstance) { - ThrowHelper.ThrowIfNull(serviceType); - ThrowHelper.ThrowIfNull(implementationInstance); + ArgumentNullException.ThrowIfNull(serviceType); + ArgumentNullException.ThrowIfNull(implementationInstance); return new ServiceDescriptor(serviceType, implementationInstance); } @@ -949,8 +949,8 @@ public static ServiceDescriptor KeyedSingleton( object? serviceKey, object implementationInstance) { - ThrowHelper.ThrowIfNull(serviceType); - ThrowHelper.ThrowIfNull(implementationInstance); + ArgumentNullException.ThrowIfNull(serviceType); + ArgumentNullException.ThrowIfNull(implementationInstance); return new ServiceDescriptor(serviceType, serviceKey, implementationInstance); } diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceProviderKeyedServiceExtensions.cs b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceProviderKeyedServiceExtensions.cs index 03075fbc9c2e69..094fa4551c844f 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceProviderKeyedServiceExtensions.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceProviderKeyedServiceExtensions.cs @@ -21,7 +21,7 @@ public static class ServiceProviderKeyedServiceExtensions /// A service object of type or null if there is no such service. public static T? GetKeyedService(this IServiceProvider provider, object? serviceKey) { - ThrowHelper.ThrowIfNull(provider); + ArgumentNullException.ThrowIfNull(provider); if (provider is IKeyedServiceProvider keyedServiceProvider) { @@ -40,8 +40,8 @@ public static class ServiceProviderKeyedServiceExtensions /// A service object of type or null if there is no such service. public static object? GetKeyedService(this IServiceProvider provider, Type serviceType, object? serviceKey) { - ThrowHelper.ThrowIfNull(provider); - ThrowHelper.ThrowIfNull(serviceType); + ArgumentNullException.ThrowIfNull(provider); + ArgumentNullException.ThrowIfNull(serviceType); if (provider is IKeyedServiceProvider keyedServiceProvider) { @@ -61,8 +61,8 @@ public static class ServiceProviderKeyedServiceExtensions /// There is no service of type . public static object GetRequiredKeyedService(this IServiceProvider provider, Type serviceType, object? serviceKey) { - ThrowHelper.ThrowIfNull(provider); - ThrowHelper.ThrowIfNull(serviceType); + ArgumentNullException.ThrowIfNull(provider); + ArgumentNullException.ThrowIfNull(serviceType); if (provider is IKeyedServiceProvider requiredServiceSupportingProvider) { @@ -82,7 +82,7 @@ public static object GetRequiredKeyedService(this IServiceProvider provider, Typ /// There is no service of type . public static T GetRequiredKeyedService(this IServiceProvider provider, object? serviceKey) where T : notnull { - ThrowHelper.ThrowIfNull(provider); + ArgumentNullException.ThrowIfNull(provider); return (T)provider.GetRequiredKeyedService(typeof(T), serviceKey); } @@ -96,7 +96,7 @@ public static T GetRequiredKeyedService(this IServiceProvider provider, objec /// An enumeration of services of type . public static IEnumerable GetKeyedServices(this IServiceProvider provider, object? serviceKey) { - ThrowHelper.ThrowIfNull(provider); + ArgumentNullException.ThrowIfNull(provider); return provider.GetRequiredKeyedService>(serviceKey); } @@ -111,8 +111,8 @@ public static IEnumerable GetKeyedServices(this IServiceProvider provider, [RequiresDynamicCode("The native code for an IEnumerable might not be available at runtime.")] public static IEnumerable GetKeyedServices(this IServiceProvider provider, Type serviceType, object? serviceKey) { - ThrowHelper.ThrowIfNull(provider); - ThrowHelper.ThrowIfNull(serviceType); + ArgumentNullException.ThrowIfNull(provider); + ArgumentNullException.ThrowIfNull(serviceType); Type? genericEnumerable = typeof(IEnumerable<>).MakeGenericType(serviceType); return (IEnumerable)provider.GetRequiredKeyedService(genericEnumerable, serviceKey); diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceProviderServiceExtensions.cs b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceProviderServiceExtensions.cs index f3a15fde1a6ef8..927834f22c77d5 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceProviderServiceExtensions.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceProviderServiceExtensions.cs @@ -20,7 +20,7 @@ public static class ServiceProviderServiceExtensions /// A service object of type or null if there is no such service. public static T? GetService(this IServiceProvider provider) { - ThrowHelper.ThrowIfNull(provider); + ArgumentNullException.ThrowIfNull(provider); return (T?)provider.GetService(typeof(T)); } @@ -34,8 +34,8 @@ public static class ServiceProviderServiceExtensions /// There is no service of type . public static object GetRequiredService(this IServiceProvider provider, Type serviceType) { - ThrowHelper.ThrowIfNull(provider); - ThrowHelper.ThrowIfNull(serviceType); + ArgumentNullException.ThrowIfNull(provider); + ArgumentNullException.ThrowIfNull(serviceType); if (provider is ISupportRequiredService requiredServiceSupportingProvider) { @@ -60,7 +60,7 @@ public static object GetRequiredService(this IServiceProvider provider, Type ser /// There is no service of type . public static T GetRequiredService(this IServiceProvider provider) where T : notnull { - ThrowHelper.ThrowIfNull(provider); + ArgumentNullException.ThrowIfNull(provider); return (T)provider.GetRequiredService(typeof(T)); } @@ -73,7 +73,7 @@ public static T GetRequiredService(this IServiceProvider provider) where T : /// An enumeration of services of type . public static IEnumerable GetServices(this IServiceProvider provider) { - ThrowHelper.ThrowIfNull(provider); + ArgumentNullException.ThrowIfNull(provider); return provider.GetRequiredService>(); } @@ -87,8 +87,8 @@ public static IEnumerable GetServices(this IServiceProvider provider) [RequiresDynamicCode("The native code for an IEnumerable might not be available at runtime.")] public static IEnumerable GetServices(this IServiceProvider provider, Type serviceType) { - ThrowHelper.ThrowIfNull(provider); - ThrowHelper.ThrowIfNull(serviceType); + ArgumentNullException.ThrowIfNull(provider); + ArgumentNullException.ThrowIfNull(serviceType); Type? genericEnumerable = typeof(IEnumerable<>).MakeGenericType(serviceType); return (IEnumerable)provider.GetRequiredService(genericEnumerable); diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/Microsoft.Extensions.DependencyInjection.sln b/src/libraries/Microsoft.Extensions.DependencyInjection/Microsoft.Extensions.DependencyInjection.sln index 31a6a2c833475a..7768bc618cc9e8 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection/Microsoft.Extensions.DependencyInjection.sln +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/Microsoft.Extensions.DependencyInjection.sln @@ -1,4 +1,8 @@ -Microsoft Visual Studio Solution File, Format Version 12.00 + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.14.36008.106 +MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestUtilities", "..\Common\tests\TestUtilities\TestUtilities.csproj", "{30201F60-A891-4C3F-A1A6-DDDD1C8525E3}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Bcl.AsyncInterfaces", "..\Microsoft.Bcl.AsyncInterfaces\src\Microsoft.Bcl.AsyncInterfaces.csproj", "{3068B34E-D975-4C11-B2F2-F10790051F2E}" @@ -41,11 +45,11 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ref", "ref", "{E168C5B8-F2E EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "gen", "gen", "{28065F40-B930-4A5D-95D8-A3BD5F86CE11}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "gen", "tools\gen", "{0B56ECAF-7B4A-4135-A343-1577ACE09920}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "gen", "gen", "{0B56ECAF-7B4A-4135-A343-1577ACE09920}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "tools\src", "{5DD887A4-ED78-4782-B372-34176C27F0C1}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{5DD887A4-ED78-4782-B372-34176C27F0C1}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ref", "tools\ref", "{6FA0C03B-0901-4FD8-AF44-D4C9E5516C2F}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ref", "ref", "{6FA0C03B-0901-4FD8-AF44-D4C9E5516C2F}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tools", "tools", "{D6F10CF9-982E-4D09-A112-0CBFD2D46AFF}" EndProject @@ -129,27 +133,31 @@ Global EndGlobalSection GlobalSection(NestedProjects) = preSolution {30201F60-A891-4C3F-A1A6-DDDD1C8525E3} = {5F2D3A6A-76D3-4C22-A7F7-8D73D67A98F8} - {2C6983BB-3CB4-4EB7-9AF1-2F24FE1ECEAB} = {5F2D3A6A-76D3-4C22-A7F7-8D73D67A98F8} - {F11DD75C-122C-4B98-9EED-F71551F9562A} = {5F2D3A6A-76D3-4C22-A7F7-8D73D67A98F8} - {1EE6CA66-6585-459D-8889-666D4C2D4C27} = {5F2D3A6A-76D3-4C22-A7F7-8D73D67A98F8} {3068B34E-D975-4C11-B2F2-F10790051F2E} = {74C4FAFF-491D-448C-8CA0-F8E5FC838CC5} + {6D90C067-5CCD-4443-81A5-B9C385011F68} = {E168C5B8-F2EB-4BDE-942A-59C1EB130D59} {9CD9F9EB-379C-44C1-9016-33DFEC821C76} = {74C4FAFF-491D-448C-8CA0-F8E5FC838CC5} {4532D9F9-1E0D-4A62-8038-D3454B255E86} = {74C4FAFF-491D-448C-8CA0-F8E5FC838CC5} - {C5ECD02C-FA5A-4B56-9CA2-47AD8989714A} = {74C4FAFF-491D-448C-8CA0-F8E5FC838CC5} - {6D90C067-5CCD-4443-81A5-B9C385011F68} = {E168C5B8-F2EB-4BDE-942A-59C1EB130D59} {66E6ADF5-200F-41F3-9CA4-858EF69D2A61} = {E168C5B8-F2EB-4BDE-942A-59C1EB130D59} + {C5ECD02C-FA5A-4B56-9CA2-47AD8989714A} = {74C4FAFF-491D-448C-8CA0-F8E5FC838CC5} + {2C6983BB-3CB4-4EB7-9AF1-2F24FE1ECEAB} = {5F2D3A6A-76D3-4C22-A7F7-8D73D67A98F8} + {F11DD75C-122C-4B98-9EED-F71551F9562A} = {5F2D3A6A-76D3-4C22-A7F7-8D73D67A98F8} + {1EE6CA66-6585-459D-8889-666D4C2D4C27} = {5F2D3A6A-76D3-4C22-A7F7-8D73D67A98F8} {B667E66C-2E5E-4698-8011-2BA37EDD9D16} = {28065F40-B930-4A5D-95D8-A3BD5F86CE11} {9E5124E4-BEDA-4B2D-9699-60E2A7B1881D} = {28065F40-B930-4A5D-95D8-A3BD5F86CE11} {C85FD264-C77B-44F3-926C-D61C5DAD369E} = {0B56ECAF-7B4A-4135-A343-1577ACE09920} {A2CD66D3-74F2-4608-A56E-F866CC494620} = {0B56ECAF-7B4A-4135-A343-1577ACE09920} - {0B56ECAF-7B4A-4135-A343-1577ACE09920} = {D6F10CF9-982E-4D09-A112-0CBFD2D46AFF} {45502850-3207-49B0-9F5D-5DE95091DB5A} = {5DD887A4-ED78-4782-B372-34176C27F0C1} {B1E4A89A-6451-4484-B42B-4D1DF21B6961} = {5DD887A4-ED78-4782-B372-34176C27F0C1} - {5DD887A4-ED78-4782-B372-34176C27F0C1} = {D6F10CF9-982E-4D09-A112-0CBFD2D46AFF} {7E8189DE-6BBA-4CD5-9BA6-DF5ADBD027D3} = {6FA0C03B-0901-4FD8-AF44-D4C9E5516C2F} + {0B56ECAF-7B4A-4135-A343-1577ACE09920} = {D6F10CF9-982E-4D09-A112-0CBFD2D46AFF} + {5DD887A4-ED78-4782-B372-34176C27F0C1} = {D6F10CF9-982E-4D09-A112-0CBFD2D46AFF} {6FA0C03B-0901-4FD8-AF44-D4C9E5516C2F} = {D6F10CF9-982E-4D09-A112-0CBFD2D46AFF} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {68A7BDA7-8093-433C-BF7A-8A6A7560BD02} EndGlobalSection + GlobalSection(SharedMSBuildProjectFiles) = preSolution + ..\..\tools\illink\src\ILLink.Shared\ILLink.Shared.projitems*{a2cd66d3-74f2-4608-a56e-f866cc494620}*SharedItemsImports = 5 + ..\..\tools\illink\src\ILLink.Shared\ILLink.Shared.projitems*{b1e4a89a-6451-4484-b42b-4d1df21b6961}*SharedItemsImports = 5 + EndGlobalSection EndGlobal diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceCollectionContainerBuilderExtensions.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceCollectionContainerBuilderExtensions.cs index 5b12c82b9d6e67..8a7227dde1eeb7 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceCollectionContainerBuilderExtensions.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceCollectionContainerBuilderExtensions.cs @@ -45,14 +45,8 @@ public static ServiceProvider BuildServiceProvider(this IServiceCollection servi /// The . public static ServiceProvider BuildServiceProvider(this IServiceCollection services, ServiceProviderOptions options) { - if (services is null) - { - throw new ArgumentNullException(nameof(services)); - } - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(options); return new ServiceProvider(services, options); } diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteFactory.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteFactory.cs index 68c89a386e7c18..79825a37aabb15 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteFactory.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteFactory.cs @@ -690,10 +690,7 @@ internal bool IsService(ServiceIdentifier serviceIdentifier) { var serviceType = serviceIdentifier.ServiceType; - if (serviceType is null) - { - throw new ArgumentNullException(nameof(serviceType)); - } + ArgumentNullException.ThrowIfNull(serviceType); // Querying for an open generic should return false (they aren't resolvable) if (serviceType.IsGenericTypeDefinition) diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/CompilationLibrary.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/CompilationLibrary.cs index 603a08e8217190..46aa7bf1e0ae38 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/CompilationLibrary.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/CompilationLibrary.cs @@ -32,7 +32,7 @@ public CompilationLibrary(string type, string? hashPath) : base(type, name, version, hash, dependencies, serviceable, path, hashPath) { - ThrowHelper.ThrowIfNull(assemblies); + ArgumentNullException.ThrowIfNull(assemblies); Assemblies = assemblies.ToArray(); } diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/CompilationOptions.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/CompilationOptions.cs index a92c5f568ac438..c3dd68971b2c59 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/CompilationOptions.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/CompilationOptions.cs @@ -60,7 +60,7 @@ public CompilationOptions(IEnumerable defines, bool? emitEntryPoint, bool? generateXmlDocumentation) { - ThrowHelper.ThrowIfNull(defines); + ArgumentNullException.ThrowIfNull(defines); Defines = defines.ToArray(); LanguageVersion = languageVersion; diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContext.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContext.cs index 48ed7493123a5c..413275420c6bbd 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContext.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContext.cs @@ -22,11 +22,11 @@ public DependencyContext(TargetInfo target, IEnumerable runtimeLibraries, IEnumerable runtimeGraph) { - ThrowHelper.ThrowIfNull(target); - ThrowHelper.ThrowIfNull(compilationOptions); - ThrowHelper.ThrowIfNull(compileLibraries); - ThrowHelper.ThrowIfNull(runtimeLibraries); - ThrowHelper.ThrowIfNull(runtimeGraph); + ArgumentNullException.ThrowIfNull(target); + ArgumentNullException.ThrowIfNull(compilationOptions); + ArgumentNullException.ThrowIfNull(compileLibraries); + ArgumentNullException.ThrowIfNull(runtimeLibraries); + ArgumentNullException.ThrowIfNull(runtimeGraph); Target = target; CompilationOptions = compilationOptions; @@ -50,7 +50,7 @@ public DependencyContext(TargetInfo target, public DependencyContext Merge(DependencyContext other) { - ThrowHelper.ThrowIfNull(other); + ArgumentNullException.ThrowIfNull(other); return new DependencyContext( Target, diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextExtensions.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextExtensions.cs index a14da142caf379..70b2eda0ca91e4 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextExtensions.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextExtensions.cs @@ -15,94 +15,94 @@ public static class DependencyContextExtensions public static IEnumerable GetDefaultNativeAssets(this DependencyContext self) { - ThrowHelper.ThrowIfNull(self); + ArgumentNullException.ThrowIfNull(self); return LinqHelpers.SelectMany(self.RuntimeLibraries, static (library, context) => library.GetDefaultNativeAssets(context), self); } public static IEnumerable GetDefaultNativeRuntimeFileAssets(this DependencyContext self) { - ThrowHelper.ThrowIfNull(self); + ArgumentNullException.ThrowIfNull(self); return LinqHelpers.SelectMany(self.RuntimeLibraries, static (library, context) => library.GetDefaultNativeRuntimeFileAssets(context), self); } public static IEnumerable GetRuntimeNativeAssets(this DependencyContext self, string runtimeIdentifier) { - ThrowHelper.ThrowIfNull(self); - ThrowHelper.ThrowIfNull(runtimeIdentifier); + ArgumentNullException.ThrowIfNull(self); + ArgumentNullException.ThrowIfNull(runtimeIdentifier); return LinqHelpers.SelectMany(self.RuntimeLibraries, static (library, context, id) => library.GetRuntimeNativeAssets(context, id), self, runtimeIdentifier); } public static IEnumerable GetRuntimeNativeRuntimeFileAssets(this DependencyContext self, string runtimeIdentifier) { - ThrowHelper.ThrowIfNull(self); - ThrowHelper.ThrowIfNull(runtimeIdentifier); + ArgumentNullException.ThrowIfNull(self); + ArgumentNullException.ThrowIfNull(runtimeIdentifier); return LinqHelpers.SelectMany(self.RuntimeLibraries, static (library, context, id) => library.GetRuntimeNativeRuntimeFileAssets(context, id), self, runtimeIdentifier); } public static IEnumerable GetDefaultNativeAssets(this RuntimeLibrary self, DependencyContext context) { - ThrowHelper.ThrowIfNull(self); + ArgumentNullException.ThrowIfNull(self); return ResolveAssets(context, string.Empty, self.NativeLibraryGroups); } public static IEnumerable GetDefaultNativeRuntimeFileAssets(this RuntimeLibrary self, DependencyContext context) { - ThrowHelper.ThrowIfNull(self); + ArgumentNullException.ThrowIfNull(self); return ResolveRuntimeFiles(context, string.Empty, self.NativeLibraryGroups); } public static IEnumerable GetRuntimeNativeAssets(this RuntimeLibrary self, DependencyContext context, string runtimeIdentifier) { - ThrowHelper.ThrowIfNull(self); - ThrowHelper.ThrowIfNull(context); - ThrowHelper.ThrowIfNull(runtimeIdentifier); + ArgumentNullException.ThrowIfNull(self); + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(runtimeIdentifier); return ResolveAssets(context, runtimeIdentifier, self.NativeLibraryGroups); } public static IEnumerable GetRuntimeNativeRuntimeFileAssets(this RuntimeLibrary self, DependencyContext context, string runtimeIdentifier) { - ThrowHelper.ThrowIfNull(self); - ThrowHelper.ThrowIfNull(context); - ThrowHelper.ThrowIfNull(runtimeIdentifier); + ArgumentNullException.ThrowIfNull(self); + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(runtimeIdentifier); return ResolveRuntimeFiles(context, runtimeIdentifier, self.NativeLibraryGroups); } public static IEnumerable GetDefaultAssemblyNames(this DependencyContext self) { - ThrowHelper.ThrowIfNull(self); + ArgumentNullException.ThrowIfNull(self); return LinqHelpers.SelectMany(self.RuntimeLibraries, static (library, context) => library.GetDefaultAssemblyNames(context), self); } public static IEnumerable GetRuntimeAssemblyNames(this DependencyContext self, string runtimeIdentifier) { - ThrowHelper.ThrowIfNull(self); - ThrowHelper.ThrowIfNull(runtimeIdentifier); + ArgumentNullException.ThrowIfNull(self); + ArgumentNullException.ThrowIfNull(runtimeIdentifier); return LinqHelpers.SelectMany(self.RuntimeLibraries, static (library, context, id) => library.GetRuntimeAssemblyNames(context, id), self, runtimeIdentifier); } public static IEnumerable GetDefaultAssemblyNames(this RuntimeLibrary self, DependencyContext context) { - ThrowHelper.ThrowIfNull(self); - ThrowHelper.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(self); + ArgumentNullException.ThrowIfNull(context); return ResolveAssets(context, string.Empty, self.RuntimeAssemblyGroups).Select(GetAssemblyName); } public static IEnumerable GetRuntimeAssemblyNames(this RuntimeLibrary self, DependencyContext context, string runtimeIdentifier) { - ThrowHelper.ThrowIfNull(self); - ThrowHelper.ThrowIfNull(context); - ThrowHelper.ThrowIfNull(runtimeIdentifier); + ArgumentNullException.ThrowIfNull(self); + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(runtimeIdentifier); return ResolveAssets(context, runtimeIdentifier, self.RuntimeAssemblyGroups).Select(GetAssemblyName); } diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextJsonReader.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextJsonReader.cs index 2f260a8bb7dd84..8dfcb8d89b6ba5 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextJsonReader.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextJsonReader.cs @@ -21,7 +21,7 @@ public class DependencyContextJsonReader : IDependencyContextReader public DependencyContext Read(Stream stream) { - ThrowHelper.ThrowIfNull(stream); + ArgumentNullException.ThrowIfNull(stream); ArraySegment buffer = ReadToEnd(stream); try diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextLoader.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextLoader.cs index 867fadd4ac09f6..6b9b52a21f23bb 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextLoader.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextLoader.cs @@ -54,7 +54,7 @@ private static bool IsEntryAssembly(Assembly assembly) [RequiresAssemblyFiles("DependencyContext for an assembly from a application published as single-file is not supported. The method will return null. Make sure the calling code can handle this case.")] public DependencyContext? Load(Assembly assembly) { - ThrowHelper.ThrowIfNull(assembly); + ArgumentNullException.ThrowIfNull(assembly); DependencyContext? context = null; using (IDependencyContextReader reader = _jsonReaderFactory()) diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextWriter.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextWriter.cs index b20895cb6631e5..d4247d937067a7 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextWriter.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextWriter.cs @@ -15,8 +15,8 @@ public class DependencyContextWriter { public void Write(DependencyContext context, Stream stream) { - ThrowHelper.ThrowIfNull(context); - ThrowHelper.ThrowIfNull(stream); + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(stream); // Custom encoder is required to fix https://github.com/dotnet/runtime/issues/3678 // Since the JSON is only written to a file that is read by the SDK (and not transmitted over the wire), diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/Library.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/Library.cs index 6dc64a5b557658..6859f9af3b9578 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/Library.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/Library.cs @@ -52,7 +52,7 @@ public Library(string type, { throw new ArgumentException(null, nameof(version)); } - ThrowHelper.ThrowIfNull(dependencies); + ArgumentNullException.ThrowIfNull(dependencies); Type = type; Name = name; diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/Microsoft.Extensions.DependencyModel.csproj b/src/libraries/Microsoft.Extensions.DependencyModel/src/Microsoft.Extensions.DependencyModel.csproj index b730684c2c012d..1fdc6a3d0aa132 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/Microsoft.Extensions.DependencyModel.csproj +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/Microsoft.Extensions.DependencyModel.csproj @@ -12,8 +12,6 @@ By default, the dependency manifest contains information about the application's - diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/AppBaseCompilationAssemblyResolver.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/AppBaseCompilationAssemblyResolver.cs index 73d7f3d3f1bdc5..2c72d4c6fca452 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/AppBaseCompilationAssemblyResolver.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/AppBaseCompilationAssemblyResolver.cs @@ -32,9 +32,9 @@ internal AppBaseCompilationAssemblyResolver(IFileSystem fileSystem) internal AppBaseCompilationAssemblyResolver(IFileSystem fileSystem, string basePath, DependencyContextPaths dependencyContextPaths) { - ThrowHelper.ThrowIfNull(fileSystem); - ThrowHelper.ThrowIfNull(basePath); - ThrowHelper.ThrowIfNull(dependencyContextPaths); + ArgumentNullException.ThrowIfNull(fileSystem); + ArgumentNullException.ThrowIfNull(basePath); + ArgumentNullException.ThrowIfNull(dependencyContextPaths); _fileSystem = fileSystem; _basePath = basePath; @@ -43,7 +43,7 @@ internal AppBaseCompilationAssemblyResolver(IFileSystem fileSystem, string baseP public bool TryResolveAssemblyPaths(CompilationLibrary library, List? assemblies) { - ThrowHelper.ThrowIfNull(library); + ArgumentNullException.ThrowIfNull(library); bool isProject = string.Equals(library.Type, "project", StringComparison.OrdinalIgnoreCase) || string.Equals(library.Type, "msbuildproject", StringComparison.OrdinalIgnoreCase); diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/CompositeCompilationAssemblyResolver.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/CompositeCompilationAssemblyResolver.cs index 4d44b6e7a69c8c..4e6156fe6ed464 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/CompositeCompilationAssemblyResolver.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/CompositeCompilationAssemblyResolver.cs @@ -12,7 +12,7 @@ public class CompositeCompilationAssemblyResolver : ICompilationAssemblyResolver public CompositeCompilationAssemblyResolver(ICompilationAssemblyResolver[] resolvers) { - ThrowHelper.ThrowIfNull(resolvers); + ArgumentNullException.ThrowIfNull(resolvers); _resolvers = resolvers; } diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/PackageCompilationAssemblyResolver.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/PackageCompilationAssemblyResolver.cs index 5211d7005365c1..fb0009414698fa 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/PackageCompilationAssemblyResolver.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/PackageCompilationAssemblyResolver.cs @@ -31,8 +31,8 @@ internal PackageCompilationAssemblyResolver(IEnvironment environment, internal PackageCompilationAssemblyResolver(IFileSystem fileSystem, string[] nugetPackageDirectories) { - ThrowHelper.ThrowIfNull(fileSystem); - ThrowHelper.ThrowIfNull(nugetPackageDirectories); + ArgumentNullException.ThrowIfNull(fileSystem); + ArgumentNullException.ThrowIfNull(nugetPackageDirectories); _fileSystem = fileSystem; _nugetPackageDirectories = nugetPackageDirectories; @@ -68,7 +68,7 @@ internal static string[] GetDefaultProbeDirectories(IEnvironment environment) public bool TryResolveAssemblyPaths(CompilationLibrary library, List? assemblies) { - ThrowHelper.ThrowIfNull(library); + ArgumentNullException.ThrowIfNull(library); if (_nugetPackageDirectories == null || _nugetPackageDirectories.Length == 0 || !string.Equals(library.Type, "package", StringComparison.OrdinalIgnoreCase)) diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/ReferenceAssemblyPathResolver.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/ReferenceAssemblyPathResolver.cs index a7e4da244ae4e3..e965c298438836 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/ReferenceAssemblyPathResolver.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/ReferenceAssemblyPathResolver.cs @@ -33,8 +33,8 @@ internal ReferenceAssemblyPathResolver(IFileSystem fileSystem, IEnvironment envi internal ReferenceAssemblyPathResolver(IFileSystem fileSystem, string? defaultReferenceAssembliesPath, string[] fallbackSearchPaths) { - ThrowHelper.ThrowIfNull(fileSystem); - ThrowHelper.ThrowIfNull(fallbackSearchPaths); + ArgumentNullException.ThrowIfNull(fileSystem); + ArgumentNullException.ThrowIfNull(fallbackSearchPaths); _fileSystem = fileSystem; _defaultReferenceAssembliesPath = defaultReferenceAssembliesPath; @@ -43,7 +43,7 @@ internal ReferenceAssemblyPathResolver(IFileSystem fileSystem, string? defaultRe public bool TryResolveAssemblyPaths(CompilationLibrary library, List? assemblies) { - ThrowHelper.ThrowIfNull(library); + ArgumentNullException.ThrowIfNull(library); if (!string.Equals(library.Type, "referenceassembly", StringComparison.OrdinalIgnoreCase)) { diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeFallbacks.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeFallbacks.cs index bb9b5cb599de23..13f8c04c370ce6 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeFallbacks.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeFallbacks.cs @@ -19,7 +19,7 @@ public RuntimeFallbacks(string runtime, IEnumerable fallbacks) { throw new ArgumentException(null, nameof(runtime)); } - ThrowHelper.ThrowIfNull(fallbacks); + ArgumentNullException.ThrowIfNull(fallbacks); Runtime = runtime; Fallbacks = fallbacks.ToArray(); diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeLibrary.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeLibrary.cs index 338743b1027b53..482da4281ca968 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeLibrary.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeLibrary.cs @@ -105,9 +105,9 @@ public RuntimeLibrary(string type, hashPath, runtimeStoreManifestName) { - ThrowHelper.ThrowIfNull(runtimeAssemblyGroups); - ThrowHelper.ThrowIfNull(nativeLibraryGroups); - ThrowHelper.ThrowIfNull(resourceAssemblies); + ArgumentNullException.ThrowIfNull(runtimeAssemblyGroups); + ArgumentNullException.ThrowIfNull(nativeLibraryGroups); + ArgumentNullException.ThrowIfNull(resourceAssemblies); RuntimeAssemblyGroups = runtimeAssemblyGroups; ResourceAssemblies = resourceAssemblies.ToArray(); diff --git a/src/libraries/Microsoft.Extensions.Diagnostics.Abstractions/src/Metrics/MetricsBuilderExtensions.Listeners.cs b/src/libraries/Microsoft.Extensions.Diagnostics.Abstractions/src/Metrics/MetricsBuilderExtensions.Listeners.cs index f405af4adf83b2..3313c8939e97eb 100644 --- a/src/libraries/Microsoft.Extensions.Diagnostics.Abstractions/src/Metrics/MetricsBuilderExtensions.Listeners.cs +++ b/src/libraries/Microsoft.Extensions.Diagnostics.Abstractions/src/Metrics/MetricsBuilderExtensions.Listeners.cs @@ -21,7 +21,7 @@ public static partial class MetricsBuilderExtensions /// Returns the original for chaining. public static IMetricsBuilder AddListener<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(this IMetricsBuilder builder) where T : class, IMetricsListener { - ThrowHelper.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(builder); builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton()); return builder; } @@ -34,7 +34,7 @@ public static partial class MetricsBuilderExtensions /// Returns the original for chaining. public static IMetricsBuilder AddListener(this IMetricsBuilder builder, IMetricsListener listener) { - ThrowHelper.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(builder); builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton(listener)); return builder; } @@ -46,7 +46,7 @@ public static IMetricsBuilder AddListener(this IMetricsBuilder builder, IMetrics /// Returns the original for chaining. public static IMetricsBuilder ClearListeners(this IMetricsBuilder builder) { - ThrowHelper.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(builder); builder.Services.RemoveAll(); return builder; } diff --git a/src/libraries/Microsoft.Extensions.Diagnostics.Abstractions/src/Metrics/MetricsBuilderExtensions.Rules.cs b/src/libraries/Microsoft.Extensions.Diagnostics.Abstractions/src/Metrics/MetricsBuilderExtensions.Rules.cs index 2bfc6c4301f871..37413da0a4e8e0 100644 --- a/src/libraries/Microsoft.Extensions.Diagnostics.Abstractions/src/Metrics/MetricsBuilderExtensions.Rules.cs +++ b/src/libraries/Microsoft.Extensions.Diagnostics.Abstractions/src/Metrics/MetricsBuilderExtensions.Rules.cs @@ -102,7 +102,7 @@ public static MetricsOptions DisableMetrics(this MetricsOptions options, string? private static IMetricsBuilder ConfigureRule(this IMetricsBuilder builder, Action configureOptions) { - ThrowHelper.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(builder); builder.Services.Configure(configureOptions); return builder; } @@ -110,7 +110,7 @@ private static IMetricsBuilder ConfigureRule(this IMetricsBuilder builder, Actio private static MetricsOptions AddRule(this MetricsOptions options, string? meterName, string? instrumentName, string? listenerName, MeterScope scopes, bool enable) { - ThrowHelper.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(options); options.Rules.Add(new InstrumentRule(meterName, instrumentName, listenerName, scopes, enable)); return options; } diff --git a/src/libraries/Microsoft.Extensions.Diagnostics.Abstractions/src/Microsoft.Extensions.Diagnostics.Abstractions.csproj b/src/libraries/Microsoft.Extensions.Diagnostics.Abstractions/src/Microsoft.Extensions.Diagnostics.Abstractions.csproj index 2710e400702d00..202fe7fc5c436e 100644 --- a/src/libraries/Microsoft.Extensions.Diagnostics.Abstractions/src/Microsoft.Extensions.Diagnostics.Abstractions.csproj +++ b/src/libraries/Microsoft.Extensions.Diagnostics.Abstractions/src/Microsoft.Extensions.Diagnostics.Abstractions.csproj @@ -19,7 +19,6 @@ Microsoft.Extensions.Diagnostics.Metrics.MetricsOptions - diff --git a/src/libraries/Microsoft.Extensions.Diagnostics/src/Metrics/Configuration/MetricListenerConfigurationFactory.cs b/src/libraries/Microsoft.Extensions.Diagnostics/src/Metrics/Configuration/MetricListenerConfigurationFactory.cs index 4c5ee6cefff6fe..a08935c47661bf 100644 --- a/src/libraries/Microsoft.Extensions.Diagnostics/src/Metrics/Configuration/MetricListenerConfigurationFactory.cs +++ b/src/libraries/Microsoft.Extensions.Diagnostics/src/Metrics/Configuration/MetricListenerConfigurationFactory.cs @@ -18,7 +18,7 @@ public MetricListenerConfigurationFactory(IEnumerable conf public IConfiguration GetConfiguration(string listenerName) { - ThrowHelper.ThrowIfNull(listenerName); + ArgumentNullException.ThrowIfNull(listenerName); var configurationBuilder = new ConfigurationBuilder(); foreach (MetricsConfiguration configuration in _configurations) diff --git a/src/libraries/Microsoft.Extensions.Diagnostics/src/Metrics/Configuration/MetricsBuilderConfigurationExtensions.cs b/src/libraries/Microsoft.Extensions.Diagnostics/src/Metrics/Configuration/MetricsBuilderConfigurationExtensions.cs index d70a0f9c03a9e2..c7655377a3d17b 100644 --- a/src/libraries/Microsoft.Extensions.Diagnostics/src/Metrics/Configuration/MetricsBuilderConfigurationExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Diagnostics/src/Metrics/Configuration/MetricsBuilderConfigurationExtensions.cs @@ -24,15 +24,9 @@ public static class MetricsBuilderConfigurationExtensions /// The original for chaining. public static IMetricsBuilder AddConfiguration(this IMetricsBuilder builder, IConfiguration configuration) { - if (builder is null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); - if (configuration is null) - { - throw new ArgumentNullException(nameof(configuration)); - } + ArgumentNullException.ThrowIfNull(configuration); builder.Services.AddSingleton>(new MetricsConfigureOptions(configuration)); builder.Services.AddSingleton>(new ConfigurationChangeTokenSource(configuration)); diff --git a/src/libraries/Microsoft.Extensions.Diagnostics/src/Metrics/DefaultMeterFactory.cs b/src/libraries/Microsoft.Extensions.Diagnostics/src/Metrics/DefaultMeterFactory.cs index 3adb0b1a795739..0cde0d9b9277aa 100644 --- a/src/libraries/Microsoft.Extensions.Diagnostics/src/Metrics/DefaultMeterFactory.cs +++ b/src/libraries/Microsoft.Extensions.Diagnostics/src/Metrics/DefaultMeterFactory.cs @@ -18,10 +18,7 @@ public DefaultMeterFactory() { } public Meter Create(MeterOptions options) { - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); if (options.Scope is not null && !object.ReferenceEquals(options.Scope, this)) { diff --git a/src/libraries/Microsoft.Extensions.Diagnostics/src/Metrics/MetricsServiceExtensions.cs b/src/libraries/Microsoft.Extensions.Diagnostics/src/Metrics/MetricsServiceExtensions.cs index c779a0afef95c1..f8aadccc1ee033 100644 --- a/src/libraries/Microsoft.Extensions.Diagnostics/src/Metrics/MetricsServiceExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Diagnostics/src/Metrics/MetricsServiceExtensions.cs @@ -22,10 +22,7 @@ public static class MetricsServiceExtensions /// The so that additional calls can be chained. public static IServiceCollection AddMetrics(this IServiceCollection services) { - if (services is null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullException.ThrowIfNull(services); services.AddOptions(); @@ -50,10 +47,7 @@ public static IServiceCollection AddMetrics(this IServiceCollection services) /// The so that additional calls can be chained. public static IServiceCollection AddMetrics(this IServiceCollection services, Action configure) { - if (configure is null) - { - throw new ArgumentNullException(nameof(configure)); - } + ArgumentNullException.ThrowIfNull(configure); services.AddMetrics(); diff --git a/src/libraries/Microsoft.Extensions.Diagnostics/src/Microsoft.Extensions.Diagnostics.csproj b/src/libraries/Microsoft.Extensions.Diagnostics/src/Microsoft.Extensions.Diagnostics.csproj index 4ed1b5fc799a35..03b45a99a65f71 100644 --- a/src/libraries/Microsoft.Extensions.Diagnostics/src/Microsoft.Extensions.Diagnostics.csproj +++ b/src/libraries/Microsoft.Extensions.Diagnostics/src/Microsoft.Extensions.Diagnostics.csproj @@ -11,7 +11,6 @@ - diff --git a/src/libraries/Microsoft.Extensions.FileProviders.Composite/src/CompositeDirectoryContents.cs b/src/libraries/Microsoft.Extensions.FileProviders.Composite/src/CompositeDirectoryContents.cs index 27be2c7c94e1c6..7e66dc12d8d662 100644 --- a/src/libraries/Microsoft.Extensions.FileProviders.Composite/src/CompositeDirectoryContents.cs +++ b/src/libraries/Microsoft.Extensions.FileProviders.Composite/src/CompositeDirectoryContents.cs @@ -28,7 +28,7 @@ public class CompositeDirectoryContents : IDirectoryContents /// The path. public CompositeDirectoryContents(IList fileProviders, string subpath) { - ThrowHelper.ThrowIfNull(fileProviders); + ArgumentNullException.ThrowIfNull(fileProviders); _fileProviders = fileProviders; _subPath = subpath; diff --git a/src/libraries/Microsoft.Extensions.FileProviders.Composite/src/CompositeFileProvider.cs b/src/libraries/Microsoft.Extensions.FileProviders.Composite/src/CompositeFileProvider.cs index c8407a359cf7fc..162a7b4d320a39 100644 --- a/src/libraries/Microsoft.Extensions.FileProviders.Composite/src/CompositeFileProvider.cs +++ b/src/libraries/Microsoft.Extensions.FileProviders.Composite/src/CompositeFileProvider.cs @@ -31,7 +31,7 @@ public CompositeFileProvider(params IFileProvider[]? fileProviders) /// The collection of objects. public CompositeFileProvider(IEnumerable fileProviders) { - ThrowHelper.ThrowIfNull(fileProviders); + ArgumentNullException.ThrowIfNull(fileProviders); _fileProviders = fileProviders.ToArray(); } diff --git a/src/libraries/Microsoft.Extensions.FileProviders.Composite/src/Microsoft.Extensions.FileProviders.Composite.csproj b/src/libraries/Microsoft.Extensions.FileProviders.Composite/src/Microsoft.Extensions.FileProviders.Composite.csproj index cb00b896b54708..2cb7c2d4b059a5 100644 --- a/src/libraries/Microsoft.Extensions.FileProviders.Composite/src/Microsoft.Extensions.FileProviders.Composite.csproj +++ b/src/libraries/Microsoft.Extensions.FileProviders.Composite/src/Microsoft.Extensions.FileProviders.Composite.csproj @@ -13,8 +13,6 @@ - diff --git a/src/libraries/Microsoft.Extensions.FileProviders.Physical/src/Internal/PhysicalDirectoryContents.cs b/src/libraries/Microsoft.Extensions.FileProviders.Physical/src/Internal/PhysicalDirectoryContents.cs index 32c2540e1378c5..b8bb67eb4fa05c 100644 --- a/src/libraries/Microsoft.Extensions.FileProviders.Physical/src/Internal/PhysicalDirectoryContents.cs +++ b/src/libraries/Microsoft.Extensions.FileProviders.Physical/src/Internal/PhysicalDirectoryContents.cs @@ -31,7 +31,7 @@ public PhysicalDirectoryContents(string directory) /// Specifies which files or directories are excluded from enumeration. public PhysicalDirectoryContents(string directory, ExclusionFilters filters) { - ThrowHelper.ThrowIfNull(directory); + ArgumentNullException.ThrowIfNull(directory); _info = new PhysicalDirectoryInfo(new DirectoryInfo(directory), filters); } diff --git a/src/libraries/Microsoft.Extensions.FileProviders.Physical/src/Microsoft.Extensions.FileProviders.Physical.csproj b/src/libraries/Microsoft.Extensions.FileProviders.Physical/src/Microsoft.Extensions.FileProviders.Physical.csproj index 030d46af2a6cc6..966b0690bb72dd 100644 --- a/src/libraries/Microsoft.Extensions.FileProviders.Physical/src/Microsoft.Extensions.FileProviders.Physical.csproj +++ b/src/libraries/Microsoft.Extensions.FileProviders.Physical/src/Microsoft.Extensions.FileProviders.Physical.csproj @@ -15,8 +15,6 @@ Link="Common\src\Extensions\EmptyDisposable.cs" /> - diff --git a/src/libraries/Microsoft.Extensions.FileProviders.Physical/src/PhysicalFilesWatcher.cs b/src/libraries/Microsoft.Extensions.FileProviders.Physical/src/PhysicalFilesWatcher.cs index d37a7cb8c62f88..8433d0cd8e1527 100644 --- a/src/libraries/Microsoft.Extensions.FileProviders.Physical/src/PhysicalFilesWatcher.cs +++ b/src/libraries/Microsoft.Extensions.FileProviders.Physical/src/PhysicalFilesWatcher.cs @@ -127,7 +127,7 @@ public PhysicalFilesWatcher( /// is . public IChangeToken CreateFileChangeToken(string filter) { - ThrowHelper.ThrowIfNull(filter); + ArgumentNullException.ThrowIfNull(filter); filter = NormalizePath(filter); diff --git a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Abstractions/FileInfoWrapper.cs b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Abstractions/FileInfoWrapper.cs index 5b464a2791dc64..a88a70e492d0c9 100644 --- a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Abstractions/FileInfoWrapper.cs +++ b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Abstractions/FileInfoWrapper.cs @@ -19,7 +19,7 @@ public class FileInfoWrapper : FileInfoBase /// The public FileInfoWrapper(FileInfo fileInfo) { - ThrowHelper.ThrowIfNull(fileInfo); + ArgumentNullException.ThrowIfNull(fileInfo); _fileInfo = fileInfo; } diff --git a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/FilePatternMatch.cs b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/FilePatternMatch.cs index b643e970b2d835..e19649700e322c 100644 --- a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/FilePatternMatch.cs +++ b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/FilePatternMatch.cs @@ -37,7 +37,7 @@ public struct FilePatternMatch : IEquatable /// The subpath to the file matched, relative to the first wildcard in the matching search pattern. public FilePatternMatch(string path, string? stem) { - ThrowHelper.ThrowIfNull(path); + ArgumentNullException.ThrowIfNull(path); Path = path; Stem = stem; diff --git a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PathSegments/LiteralPathSegment.cs b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PathSegments/LiteralPathSegment.cs index 53d71cda8ee12e..6cb9c28ee84a1b 100644 --- a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PathSegments/LiteralPathSegment.cs +++ b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PathSegments/LiteralPathSegment.cs @@ -15,7 +15,7 @@ public class LiteralPathSegment : IPathSegment public LiteralPathSegment(string value, StringComparison comparisonType) { - ThrowHelper.ThrowIfNull(value); + ArgumentNullException.ThrowIfNull(value); Value = value; _comparisonType = comparisonType; diff --git a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PathSegments/WildcardPathSegment.cs b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PathSegments/WildcardPathSegment.cs index e4160e105ac217..f6199a9315df72 100644 --- a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PathSegments/WildcardPathSegment.cs +++ b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PathSegments/WildcardPathSegment.cs @@ -17,9 +17,9 @@ public class WildcardPathSegment : IPathSegment public WildcardPathSegment(string beginsWith, List contains, string endsWith, StringComparison comparisonType) { - ThrowHelper.ThrowIfNull(beginsWith); - ThrowHelper.ThrowIfNull(contains); - ThrowHelper.ThrowIfNull(endsWith); + ArgumentNullException.ThrowIfNull(beginsWith); + ArgumentNullException.ThrowIfNull(contains); + ArgumentNullException.ThrowIfNull(endsWith); _comparisonType = comparisonType switch { diff --git a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PatternContexts/PatternContextLinear.cs b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PatternContexts/PatternContextLinear.cs index 29a53d0e7d0f8a..3e4da101c9c277 100644 --- a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PatternContexts/PatternContextLinear.cs +++ b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PatternContexts/PatternContextLinear.cs @@ -12,7 +12,7 @@ public abstract class PatternContextLinear { public PatternContextLinear(ILinearPattern pattern) { - ThrowHelper.ThrowIfNull(pattern); + ArgumentNullException.ThrowIfNull(pattern); Pattern = pattern; } diff --git a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PatternContexts/PatternContextRagged.cs b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PatternContexts/PatternContextRagged.cs index 2927530981686a..fe834461cddbb7 100644 --- a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PatternContexts/PatternContextRagged.cs +++ b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PatternContexts/PatternContextRagged.cs @@ -11,7 +11,7 @@ public abstract class PatternContextRagged : PatternContextAlways returns instance of , even if no files were matched public virtual PatternMatchingResult Execute(DirectoryInfoBase directoryInfo) { - ThrowHelper.ThrowIfNull(directoryInfo); + ArgumentNullException.ThrowIfNull(directoryInfo); var context = new MatcherContext(_includePatterns, _excludePatterns, directoryInfo, _comparison); return context.Execute(); diff --git a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/MatcherExtensions.cs b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/MatcherExtensions.cs index c7db2fc670345b..b18877202c2c37 100644 --- a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/MatcherExtensions.cs +++ b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/MatcherExtensions.cs @@ -109,7 +109,7 @@ public static PatternMatchingResult Match(this Matcher matcher, IEnumerableThe match results. public static PatternMatchingResult Match(this Matcher matcher, string rootDir, IEnumerable? files) { - ThrowHelper.ThrowIfNull(matcher); + ArgumentNullException.ThrowIfNull(matcher); return matcher.Execute(new InMemoryDirectoryInfo(rootDir, files)); } diff --git a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Microsoft.Extensions.FileSystemGlobbing.csproj b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Microsoft.Extensions.FileSystemGlobbing.csproj index 2c51520950028e..b1614dcd8b6a22 100644 --- a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Microsoft.Extensions.FileSystemGlobbing.csproj +++ b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Microsoft.Extensions.FileSystemGlobbing.csproj @@ -11,8 +11,6 @@ - diff --git a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/PatternMatchingResult.cs b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/PatternMatchingResult.cs index 84ae35003e117a..5dc2733b8559bb 100644 --- a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/PatternMatchingResult.cs +++ b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/PatternMatchingResult.cs @@ -29,7 +29,7 @@ public PatternMatchingResult(IEnumerable files) /// A value that determines if has any matches. public PatternMatchingResult(IEnumerable files, bool hasMatches) { - ThrowHelper.ThrowIfNull(files); + ArgumentNullException.ThrowIfNull(files); Files = files; HasMatches = hasMatches; diff --git a/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/HostBuilderContext.cs b/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/HostBuilderContext.cs index 85e6f95a79c941..443df60c260e4d 100644 --- a/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/HostBuilderContext.cs +++ b/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/HostBuilderContext.cs @@ -18,7 +18,7 @@ public class HostBuilderContext /// A non-null for sharing state between components during the host building process. public HostBuilderContext(IDictionary properties) { - ThrowHelper.ThrowIfNull(properties); + ArgumentNullException.ThrowIfNull(properties); Properties = properties; } diff --git a/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/HostEnvironmentEnvExtensions.cs b/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/HostEnvironmentEnvExtensions.cs index c891d8e64ca511..cffc50c030609b 100644 --- a/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/HostEnvironmentEnvExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/HostEnvironmentEnvExtensions.cs @@ -17,7 +17,7 @@ public static class HostEnvironmentEnvExtensions /// if the environment name is , otherwise . public static bool IsDevelopment(this IHostEnvironment hostEnvironment) { - ThrowHelper.ThrowIfNull(hostEnvironment); + ArgumentNullException.ThrowIfNull(hostEnvironment); return hostEnvironment.IsEnvironment(Environments.Development); } @@ -29,7 +29,7 @@ public static bool IsDevelopment(this IHostEnvironment hostEnvironment) /// if the environment name is , otherwise . public static bool IsStaging(this IHostEnvironment hostEnvironment) { - ThrowHelper.ThrowIfNull(hostEnvironment); + ArgumentNullException.ThrowIfNull(hostEnvironment); return hostEnvironment.IsEnvironment(Environments.Staging); } @@ -41,7 +41,7 @@ public static bool IsStaging(this IHostEnvironment hostEnvironment) /// if the environment name is , otherwise . public static bool IsProduction(this IHostEnvironment hostEnvironment) { - ThrowHelper.ThrowIfNull(hostEnvironment); + ArgumentNullException.ThrowIfNull(hostEnvironment); return hostEnvironment.IsEnvironment(Environments.Production); } @@ -56,7 +56,7 @@ public static bool IsEnvironment( this IHostEnvironment hostEnvironment, string environmentName) { - ThrowHelper.ThrowIfNull(hostEnvironment); + ArgumentNullException.ThrowIfNull(hostEnvironment); return string.Equals( hostEnvironment.EnvironmentName, diff --git a/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/HostingEnvironmentExtensions.cs b/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/HostingEnvironmentExtensions.cs index 5e2a6cccef94d5..d096c93eaa53b4 100644 --- a/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/HostingEnvironmentExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/HostingEnvironmentExtensions.cs @@ -18,7 +18,7 @@ public static class HostingEnvironmentExtensions /// if the environment name is , otherwise . public static bool IsDevelopment(this IHostingEnvironment hostingEnvironment) { - ThrowHelper.ThrowIfNull(hostingEnvironment); + ArgumentNullException.ThrowIfNull(hostingEnvironment); return hostingEnvironment.IsEnvironment(EnvironmentName.Development); } @@ -30,7 +30,7 @@ public static bool IsDevelopment(this IHostingEnvironment hostingEnvironment) /// if the environment name is , otherwise . public static bool IsStaging(this IHostingEnvironment hostingEnvironment) { - ThrowHelper.ThrowIfNull(hostingEnvironment); + ArgumentNullException.ThrowIfNull(hostingEnvironment); return hostingEnvironment.IsEnvironment(EnvironmentName.Staging); } @@ -42,7 +42,7 @@ public static bool IsStaging(this IHostingEnvironment hostingEnvironment) /// if the environment name is , otherwise . public static bool IsProduction(this IHostingEnvironment hostingEnvironment) { - ThrowHelper.ThrowIfNull(hostingEnvironment); + ArgumentNullException.ThrowIfNull(hostingEnvironment); return hostingEnvironment.IsEnvironment(EnvironmentName.Production); } @@ -57,7 +57,7 @@ public static bool IsEnvironment( this IHostingEnvironment hostingEnvironment, string environmentName) { - ThrowHelper.ThrowIfNull(hostingEnvironment); + ArgumentNullException.ThrowIfNull(hostingEnvironment); return string.Equals( hostingEnvironment.EnvironmentName, diff --git a/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/Microsoft.Extensions.Hosting.Abstractions.csproj b/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/Microsoft.Extensions.Hosting.Abstractions.csproj index c2a3841ec4902f..e96791223b25f9 100644 --- a/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/Microsoft.Extensions.Hosting.Abstractions.csproj +++ b/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/Microsoft.Extensions.Hosting.Abstractions.csproj @@ -9,7 +9,6 @@ - diff --git a/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/Microsoft.Extensions.Hosting.Systemd.csproj b/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/Microsoft.Extensions.Hosting.Systemd.csproj index 94ee3bbf79c373..526c3c164f5ad3 100644 --- a/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/Microsoft.Extensions.Hosting.Systemd.csproj +++ b/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/Microsoft.Extensions.Hosting.Systemd.csproj @@ -19,7 +19,6 @@ - diff --git a/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/ServiceState.cs b/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/ServiceState.cs index 3fff525a646510..b9a5b3d9a6bbdd 100644 --- a/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/ServiceState.cs +++ b/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/ServiceState.cs @@ -29,7 +29,7 @@ public struct ServiceState /// A representation of service state. public ServiceState(string state) { - ThrowHelper.ThrowIfNull(state); + ArgumentNullException.ThrowIfNull(state); _data = Encoding.UTF8.GetBytes(state); } diff --git a/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/SystemdHostBuilderExtensions.cs b/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/SystemdHostBuilderExtensions.cs index 5be28337bbcef2..814160886b3c63 100644 --- a/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/SystemdHostBuilderExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/SystemdHostBuilderExtensions.cs @@ -32,7 +32,7 @@ public static class SystemdHostBuilderExtensions /// The instance for chaining. public static IHostBuilder UseSystemd(this IHostBuilder hostBuilder) { - ThrowHelper.ThrowIfNull(hostBuilder); + ArgumentNullException.ThrowIfNull(hostBuilder); if (SystemdHelpers.IsSystemdService()) { @@ -67,7 +67,7 @@ public static IHostBuilder UseSystemd(this IHostBuilder hostBuilder) /// The instance for chaining. public static IServiceCollection AddSystemd(this IServiceCollection services) { - ThrowHelper.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(services); if (SystemdHelpers.IsSystemdService()) { diff --git a/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/SystemdLifetime.cs b/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/SystemdLifetime.cs index 8aa4da9e839a92..6ca04aa0ffa6e3 100644 --- a/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/SystemdLifetime.cs +++ b/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/SystemdLifetime.cs @@ -31,10 +31,10 @@ public partial class SystemdLifetime : IHostLifetime, IDisposable /// The used to instantiate the lifetime logger. public SystemdLifetime(IHostEnvironment environment, IHostApplicationLifetime applicationLifetime, ISystemdNotifier systemdNotifier, ILoggerFactory loggerFactory) { - ThrowHelper.ThrowIfNull(environment); - ThrowHelper.ThrowIfNull(applicationLifetime); - ThrowHelper.ThrowIfNull(systemdNotifier); - ThrowHelper.ThrowIfNull(loggerFactory); + ArgumentNullException.ThrowIfNull(environment); + ArgumentNullException.ThrowIfNull(applicationLifetime); + ArgumentNullException.ThrowIfNull(systemdNotifier); + ArgumentNullException.ThrowIfNull(loggerFactory); Environment = environment; ApplicationLifetime = applicationLifetime; diff --git a/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/src/Microsoft.Extensions.Hosting.WindowsServices.csproj b/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/src/Microsoft.Extensions.Hosting.WindowsServices.csproj index 8a6564c371c173..4194664608c32e 100644 --- a/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/src/Microsoft.Extensions.Hosting.WindowsServices.csproj +++ b/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/src/Microsoft.Extensions.Hosting.WindowsServices.csproj @@ -17,8 +17,6 @@ Link="Common\Interop\Windows\Kernel32\Interop.CreateToolhelp32Snapshot.cs" /> - diff --git a/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/src/WindowsServiceLifetime.cs b/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/src/WindowsServiceLifetime.cs index 65d220058ac174..a1b58c01f630ce 100644 --- a/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/src/WindowsServiceLifetime.cs +++ b/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/src/WindowsServiceLifetime.cs @@ -45,11 +45,11 @@ public WindowsServiceLifetime(IHostEnvironment environment, IHostApplicationLife /// The Windows service options used to find the service name. public WindowsServiceLifetime(IHostEnvironment environment, IHostApplicationLifetime applicationLifetime, ILoggerFactory loggerFactory, IOptions optionsAccessor, IOptions windowsServiceOptionsAccessor) { - ThrowHelper.ThrowIfNull(environment); - ThrowHelper.ThrowIfNull(applicationLifetime); - ThrowHelper.ThrowIfNull(loggerFactory); - ThrowHelper.ThrowIfNull(optionsAccessor); - ThrowHelper.ThrowIfNull(windowsServiceOptionsAccessor); + ArgumentNullException.ThrowIfNull(environment); + ArgumentNullException.ThrowIfNull(applicationLifetime); + ArgumentNullException.ThrowIfNull(loggerFactory); + ArgumentNullException.ThrowIfNull(optionsAccessor); + ArgumentNullException.ThrowIfNull(windowsServiceOptionsAccessor); Environment = environment; ApplicationLifetime = applicationLifetime; diff --git a/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/src/WindowsServiceLifetimeHostBuilderExtensions.cs b/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/src/WindowsServiceLifetimeHostBuilderExtensions.cs index 0280d8ee9c5ede..a435f0a584b936 100644 --- a/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/src/WindowsServiceLifetimeHostBuilderExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/src/WindowsServiceLifetimeHostBuilderExtensions.cs @@ -44,7 +44,7 @@ public static IHostBuilder UseWindowsService(this IHostBuilder hostBuilder) /// The instance for chaining. public static IHostBuilder UseWindowsService(this IHostBuilder hostBuilder, Action configure) { - ThrowHelper.ThrowIfNull(hostBuilder); + ArgumentNullException.ThrowIfNull(hostBuilder); if (WindowsServiceHelpers.IsWindowsService()) { @@ -94,7 +94,7 @@ public static IServiceCollection AddWindowsService(this IServiceCollection servi /// The instance for chaining. public static IServiceCollection AddWindowsService(this IServiceCollection services, Action configure) { - ThrowHelper.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(services); if (WindowsServiceHelpers.IsWindowsService()) { diff --git a/src/libraries/Microsoft.Extensions.Hosting/src/HostApplicationBuilder.cs b/src/libraries/Microsoft.Extensions.Hosting/src/HostApplicationBuilder.cs index a4bd55d4efb3a2..e89cf30d8c8f2c 100644 --- a/src/libraries/Microsoft.Extensions.Hosting/src/HostApplicationBuilder.cs +++ b/src/libraries/Microsoft.Extensions.Hosting/src/HostApplicationBuilder.cs @@ -343,7 +343,7 @@ public void ApplyChanges() public IHostBuilder ConfigureHostConfiguration(Action configureDelegate) { - ThrowHelper.ThrowIfNull(configureDelegate); + ArgumentNullException.ThrowIfNull(configureDelegate); _configureHostConfigActions.Add(configureDelegate); return this; @@ -351,7 +351,7 @@ public IHostBuilder ConfigureHostConfiguration(Action con public IHostBuilder ConfigureAppConfiguration(Action configureDelegate) { - ThrowHelper.ThrowIfNull(configureDelegate); + ArgumentNullException.ThrowIfNull(configureDelegate); _configureAppConfigActions.Add(configureDelegate); return this; @@ -359,7 +359,7 @@ public IHostBuilder ConfigureAppConfiguration(Action configureDelegate) { - ThrowHelper.ThrowIfNull(configureDelegate); + ArgumentNullException.ThrowIfNull(configureDelegate); _configureServicesActions.Add(configureDelegate); return this; @@ -367,7 +367,7 @@ public IHostBuilder ConfigureServices(Action(IServiceProviderFactory factory) where TContainerBuilder : notnull { - ThrowHelper.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(factory); _serviceProviderFactory = new ServiceFactoryAdapter(factory); return this; @@ -376,7 +376,7 @@ public IHostBuilder UseServiceProviderFactory(IServiceProvide public IHostBuilder UseServiceProviderFactory(Func> factory) where TContainerBuilder : notnull { - ThrowHelper.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(factory); _serviceProviderFactory = new ServiceFactoryAdapter(() => _hostApplicationBuilder._hostBuilderContext, factory); return this; @@ -384,7 +384,7 @@ public IHostBuilder UseServiceProviderFactory(Func(Action configureDelegate) { - ThrowHelper.ThrowIfNull(configureDelegate); + ArgumentNullException.ThrowIfNull(configureDelegate); _configureContainerActions.Add(new ConfigureContainerAdapter(configureDelegate)); return this; diff --git a/src/libraries/Microsoft.Extensions.Hosting/src/HostBuilder.cs b/src/libraries/Microsoft.Extensions.Hosting/src/HostBuilder.cs index 9fb7219ad49967..aa6a79231cc27c 100644 --- a/src/libraries/Microsoft.Extensions.Hosting/src/HostBuilder.cs +++ b/src/libraries/Microsoft.Extensions.Hosting/src/HostBuilder.cs @@ -62,7 +62,7 @@ public HostBuilder() /// The same instance of the for chaining. public IHostBuilder ConfigureHostConfiguration(Action configureDelegate) { - ThrowHelper.ThrowIfNull(configureDelegate); + ArgumentNullException.ThrowIfNull(configureDelegate); _configureHostConfigActions.Add(configureDelegate); return this; @@ -78,7 +78,7 @@ public IHostBuilder ConfigureHostConfiguration(Action con /// The same instance of the for chaining. public IHostBuilder ConfigureAppConfiguration(Action configureDelegate) { - ThrowHelper.ThrowIfNull(configureDelegate); + ArgumentNullException.ThrowIfNull(configureDelegate); _configureAppConfigActions.Add(configureDelegate); return this; @@ -92,7 +92,7 @@ public IHostBuilder ConfigureAppConfiguration(ActionThe same instance of the for chaining. public IHostBuilder ConfigureServices(Action configureDelegate) { - ThrowHelper.ThrowIfNull(configureDelegate); + ArgumentNullException.ThrowIfNull(configureDelegate); _configureServicesActions.Add(configureDelegate); return this; @@ -106,7 +106,7 @@ public IHostBuilder ConfigureServices(ActionThe same instance of the for chaining. public IHostBuilder UseServiceProviderFactory(IServiceProviderFactory factory) where TContainerBuilder : notnull { - ThrowHelper.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(factory); _serviceProviderFactory = new ServiceFactoryAdapter(factory); _defaultProviderFactoryUsed = false; @@ -121,7 +121,7 @@ public IHostBuilder UseServiceProviderFactory(IServiceProvide /// The same instance of the for chaining. public IHostBuilder UseServiceProviderFactory(Func> factory) where TContainerBuilder : notnull { - ThrowHelper.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(factory); _serviceProviderFactory = new ServiceFactoryAdapter(() => _hostBuilderContext!, factory); _defaultProviderFactoryUsed = false; @@ -138,7 +138,7 @@ public IHostBuilder UseServiceProviderFactory(FuncThe same instance of the for chaining. public IHostBuilder ConfigureContainer(Action configureDelegate) { - ThrowHelper.ThrowIfNull(configureDelegate); + ArgumentNullException.ThrowIfNull(configureDelegate); _configureContainerActions.Add(new ConfigureContainerAdapter(configureDelegate)); return this; diff --git a/src/libraries/Microsoft.Extensions.Hosting/src/HostingHostBuilderExtensions.cs b/src/libraries/Microsoft.Extensions.Hosting/src/HostingHostBuilderExtensions.cs index 656b54a8e6e1d3..32305da076b99e 100644 --- a/src/libraries/Microsoft.Extensions.Hosting/src/HostingHostBuilderExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Hosting/src/HostingHostBuilderExtensions.cs @@ -35,7 +35,7 @@ public static IHostBuilder UseEnvironment(this IHostBuilder hostBuilder, string { return hostBuilder.ConfigureHostConfiguration(configBuilder => { - ThrowHelper.ThrowIfNull(environment); + ArgumentNullException.ThrowIfNull(environment); configBuilder.AddInMemoryCollection(new[] { @@ -55,7 +55,7 @@ public static IHostBuilder UseContentRoot(this IHostBuilder hostBuilder, string { return hostBuilder.ConfigureHostConfiguration(configBuilder => { - ThrowHelper.ThrowIfNull(contentRoot); + ArgumentNullException.ThrowIfNull(contentRoot); configBuilder.AddInMemoryCollection(new[] { diff --git a/src/libraries/Microsoft.Extensions.Hosting/src/Internal/ConfigureContainerAdapter.cs b/src/libraries/Microsoft.Extensions.Hosting/src/Internal/ConfigureContainerAdapter.cs index 2974183b656b07..541b7c86f03c07 100644 --- a/src/libraries/Microsoft.Extensions.Hosting/src/Internal/ConfigureContainerAdapter.cs +++ b/src/libraries/Microsoft.Extensions.Hosting/src/Internal/ConfigureContainerAdapter.cs @@ -11,7 +11,7 @@ internal sealed class ConfigureContainerAdapter : IConfigureC public ConfigureContainerAdapter(Action action) { - ThrowHelper.ThrowIfNull(action); + ArgumentNullException.ThrowIfNull(action); _action = action; } diff --git a/src/libraries/Microsoft.Extensions.Hosting/src/Internal/ConsoleLifetime.cs b/src/libraries/Microsoft.Extensions.Hosting/src/Internal/ConsoleLifetime.cs index a146865e6a80ea..b197587d47aa46 100644 --- a/src/libraries/Microsoft.Extensions.Hosting/src/Internal/ConsoleLifetime.cs +++ b/src/libraries/Microsoft.Extensions.Hosting/src/Internal/ConsoleLifetime.cs @@ -45,11 +45,11 @@ public ConsoleLifetime(IOptions options, IHostEnvironmen /// or or or or is . public ConsoleLifetime(IOptions options, IHostEnvironment environment, IHostApplicationLifetime applicationLifetime, IOptions hostOptions, ILoggerFactory loggerFactory) { - ThrowHelper.ThrowIfNull(options?.Value, nameof(options)); - ThrowHelper.ThrowIfNull(applicationLifetime); - ThrowHelper.ThrowIfNull(environment); - ThrowHelper.ThrowIfNull(hostOptions?.Value, nameof(hostOptions)); - ThrowHelper.ThrowIfNull(loggerFactory); + ArgumentNullException.ThrowIfNull(options?.Value, nameof(options)); + ArgumentNullException.ThrowIfNull(applicationLifetime); + ArgumentNullException.ThrowIfNull(environment); + ArgumentNullException.ThrowIfNull(hostOptions?.Value, nameof(hostOptions)); + ArgumentNullException.ThrowIfNull(loggerFactory); Options = options.Value; Environment = environment; diff --git a/src/libraries/Microsoft.Extensions.Hosting/src/Internal/Host.cs b/src/libraries/Microsoft.Extensions.Hosting/src/Internal/Host.cs index 18f295a3599d99..12066ef8814d27 100644 --- a/src/libraries/Microsoft.Extensions.Hosting/src/Internal/Host.cs +++ b/src/libraries/Microsoft.Extensions.Hosting/src/Internal/Host.cs @@ -39,10 +39,10 @@ public Host(IServiceProvider services, IHostLifetime hostLifetime, IOptions options) { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(applicationLifetime); - ThrowHelper.ThrowIfNull(logger); - ThrowHelper.ThrowIfNull(hostLifetime); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(applicationLifetime); + ArgumentNullException.ThrowIfNull(logger); + ArgumentNullException.ThrowIfNull(hostLifetime); Services = services; _applicationLifetime = (applicationLifetime as ApplicationLifetime)!; diff --git a/src/libraries/Microsoft.Extensions.Hosting/src/Internal/ServiceFactoryAdapter.cs b/src/libraries/Microsoft.Extensions.Hosting/src/Internal/ServiceFactoryAdapter.cs index 69f7c352cb7482..a11a39e660c0b9 100644 --- a/src/libraries/Microsoft.Extensions.Hosting/src/Internal/ServiceFactoryAdapter.cs +++ b/src/libraries/Microsoft.Extensions.Hosting/src/Internal/ServiceFactoryAdapter.cs @@ -15,15 +15,15 @@ internal sealed class ServiceFactoryAdapter : IServiceFactory public ServiceFactoryAdapter(IServiceProviderFactory serviceProviderFactory) { - ThrowHelper.ThrowIfNull(serviceProviderFactory); + ArgumentNullException.ThrowIfNull(serviceProviderFactory); _serviceProviderFactory = serviceProviderFactory; } public ServiceFactoryAdapter(Func contextResolver, Func> factoryResolver) { - ThrowHelper.ThrowIfNull(contextResolver); - ThrowHelper.ThrowIfNull(factoryResolver); + ArgumentNullException.ThrowIfNull(contextResolver); + ArgumentNullException.ThrowIfNull(factoryResolver); _contextResolver = contextResolver; _factoryResolver = factoryResolver; diff --git a/src/libraries/Microsoft.Extensions.Hosting/src/Microsoft.Extensions.Hosting.csproj b/src/libraries/Microsoft.Extensions.Hosting/src/Microsoft.Extensions.Hosting.csproj index aac48bc7861490..c173385b1a86ab 100644 --- a/src/libraries/Microsoft.Extensions.Hosting/src/Microsoft.Extensions.Hosting.csproj +++ b/src/libraries/Microsoft.Extensions.Hosting/src/Microsoft.Extensions.Hosting.csproj @@ -7,10 +7,6 @@ true - - - - diff --git a/src/libraries/Microsoft.Extensions.Http/src/DefaultHttpClientFactory.cs b/src/libraries/Microsoft.Extensions.Http/src/DefaultHttpClientFactory.cs index 04e561d61c0d96..6ac44753958019 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/DefaultHttpClientFactory.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/DefaultHttpClientFactory.cs @@ -65,10 +65,10 @@ public DefaultHttpClientFactory( IOptionsMonitor optionsMonitor, IEnumerable filters) { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(scopeFactory); - ThrowHelper.ThrowIfNull(optionsMonitor); - ThrowHelper.ThrowIfNull(filters); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(scopeFactory); + ArgumentNullException.ThrowIfNull(optionsMonitor); + ArgumentNullException.ThrowIfNull(filters); _services = services; _scopeFactory = scopeFactory; @@ -102,7 +102,7 @@ public DefaultHttpClientFactory( public HttpClient CreateClient(string name) { - ThrowHelper.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(name); HttpMessageHandler handler = CreateHandler(name); var client = new HttpClient(handler, disposeHandler: false); @@ -118,7 +118,7 @@ public HttpClient CreateClient(string name) public HttpMessageHandler CreateHandler(string name) { - ThrowHelper.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(name); ActiveHandlerTrackingEntry entry = _activeHandlers.GetOrAdd(name, _entryFactory).Value; diff --git a/src/libraries/Microsoft.Extensions.Http/src/DefaultHttpMessageHandlerBuilder.cs b/src/libraries/Microsoft.Extensions.Http/src/DefaultHttpMessageHandlerBuilder.cs index fa154227f7c679..f9466f30103fd0 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/DefaultHttpMessageHandlerBuilder.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/DefaultHttpMessageHandlerBuilder.cs @@ -27,7 +27,7 @@ public override string? Name get => _name; set { - ThrowHelper.ThrowIfNull(value); + ArgumentNullException.ThrowIfNull(value); _name = value; } } diff --git a/src/libraries/Microsoft.Extensions.Http/src/DefaultTypedHttpClientFactory.cs b/src/libraries/Microsoft.Extensions.Http/src/DefaultTypedHttpClientFactory.cs index dc474d6676f92d..8292ac2a57dbbe 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/DefaultTypedHttpClientFactory.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/DefaultTypedHttpClientFactory.cs @@ -17,7 +17,7 @@ internal sealed class DefaultTypedHttpClientFactory<[DynamicallyAccessedMembers( public DefaultTypedHttpClientFactory(Cache cache, IServiceProvider services) { - ThrowHelper.ThrowIfNull(cache); + ArgumentNullException.ThrowIfNull(cache); _cache = cache; _services = services; @@ -25,7 +25,7 @@ public DefaultTypedHttpClientFactory(Cache cache, IServiceProvider services) public TClient CreateClient(HttpClient httpClient) { - ThrowHelper.ThrowIfNull(httpClient); + ArgumentNullException.ThrowIfNull(httpClient); return (TClient)_cache.Activator(_services, new object[] { httpClient }); } diff --git a/src/libraries/Microsoft.Extensions.Http/src/DependencyInjection/HttpClientBuilderExtensions.Logging.cs b/src/libraries/Microsoft.Extensions.Http/src/DependencyInjection/HttpClientBuilderExtensions.Logging.cs index bf1b3c6d4ae90a..cd482ff5a60dbe 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/DependencyInjection/HttpClientBuilderExtensions.Logging.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/DependencyInjection/HttpClientBuilderExtensions.Logging.cs @@ -45,8 +45,8 @@ public static partial class HttpClientBuilderExtensions /// public static IHttpClientBuilder AddLogger(this IHttpClientBuilder builder, Func httpClientLoggerFactory, bool wrapHandlersPipeline = false) { - ThrowHelper.ThrowIfNull(builder); - ThrowHelper.ThrowIfNull(httpClientLoggerFactory); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(httpClientLoggerFactory); builder.Services.Configure(builder.Name, options => { @@ -108,7 +108,7 @@ public static IHttpClientBuilder AddLogger(this IHttpClientBuilder builder, Func public static IHttpClientBuilder AddLogger(this IHttpClientBuilder builder, bool wrapHandlersPipeline = false) where TLogger : IHttpClientLogger { - ThrowHelper.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(builder); return AddLogger(builder, services => services.GetRequiredService(), wrapHandlersPipeline); } @@ -120,7 +120,7 @@ public static IHttpClientBuilder AddLogger(this IHttpClientBuilder buil /// An that can be used to configure the client. public static IHttpClientBuilder RemoveAllLoggers(this IHttpClientBuilder builder) { - ThrowHelper.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(builder); builder.Services.Configure(builder.Name, options => { @@ -138,7 +138,7 @@ public static IHttpClientBuilder RemoveAllLoggers(this IHttpClientBuilder builde /// An that can be used to configure the client. public static IHttpClientBuilder AddDefaultLogger(this IHttpClientBuilder builder) { - ThrowHelper.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(builder); builder.Services.Configure(builder.Name, options => options.SuppressDefaultLogging = false); return builder; diff --git a/src/libraries/Microsoft.Extensions.Http/src/DependencyInjection/HttpClientBuilderExtensions.cs b/src/libraries/Microsoft.Extensions.Http/src/DependencyInjection/HttpClientBuilderExtensions.cs index 7b93ebe2ea139b..be744e284acaac 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/DependencyInjection/HttpClientBuilderExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/DependencyInjection/HttpClientBuilderExtensions.cs @@ -27,8 +27,8 @@ public static partial class HttpClientBuilderExtensions /// An that can be used to configure the client. public static IHttpClientBuilder ConfigureHttpClient(this IHttpClientBuilder builder, Action configureClient) { - ThrowHelper.ThrowIfNull(builder); - ThrowHelper.ThrowIfNull(configureClient); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(configureClient); builder.Services.Configure(builder.Name, options => options.HttpClientActions.Add(configureClient)); @@ -47,8 +47,8 @@ public static IHttpClientBuilder ConfigureHttpClient(this IHttpClientBuilder bui /// public static IHttpClientBuilder ConfigureHttpClient(this IHttpClientBuilder builder, Action configureClient) { - ThrowHelper.ThrowIfNull(builder); - ThrowHelper.ThrowIfNull(configureClient); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(configureClient); builder.Services.AddTransient>(services => { @@ -73,8 +73,8 @@ public static IHttpClientBuilder ConfigureHttpClient(this IHttpClientBuilder bui /// public static IHttpClientBuilder AddHttpMessageHandler(this IHttpClientBuilder builder, Func configureHandler) { - ThrowHelper.ThrowIfNull(builder); - ThrowHelper.ThrowIfNull(configureHandler); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(configureHandler); builder.Services.Configure(builder.Name, options => { @@ -102,8 +102,8 @@ public static IHttpClientBuilder AddHttpMessageHandler(this IHttpClientBuilder b /// public static IHttpClientBuilder AddHttpMessageHandler(this IHttpClientBuilder builder, Func configureHandler) { - ThrowHelper.ThrowIfNull(builder); - ThrowHelper.ThrowIfNull(configureHandler); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(configureHandler); builder.Services.Configure(builder.Name, options => { @@ -130,7 +130,7 @@ public static IHttpClientBuilder AddHttpMessageHandler(this IHttpClientBuilder b public static IHttpClientBuilder AddHttpMessageHandler(this IHttpClientBuilder builder) where THandler : DelegatingHandler { - ThrowHelper.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(builder); builder.Services.Configure(builder.Name, options => { @@ -153,8 +153,8 @@ public static IHttpClientBuilder AddHttpMessageHandler(this IHttpClien /// public static IHttpClientBuilder ConfigurePrimaryHttpMessageHandler(this IHttpClientBuilder builder, Func configureHandler) { - ThrowHelper.ThrowIfNull(builder); - ThrowHelper.ThrowIfNull(configureHandler); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(configureHandler); builder.Services.Configure(builder.Name, options => { @@ -183,8 +183,8 @@ public static IHttpClientBuilder ConfigurePrimaryHttpMessageHandler(this IHttpCl /// public static IHttpClientBuilder ConfigurePrimaryHttpMessageHandler(this IHttpClientBuilder builder, Func configureHandler) { - ThrowHelper.ThrowIfNull(builder); - ThrowHelper.ThrowIfNull(configureHandler); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(configureHandler); builder.Services.Configure(builder.Name, options => { @@ -212,7 +212,7 @@ public static IHttpClientBuilder ConfigurePrimaryHttpMessageHandler(this IHttpCl public static IHttpClientBuilder ConfigurePrimaryHttpMessageHandler(this IHttpClientBuilder builder) where THandler : HttpMessageHandler { - ThrowHelper.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(builder); builder.Services.Configure(builder.Name, options => { @@ -237,8 +237,8 @@ public static IHttpClientBuilder ConfigurePrimaryHttpMessageHandler(th /// public static IHttpClientBuilder ConfigurePrimaryHttpMessageHandler(this IHttpClientBuilder builder, Action configureHandler) { - ThrowHelper.ThrowIfNull(builder); - ThrowHelper.ThrowIfNull(configureHandler); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(configureHandler); builder.Services.Configure(builder.Name, options => { @@ -258,8 +258,8 @@ public static IHttpClientBuilder ConfigurePrimaryHttpMessageHandler(this IHttpCl [Obsolete("This method has been deprecated. Use ConfigurePrimaryHttpMessageHandler or ConfigureAdditionalHttpMessageHandlers instead.")] public static IHttpClientBuilder ConfigureHttpMessageHandlerBuilder(this IHttpClientBuilder builder, Action configureBuilder) { - ThrowHelper.ThrowIfNull(builder); - ThrowHelper.ThrowIfNull(configureBuilder); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(configureBuilder); builder.Services.Configure(builder.Name, options => options.HttpMessageHandlerBuilderActions.Add(configureBuilder)); @@ -285,7 +285,7 @@ public static IHttpClientBuilder ConfigureHttpMessageHandlerBuilder(this IHttpCl [UnsupportedOSPlatform("browser")] public static IHttpClientBuilder UseSocketsHttpHandler(this IHttpClientBuilder builder, Action? configureHandler = null) { - ThrowHelper.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(builder); builder.Services.Configure(builder.Name, options => { @@ -323,7 +323,7 @@ public static IHttpClientBuilder UseSocketsHttpHandler(this IHttpClientBuilder b [UnsupportedOSPlatform("browser")] public static IHttpClientBuilder UseSocketsHttpHandler(this IHttpClientBuilder builder, Action configureBuilder) { - ThrowHelper.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(builder); UseSocketsHttpHandler(builder); configureBuilder(new DefaultSocketsHttpHandlerBuilder(builder.Services, builder.Name)); @@ -361,7 +361,7 @@ public static IHttpClientBuilder UseSocketsHttpHandler(this IHttpClientBuilder b this IHttpClientBuilder builder) where TClient : class { - ThrowHelper.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(builder); return AddTypedClientCore(builder, validateSingleType: false); } @@ -424,7 +424,7 @@ private static TClient AddTransientHelper(IServiceProvider s, IHttpClie where TClient : class where TImplementation : class, TClient { - ThrowHelper.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(builder); return AddTypedClientCore(builder, validateSingleType: false); } @@ -476,8 +476,8 @@ private static TClient AddTransientHelper(IServiceProv public static IHttpClientBuilder AddTypedClient(this IHttpClientBuilder builder, Func factory) where TClient : class { - ThrowHelper.ThrowIfNull(builder); - ThrowHelper.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(factory); return AddTypedClientCore(builder, factory, validateSingleType: false); } @@ -522,8 +522,8 @@ internal static IHttpClientBuilder AddTypedClientCore(this IHttpClientB public static IHttpClientBuilder AddTypedClient(this IHttpClientBuilder builder, Func factory) where TClient : class { - ThrowHelper.ThrowIfNull(builder); - ThrowHelper.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(factory); return AddTypedClientCore(builder, factory, validateSingleType: false); } @@ -531,8 +531,8 @@ public static IHttpClientBuilder AddTypedClient(this IHttpClientBuilder internal static IHttpClientBuilder AddTypedClientCore(this IHttpClientBuilder builder, Func factory, bool validateSingleType) where TClient : class { - ThrowHelper.ThrowIfNull(builder); - ThrowHelper.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(factory); ReserveClient(builder, typeof(TClient), builder.Name, validateSingleType); @@ -557,8 +557,8 @@ internal static IHttpClientBuilder AddTypedClientCore(this IHttpClientB /// public static IHttpClientBuilder RedactLoggedHeaders(this IHttpClientBuilder builder, Func shouldRedactHeaderValue) { - ThrowHelper.ThrowIfNull(builder); - ThrowHelper.ThrowIfNull(shouldRedactHeaderValue); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(shouldRedactHeaderValue); builder.Services.Configure(builder.Name, options => { @@ -576,8 +576,8 @@ public static IHttpClientBuilder RedactLoggedHeaders(this IHttpClientBuilder bui /// The . public static IHttpClientBuilder RedactLoggedHeaders(this IHttpClientBuilder builder, IEnumerable redactedLoggedHeaderNames) { - ThrowHelper.ThrowIfNull(builder); - ThrowHelper.ThrowIfNull(redactedLoggedHeaderNames); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(redactedLoggedHeaderNames); builder.Services.Configure(builder.Name, options => { @@ -615,7 +615,7 @@ public static IHttpClientBuilder RedactLoggedHeaders(this IHttpClientBuilder bui /// public static IHttpClientBuilder SetHandlerLifetime(this IHttpClientBuilder builder, TimeSpan handlerLifetime) { - ThrowHelper.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(builder); if (handlerLifetime != Timeout.InfiniteTimeSpan && handlerLifetime < HttpClientFactoryOptions.MinimumHandlerLifetime) { @@ -635,8 +635,8 @@ public static IHttpClientBuilder SetHandlerLifetime(this IHttpClientBuilder buil /// An that can be used to configure the client. public static IHttpClientBuilder ConfigureAdditionalHttpMessageHandlers(this IHttpClientBuilder builder, Action, IServiceProvider> configureAdditionalHandlers) { - ThrowHelper.ThrowIfNull(builder); - ThrowHelper.ThrowIfNull(configureAdditionalHandlers); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(configureAdditionalHandlers); builder.Services.Configure(builder.Name, options => { @@ -686,7 +686,7 @@ public static IHttpClientBuilder ConfigureAdditionalHttpMessageHandlers(this IHt /// public static IHttpClientBuilder AddAsKeyed(this IHttpClientBuilder builder, ServiceLifetime lifetime = ServiceLifetime.Scoped) { - ThrowHelper.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(builder); string? name = builder.Name; IServiceCollection services = builder.Services; @@ -728,7 +728,7 @@ public static IHttpClientBuilder AddAsKeyed(this IHttpClientBuilder builder, Ser /// public static IHttpClientBuilder RemoveAsKeyed(this IHttpClientBuilder builder) { - ThrowHelper.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(builder); string? name = builder.Name; IServiceCollection services = builder.Services; diff --git a/src/libraries/Microsoft.Extensions.Http/src/DependencyInjection/HttpClientFactoryServiceCollectionExtensions.cs b/src/libraries/Microsoft.Extensions.Http/src/DependencyInjection/HttpClientFactoryServiceCollectionExtensions.cs index c2ed48606432a9..154d05b7254b6b 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/DependencyInjection/HttpClientFactoryServiceCollectionExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/DependencyInjection/HttpClientFactoryServiceCollectionExtensions.cs @@ -25,7 +25,7 @@ public static class HttpClientFactoryServiceCollectionExtensions /// The . public static IServiceCollection AddHttpClient(this IServiceCollection services) { - ThrowHelper.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(services); services.AddLogging(); services.AddOptions(); @@ -79,8 +79,8 @@ public static IServiceCollection AddHttpClient(this IServiceCollection services) /// The . public static IServiceCollection ConfigureHttpClientDefaults(this IServiceCollection services, Action configure) { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(configure); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configure); AddHttpClient(services); @@ -107,8 +107,8 @@ public static IServiceCollection ConfigureHttpClientDefaults(this IServiceCollec /// public static IHttpClientBuilder AddHttpClient(this IServiceCollection services, string name) { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(name); AddHttpClient(services); @@ -134,9 +134,9 @@ public static IHttpClientBuilder AddHttpClient(this IServiceCollection services, /// public static IHttpClientBuilder AddHttpClient(this IServiceCollection services, string name, Action configureClient) { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(name); - ThrowHelper.ThrowIfNull(configureClient); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(configureClient); AddHttpClient(services); @@ -164,9 +164,9 @@ public static IHttpClientBuilder AddHttpClient(this IServiceCollection services, /// public static IHttpClientBuilder AddHttpClient(this IServiceCollection services, string name, Action configureClient) { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(name); - ThrowHelper.ThrowIfNull(configureClient); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(configureClient); AddHttpClient(services); @@ -201,7 +201,7 @@ public static IHttpClientBuilder AddHttpClient(this IServiceCollection services, this IServiceCollection services) where TClient : class { - ThrowHelper.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(services); AddHttpClient(services); @@ -242,7 +242,7 @@ public static IHttpClientBuilder AddHttpClient(this IServiceCollection services, where TClient : class where TImplementation : class, TClient { - ThrowHelper.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(services); AddHttpClient(services); @@ -281,8 +281,8 @@ public static IHttpClientBuilder AddHttpClient(this IServiceCollection services, this IServiceCollection services, string name) where TClient : class { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(name); AddHttpClient(services); @@ -325,8 +325,8 @@ public static IHttpClientBuilder AddHttpClient(this IServiceCollection services, where TClient : class where TImplementation : class, TClient { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(name); AddHttpClient(services); @@ -362,8 +362,8 @@ public static IHttpClientBuilder AddHttpClient(this IServiceCollection services, this IServiceCollection services, Action configureClient) where TClient : class { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(configureClient); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configureClient); AddHttpClient(services); @@ -401,8 +401,8 @@ public static IHttpClientBuilder AddHttpClient(this IServiceCollection services, this IServiceCollection services, Action configureClient) where TClient : class { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(configureClient); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configureClient); AddHttpClient(services); @@ -445,8 +445,8 @@ public static IHttpClientBuilder AddHttpClient(this IServiceCollection services, where TClient : class where TImplementation : class, TClient { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(configureClient); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configureClient); AddHttpClient(services); @@ -489,8 +489,8 @@ public static IHttpClientBuilder AddHttpClient(this IServiceCollection services, where TClient : class where TImplementation : class, TClient { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(configureClient); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configureClient); AddHttpClient(services); @@ -531,9 +531,9 @@ public static IHttpClientBuilder AddHttpClient(this IServiceCollection services, this IServiceCollection services, string name, Action configureClient) where TClient : class { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(name); - ThrowHelper.ThrowIfNull(configureClient); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(configureClient); AddHttpClient(services); @@ -573,9 +573,9 @@ public static IHttpClientBuilder AddHttpClient(this IServiceCollection services, this IServiceCollection services, string name, Action configureClient) where TClient : class { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(name); - ThrowHelper.ThrowIfNull(configureClient); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(configureClient); AddHttpClient(services); @@ -620,9 +620,9 @@ public static IHttpClientBuilder AddHttpClient(this IServiceCollection services, where TClient : class where TImplementation : class, TClient { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(name); - ThrowHelper.ThrowIfNull(configureClient); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(configureClient); AddHttpClient(services); @@ -667,9 +667,9 @@ public static IHttpClientBuilder AddHttpClient(this IServiceCollection services, where TClient : class where TImplementation : class, TClient { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(name); - ThrowHelper.ThrowIfNull(configureClient); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(configureClient); AddHttpClient(services); @@ -708,8 +708,8 @@ public static IHttpClientBuilder AddHttpClient(this IS where TClient : class where TImplementation : class, TClient { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(factory); string name = TypeNameHelper.GetTypeDisplayName(typeof(TClient), fullName: false); return AddHttpClient(services, name, factory); @@ -747,9 +747,9 @@ public static IHttpClientBuilder AddHttpClient(this IS where TClient : class where TImplementation : class, TClient { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(name); - ThrowHelper.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(factory); AddHttpClient(services); @@ -787,8 +787,8 @@ public static IHttpClientBuilder AddHttpClient(this IS where TClient : class where TImplementation : class, TClient { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(factory); string name = TypeNameHelper.GetTypeDisplayName(typeof(TClient), fullName: false); return AddHttpClient(services, name, factory); @@ -824,9 +824,9 @@ public static IHttpClientBuilder AddHttpClient(this IS where TClient : class where TImplementation : class, TClient { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(name); - ThrowHelper.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(factory); AddHttpClient(services); diff --git a/src/libraries/Microsoft.Extensions.Http/src/DependencyInjection/HttpClientKeyedLifetime.cs b/src/libraries/Microsoft.Extensions.Http/src/DependencyInjection/HttpClientKeyedLifetime.cs index 40e0b3563ec914..065e8766a29f04 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/DependencyInjection/HttpClientKeyedLifetime.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/DependencyInjection/HttpClientKeyedLifetime.cs @@ -26,7 +26,7 @@ private HttpClientKeyedLifetime(object serviceKey, ServiceDescriptor client, Ser private HttpClientKeyedLifetime(object serviceKey, ServiceLifetime lifetime) { - ThrowHelper.ThrowIfNull(serviceKey); + ArgumentNullException.ThrowIfNull(serviceKey); ServiceKey = serviceKey; Client = ServiceDescriptor.DescribeKeyed(typeof(HttpClient), ServiceKey, CreateKeyedClient, lifetime); Handler = ServiceDescriptor.DescribeKeyed(typeof(HttpMessageHandler), ServiceKey, CreateKeyedHandler, lifetime); diff --git a/src/libraries/Microsoft.Extensions.Http/src/HttpClientFactoryExtensions.cs b/src/libraries/Microsoft.Extensions.Http/src/HttpClientFactoryExtensions.cs index 3719b36637c8db..b244517eea76b5 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/HttpClientFactoryExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/HttpClientFactoryExtensions.cs @@ -17,7 +17,7 @@ public static class HttpClientFactoryExtensions /// An configured using the default configuration. public static HttpClient CreateClient(this IHttpClientFactory factory) { - ThrowHelper.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(factory); return factory.CreateClient(Options.DefaultName); } diff --git a/src/libraries/Microsoft.Extensions.Http/src/HttpMessageHandlerBuilder.cs b/src/libraries/Microsoft.Extensions.Http/src/HttpMessageHandlerBuilder.cs index 4785ce7c9291d4..2a90d37d24b6e7 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/HttpMessageHandlerBuilder.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/HttpMessageHandlerBuilder.cs @@ -80,8 +80,8 @@ public abstract class HttpMessageHandlerBuilder /// The DelegatingHandler.InnerHandler property must be . DelegatingHandler instances provided to HttpMessageHandlerBuilder must not be reused or cached. protected internal static HttpMessageHandler CreateHandlerPipeline(HttpMessageHandler primaryHandler, IEnumerable additionalHandlers) { - ThrowHelper.ThrowIfNull(primaryHandler); - ThrowHelper.ThrowIfNull(additionalHandlers); + ArgumentNullException.ThrowIfNull(primaryHandler); + ArgumentNullException.ThrowIfNull(additionalHandlers); // This is similar to https://github.com/aspnet/AspNetWebStack/blob/master/src/System.Net.Http.Formatting/HttpClientFactory.cs#L58 // but we don't want to take that package as a dependency. diff --git a/src/libraries/Microsoft.Extensions.Http/src/HttpMessageHandlerFactoryExtensions.cs b/src/libraries/Microsoft.Extensions.Http/src/HttpMessageHandlerFactoryExtensions.cs index 068782b7a0d7f9..305932ccdf80d1 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/HttpMessageHandlerFactoryExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/HttpMessageHandlerFactoryExtensions.cs @@ -17,7 +17,7 @@ public static class HttpMessageHandlerFactoryExtensions /// An configured using the default configuration. public static HttpMessageHandler CreateHandler(this IHttpMessageHandlerFactory factory) { - ThrowHelper.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(factory); return factory.CreateHandler(Options.DefaultName); } diff --git a/src/libraries/Microsoft.Extensions.Http/src/Logging/HttpClientLoggerHandler.cs b/src/libraries/Microsoft.Extensions.Http/src/Logging/HttpClientLoggerHandler.cs index a7aeebe8578f3e..9f8d3ebdb4f189 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/Logging/HttpClientLoggerHandler.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/Logging/HttpClientLoggerHandler.cs @@ -16,7 +16,7 @@ internal sealed class HttpClientLoggerHandler : DelegatingHandler public HttpClientLoggerHandler(IHttpClientLogger httpClientLogger) { - ThrowHelper.ThrowIfNull(httpClientLogger); + ArgumentNullException.ThrowIfNull(httpClientLogger); _httpClientLogger = httpClientLogger; _httpClientAsyncLogger = httpClientLogger as IHttpClientAsyncLogger; @@ -24,7 +24,7 @@ public HttpClientLoggerHandler(IHttpClientLogger httpClientLogger) protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { - ThrowHelper.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(request); var stopwatch = ValueStopwatch.StartNew(); HttpResponseMessage? response = null; @@ -64,7 +64,7 @@ protected override async Task SendAsync(HttpRequestMessage #if NET protected override HttpResponseMessage Send(HttpRequestMessage request, CancellationToken cancellationToken) { - ThrowHelper.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(request); var stopwatch = ValueStopwatch.StartNew(); HttpResponseMessage? response = null; diff --git a/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingHttpMessageHandler.cs b/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingHttpMessageHandler.cs index 077d48382e89c2..73a678b69747e0 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingHttpMessageHandler.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingHttpMessageHandler.cs @@ -26,7 +26,7 @@ public class LoggingHttpMessageHandler : DelegatingHandler /// is . public LoggingHttpMessageHandler(ILogger logger) { - ThrowHelper.ThrowIfNull(logger); + ArgumentNullException.ThrowIfNull(logger); _logger = logger; } @@ -39,8 +39,8 @@ public LoggingHttpMessageHandler(ILogger logger) /// or is . public LoggingHttpMessageHandler(ILogger logger, HttpClientFactoryOptions options) { - ThrowHelper.ThrowIfNull(logger); - ThrowHelper.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(logger); + ArgumentNullException.ThrowIfNull(options); _logger = logger; _options = options; @@ -48,7 +48,7 @@ public LoggingHttpMessageHandler(ILogger logger, HttpClientFactoryOptions option private Task SendCoreAsync(HttpRequestMessage request, bool useAsync, CancellationToken cancellationToken) { - ThrowHelper.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(request); return Core(request, useAsync, cancellationToken); async Task Core(HttpRequestMessage request, bool useAsync, CancellationToken cancellationToken) diff --git a/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingHttpMessageHandlerBuilderFilter.cs b/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingHttpMessageHandlerBuilderFilter.cs index a10a1f831e8835..845725f0994af3 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingHttpMessageHandlerBuilderFilter.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingHttpMessageHandlerBuilderFilter.cs @@ -22,8 +22,8 @@ internal sealed class LoggingHttpMessageHandlerBuilderFilter : IHttpMessageHandl public LoggingHttpMessageHandlerBuilderFilter(IServiceProvider serviceProvider, IOptionsMonitor optionsMonitor) { - ThrowHelper.ThrowIfNull(serviceProvider); - ThrowHelper.ThrowIfNull(optionsMonitor); + ArgumentNullException.ThrowIfNull(serviceProvider); + ArgumentNullException.ThrowIfNull(optionsMonitor); _serviceProvider = serviceProvider; _optionsMonitor = optionsMonitor; @@ -31,7 +31,7 @@ public LoggingHttpMessageHandlerBuilderFilter(IServiceProvider serviceProvider, public Action Configure(Action next) { - ThrowHelper.ThrowIfNull(next); + ArgumentNullException.ThrowIfNull(next); return (builder) => { diff --git a/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingScopeHttpMessageHandler.cs b/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingScopeHttpMessageHandler.cs index 033234b38e431c..193784492d0d59 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingScopeHttpMessageHandler.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingScopeHttpMessageHandler.cs @@ -25,7 +25,7 @@ public class LoggingScopeHttpMessageHandler : DelegatingHandler /// is . public LoggingScopeHttpMessageHandler(ILogger logger) { - ThrowHelper.ThrowIfNull(logger); + ArgumentNullException.ThrowIfNull(logger); _logger = logger; } @@ -38,8 +38,8 @@ public LoggingScopeHttpMessageHandler(ILogger logger) /// or is . public LoggingScopeHttpMessageHandler(ILogger logger, HttpClientFactoryOptions options) { - ThrowHelper.ThrowIfNull(logger); - ThrowHelper.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(logger); + ArgumentNullException.ThrowIfNull(options); _logger = logger; _options = options; @@ -47,7 +47,7 @@ public LoggingScopeHttpMessageHandler(ILogger logger, HttpClientFactoryOptions o private Task SendCoreAsync(HttpRequestMessage request, bool useAsync, CancellationToken cancellationToken) { - ThrowHelper.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(request); return Core(request, useAsync, cancellationToken); async Task Core(HttpRequestMessage request, bool useAsync, CancellationToken cancellationToken) diff --git a/src/libraries/Microsoft.Extensions.Http/src/MetricsFactoryHttpMessageHandlerFilter.cs b/src/libraries/Microsoft.Extensions.Http/src/MetricsFactoryHttpMessageHandlerFilter.cs index 0a9193299f1447..2a8645b09cb3f6 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/MetricsFactoryHttpMessageHandlerFilter.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/MetricsFactoryHttpMessageHandlerFilter.cs @@ -14,14 +14,14 @@ internal sealed class MetricsFactoryHttpMessageHandlerFilter : IHttpMessageHandl public MetricsFactoryHttpMessageHandlerFilter(IMeterFactory meterFactory) { - ThrowHelper.ThrowIfNull(meterFactory); + ArgumentNullException.ThrowIfNull(meterFactory); _meterFactory = meterFactory; } public Action Configure(Action next) { - ThrowHelper.ThrowIfNull(next); + ArgumentNullException.ThrowIfNull(next); return (builder) => { diff --git a/src/libraries/Microsoft.Extensions.Http/src/Microsoft.Extensions.Http.csproj b/src/libraries/Microsoft.Extensions.Http/src/Microsoft.Extensions.Http.csproj index 035a1a485ebc54..0208f2994e2192 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/Microsoft.Extensions.Http.csproj +++ b/src/libraries/Microsoft.Extensions.Http/src/Microsoft.Extensions.Http.csproj @@ -15,8 +15,6 @@ System.Net.Http.IHttpClientFactory Link="Common\src\Extensions\NonCapturingTimer\NonCapturingTimer.cs" /> - diff --git a/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LogValuesFormatter.cs b/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LogValuesFormatter.cs index 09fe16792d9b62..711b73d5ba4973 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LogValuesFormatter.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LogValuesFormatter.cs @@ -29,7 +29,7 @@ internal sealed class LogValuesFormatter public LogValuesFormatter(string format) { - ThrowHelper.ThrowIfNull(format); + ArgumentNullException.ThrowIfNull(format); OriginalFormat = format; diff --git a/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LoggerExtensions.cs b/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LoggerExtensions.cs index 75a9b855369903..9a68ebc973db85 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LoggerExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LoggerExtensions.cs @@ -481,7 +481,7 @@ public static void Log(this ILogger logger, LogLevel logLevel, Exception? except /// An object array that contains zero or more objects to format. public static void Log(this ILogger logger, LogLevel logLevel, EventId eventId, Exception? exception, string? message, params object?[] args) { - ThrowHelper.ThrowIfNull(logger); + ArgumentNullException.ThrowIfNull(logger); logger.Log(logLevel, eventId, new FormattedLogValues(message, args), exception, _messageFormatter); } @@ -505,7 +505,7 @@ public static void Log(this ILogger logger, LogLevel logLevel, EventId eventId, string messageFormat, params object?[] args) { - ThrowHelper.ThrowIfNull(logger); + ArgumentNullException.ThrowIfNull(logger); return logger.BeginScope(new FormattedLogValues(messageFormat, args)); } diff --git a/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LoggerFactoryExtensions.cs b/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LoggerFactoryExtensions.cs index cd78f7ac5450d0..cc470f26969fe1 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LoggerFactoryExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LoggerFactoryExtensions.cs @@ -19,7 +19,7 @@ public static class LoggerFactoryExtensions /// The that was created. public static ILogger CreateLogger(this ILoggerFactory factory) { - ThrowHelper.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(factory); return new Logger(factory); } @@ -31,8 +31,8 @@ public static ILogger CreateLogger(this ILoggerFactory factory) /// The that was created. public static ILogger CreateLogger(this ILoggerFactory factory, Type type) { - ThrowHelper.ThrowIfNull(factory); - ThrowHelper.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(type); return factory.CreateLogger(TypeNameHelper.GetTypeDisplayName(type, includeGenericParameters: false, nestedTypeDelimiter: '.')); } diff --git a/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LoggerT.cs b/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LoggerT.cs index fed0e5c73324c1..493eeb40b41157 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LoggerT.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LoggerT.cs @@ -24,7 +24,7 @@ public class Logger : ILogger /// The factory. public Logger(ILoggerFactory factory) { - ThrowHelper.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(factory); _logger = factory.CreateLogger(GetCategoryName()); } diff --git a/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/Microsoft.Extensions.Logging.Abstractions.csproj b/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/Microsoft.Extensions.Logging.Abstractions.csproj index fa3f20ac4c7489..bdab5d5560e137 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/Microsoft.Extensions.Logging.Abstractions.csproj +++ b/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/Microsoft.Extensions.Logging.Abstractions.csproj @@ -29,8 +29,6 @@ Microsoft.Extensions.Logging.Abstractions.NullLogger Link="Common\src\Extensions\Logging\DebuggerDisplayFormatting.cs" /> - diff --git a/src/libraries/Microsoft.Extensions.Logging.Configuration/src/LoggerProviderConfigurationFactory.cs b/src/libraries/Microsoft.Extensions.Logging.Configuration/src/LoggerProviderConfigurationFactory.cs index 4cd41c18ff6053..f8c125fc5ff796 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Configuration/src/LoggerProviderConfigurationFactory.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Configuration/src/LoggerProviderConfigurationFactory.cs @@ -18,7 +18,7 @@ public LoggerProviderConfigurationFactory(IEnumerable conf public IConfiguration GetConfiguration(Type providerType) { - ThrowHelper.ThrowIfNull(providerType); + ArgumentNullException.ThrowIfNull(providerType); string fullName = providerType.FullName!; string? alias = ProviderAliasUtilities.GetAlias(providerType); diff --git a/src/libraries/Microsoft.Extensions.Logging.Configuration/src/Microsoft.Extensions.Logging.Configuration.csproj b/src/libraries/Microsoft.Extensions.Logging.Configuration/src/Microsoft.Extensions.Logging.Configuration.csproj index 0a41b2ea2e6b82..b8f2e7471cb685 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Configuration/src/Microsoft.Extensions.Logging.Configuration.csproj +++ b/src/libraries/Microsoft.Extensions.Logging.Configuration/src/Microsoft.Extensions.Logging.Configuration.csproj @@ -14,8 +14,6 @@ - diff --git a/src/libraries/Microsoft.Extensions.Logging.Console/src/AnsiParser.cs b/src/libraries/Microsoft.Extensions.Logging.Console/src/AnsiParser.cs index 71ea987bff1953..ff1c33fb22b85a 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Console/src/AnsiParser.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Console/src/AnsiParser.cs @@ -12,7 +12,7 @@ internal sealed class AnsiParser private readonly Action _onParseWrite; public AnsiParser(Action onParseWrite) { - ThrowHelper.ThrowIfNull(onParseWrite); + ArgumentNullException.ThrowIfNull(onParseWrite); _onParseWrite = onParseWrite; } diff --git a/src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleFormatter.cs b/src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleFormatter.cs index bcd0bcbdf25ec0..81f4e1671c905d 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleFormatter.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleFormatter.cs @@ -18,7 +18,7 @@ public abstract class ConsoleFormatter /// protected ConsoleFormatter(string name) { - ThrowHelper.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(name); Name = name; } diff --git a/src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleLogger.cs b/src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleLogger.cs index c030eb059e372a..75a831ff84f0cc 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleLogger.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleLogger.cs @@ -26,7 +26,7 @@ internal ConsoleLogger( IExternalScopeProvider? scopeProvider, ConsoleLoggerOptions options) { - ThrowHelper.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(name); _name = name; _queueProcessor = loggerProcessor; @@ -50,7 +50,7 @@ public void Log(LogLevel logLevel, EventId eventId, TState state, Except return; } - ThrowHelper.ThrowIfNull(formatter); + ArgumentNullException.ThrowIfNull(formatter); t_stringWriter ??= new StringWriter(); LogEntry logEntry = new LogEntry(logLevel, _name, eventId, state, exception, formatter); @@ -73,7 +73,7 @@ public void Log(LogLevel logLevel, EventId eventId, TState state, Except /// public void LogRecords(IEnumerable records) { - ThrowHelper.ThrowIfNull(records); + ArgumentNullException.ThrowIfNull(records); StringWriter writer = t_stringWriter ??= new StringWriter(); diff --git a/src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleLoggerExtensions.cs b/src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleLoggerExtensions.cs index 0dcdcee2a3c9ea..2d9525020a76c5 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleLoggerExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleLoggerExtensions.cs @@ -10,7 +10,6 @@ using Microsoft.Extensions.Logging.Configuration; using Microsoft.Extensions.Logging.Console; using Microsoft.Extensions.Options; -using ThrowHelper = System.ThrowHelper; namespace Microsoft.Extensions.Logging { @@ -50,7 +49,7 @@ public static ILoggingBuilder AddConsole(this ILoggingBuilder builder) /// A delegate to configure the . public static ILoggingBuilder AddConsole(this ILoggingBuilder builder, Action configure) { - ThrowHelper.ThrowIfNull(configure); + ArgumentNullException.ThrowIfNull(configure); builder.AddConsole(); builder.Services.Configure(configure); @@ -112,7 +111,7 @@ public static ILoggingBuilder AddSystemdConsole(this ILoggingBuilder builder) => internal static ILoggingBuilder AddConsoleWithFormatter(this ILoggingBuilder builder, string name, Action configure) where TOptions : ConsoleFormatterOptions { - ThrowHelper.ThrowIfNull(configure); + ArgumentNullException.ThrowIfNull(configure); builder.AddFormatterWithName(name); builder.Services.Configure(configure); @@ -147,7 +146,7 @@ private static ILoggingBuilder AddFormatterWithName(this ILoggingBuilder builder where TOptions : ConsoleFormatterOptions where TFormatter : ConsoleFormatter { - ThrowHelper.ThrowIfNull(configure); + ArgumentNullException.ThrowIfNull(configure); builder.AddConsoleFormatter(); builder.Services.Configure(configure); diff --git a/src/libraries/Microsoft.Extensions.Logging.Console/src/Microsoft.Extensions.Logging.Console.csproj b/src/libraries/Microsoft.Extensions.Logging.Console/src/Microsoft.Extensions.Logging.Console.csproj index 217bfaed0470f8..5727e4e667586c 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Console/src/Microsoft.Extensions.Logging.Console.csproj +++ b/src/libraries/Microsoft.Extensions.Logging.Console/src/Microsoft.Extensions.Logging.Console.csproj @@ -19,7 +19,6 @@ - diff --git a/src/libraries/Microsoft.Extensions.Logging.Debug/src/DebugLogger.cs b/src/libraries/Microsoft.Extensions.Logging.Debug/src/DebugLogger.cs index ca0d5474216902..a0690eab7bb5ab 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Debug/src/DebugLogger.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Debug/src/DebugLogger.cs @@ -43,7 +43,7 @@ public void Log(LogLevel logLevel, EventId eventId, TState state, Except return; } - ThrowHelper.ThrowIfNull(formatter); + ArgumentNullException.ThrowIfNull(formatter); string message = formatter(state, exception); diff --git a/src/libraries/Microsoft.Extensions.Logging.Debug/src/Microsoft.Extensions.Logging.Debug.csproj b/src/libraries/Microsoft.Extensions.Logging.Debug/src/Microsoft.Extensions.Logging.Debug.csproj index da5ffceed4231e..37f81bd6917335 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Debug/src/Microsoft.Extensions.Logging.Debug.csproj +++ b/src/libraries/Microsoft.Extensions.Logging.Debug/src/Microsoft.Extensions.Logging.Debug.csproj @@ -12,8 +12,6 @@ Link="Common\src\Extensions\Logging\NullExternalScopeProvider.cs" /> - diff --git a/src/libraries/Microsoft.Extensions.Logging.EventLog/src/EventLogLogger.cs b/src/libraries/Microsoft.Extensions.Logging.EventLog/src/EventLogLogger.cs index a5d6e6a6a3c5ad..d8c0ab72821830 100644 --- a/src/libraries/Microsoft.Extensions.Logging.EventLog/src/EventLogLogger.cs +++ b/src/libraries/Microsoft.Extensions.Logging.EventLog/src/EventLogLogger.cs @@ -29,8 +29,8 @@ internal sealed class EventLogLogger : ILogger /// The . public EventLogLogger(string name, EventLogSettings settings, IExternalScopeProvider? externalScopeProvider) { - ThrowHelper.ThrowIfNull(name); - ThrowHelper.ThrowIfNull(settings); + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(settings); _name = name; _settings = settings; @@ -79,7 +79,7 @@ public void Log( return; } - ThrowHelper.ThrowIfNull(formatter); + ArgumentNullException.ThrowIfNull(formatter); string message = formatter(state, exception); diff --git a/src/libraries/Microsoft.Extensions.Logging.EventLog/src/EventLoggerFactoryExtensions.cs b/src/libraries/Microsoft.Extensions.Logging.EventLog/src/EventLoggerFactoryExtensions.cs index 3b01b7de138fb2..ef7123df898f8c 100644 --- a/src/libraries/Microsoft.Extensions.Logging.EventLog/src/EventLoggerFactoryExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Logging.EventLog/src/EventLoggerFactoryExtensions.cs @@ -23,8 +23,8 @@ public static class EventLoggerFactoryExtensions [Obsolete("This method is retained only for compatibility. The recommended alternative is AddEventLog(this ILoggingBuilder builder).", error: true)] public static ILoggerFactory AddEventLog(this ILoggerFactory factory, EventLog.EventLogSettings settings) { - ThrowHelper.ThrowIfNull(factory); - ThrowHelper.ThrowIfNull(settings); + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(settings); factory.AddProvider(new EventLogLoggerProvider(settings)); return factory; @@ -55,7 +55,7 @@ public static ILoggerFactory AddEventLog(this ILoggerFactory factory, LogLevel m /// The so that additional calls can be chained. public static ILoggingBuilder AddEventLog(this ILoggingBuilder builder) { - ThrowHelper.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(builder); builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton()); @@ -70,8 +70,8 @@ public static ILoggingBuilder AddEventLog(this ILoggingBuilder builder) /// The so that additional calls can be chained. public static ILoggingBuilder AddEventLog(this ILoggingBuilder builder, EventLogSettings settings) { - ThrowHelper.ThrowIfNull(builder); - ThrowHelper.ThrowIfNull(settings); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(settings); builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton(new EventLogLoggerProvider(settings))); @@ -86,7 +86,7 @@ public static ILoggingBuilder AddEventLog(this ILoggingBuilder builder, EventLog /// The so that additional calls can be chained. public static ILoggingBuilder AddEventLog(this ILoggingBuilder builder, Action configure) { - ThrowHelper.ThrowIfNull(configure); + ArgumentNullException.ThrowIfNull(configure); builder.AddEventLog(); builder.Services.Configure(configure); diff --git a/src/libraries/Microsoft.Extensions.Logging.EventLog/src/Microsoft.Extensions.Logging.EventLog.csproj b/src/libraries/Microsoft.Extensions.Logging.EventLog/src/Microsoft.Extensions.Logging.EventLog.csproj index 31d7e5e17f7e88..ebe0f0b2e24993 100644 --- a/src/libraries/Microsoft.Extensions.Logging.EventLog/src/Microsoft.Extensions.Logging.EventLog.csproj +++ b/src/libraries/Microsoft.Extensions.Logging.EventLog/src/Microsoft.Extensions.Logging.EventLog.csproj @@ -14,8 +14,6 @@ Link="Common\src\Extensions\Logging\NullExternalScopeProvider.cs" /> - diff --git a/src/libraries/Microsoft.Extensions.Logging.EventSource/src/EventSourceLoggerFactoryExtensions.cs b/src/libraries/Microsoft.Extensions.Logging.EventSource/src/EventSourceLoggerFactoryExtensions.cs index 1c25028f8a200d..d5b0fb98ae32b4 100644 --- a/src/libraries/Microsoft.Extensions.Logging.EventSource/src/EventSourceLoggerFactoryExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Logging.EventSource/src/EventSourceLoggerFactoryExtensions.cs @@ -24,7 +24,7 @@ public static class EventSourceLoggerFactoryExtensions [Obsolete("This method is retained only for compatibility. The recommended alternative is AddEventSourceLogger(this ILoggingBuilder builder).", error: true)] public static ILoggerFactory AddEventSourceLogger(this ILoggerFactory factory) { - ThrowHelper.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(factory); factory.AddProvider(new EventSourceLoggerProvider(LoggingEventSource.Instance)); @@ -38,7 +38,7 @@ public static ILoggerFactory AddEventSourceLogger(this ILoggerFactory factory) /// The so that additional calls can be chained. public static ILoggingBuilder AddEventSourceLogger(this ILoggingBuilder builder) { - ThrowHelper.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(builder); builder.Services.TryAddSingleton(LoggingEventSource.Instance); builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton()); diff --git a/src/libraries/Microsoft.Extensions.Logging.EventSource/src/EventSourceLoggerProvider.cs b/src/libraries/Microsoft.Extensions.Logging.EventSource/src/EventSourceLoggerProvider.cs index 6a5343d12129e1..e798d772d06eed 100644 --- a/src/libraries/Microsoft.Extensions.Logging.EventSource/src/EventSourceLoggerProvider.cs +++ b/src/libraries/Microsoft.Extensions.Logging.EventSource/src/EventSourceLoggerProvider.cs @@ -26,7 +26,7 @@ public class EventSourceLoggerProvider : ILoggerProvider /// The logging event source. public EventSourceLoggerProvider(LoggingEventSource eventSource) { - ThrowHelper.ThrowIfNull(eventSource); + ArgumentNullException.ThrowIfNull(eventSource); _eventSource = eventSource; _factoryID = Interlocked.Increment(ref _globalFactoryID); diff --git a/src/libraries/Microsoft.Extensions.Logging.EventSource/src/Microsoft.Extensions.Logging.EventSource.csproj b/src/libraries/Microsoft.Extensions.Logging.EventSource/src/Microsoft.Extensions.Logging.EventSource.csproj index 93f6eb01c75a1d..7be872efbc3f44 100644 --- a/src/libraries/Microsoft.Extensions.Logging.EventSource/src/Microsoft.Extensions.Logging.EventSource.csproj +++ b/src/libraries/Microsoft.Extensions.Logging.EventSource/src/Microsoft.Extensions.Logging.EventSource.csproj @@ -15,8 +15,6 @@ Link="Common\src\Extensions\Logging\NullExternalScopeProvider.cs" /> - diff --git a/src/libraries/Microsoft.Extensions.Logging.TraceSource/src/Microsoft.Extensions.Logging.TraceSource.csproj b/src/libraries/Microsoft.Extensions.Logging.TraceSource/src/Microsoft.Extensions.Logging.TraceSource.csproj index 6568c9908c14f2..a5740c2c73f69f 100644 --- a/src/libraries/Microsoft.Extensions.Logging.TraceSource/src/Microsoft.Extensions.Logging.TraceSource.csproj +++ b/src/libraries/Microsoft.Extensions.Logging.TraceSource/src/Microsoft.Extensions.Logging.TraceSource.csproj @@ -7,10 +7,6 @@ TraceSource logger provider implementation for Microsoft.Extensions.Logging. This logger logs messages to a trace listener by writing messages with System.Diagnostics.TraceSource.TraceEvent(). - - - - diff --git a/src/libraries/Microsoft.Extensions.Logging.TraceSource/src/TraceSourceFactoryExtensions.cs b/src/libraries/Microsoft.Extensions.Logging.TraceSource/src/TraceSourceFactoryExtensions.cs index 863a069d50366c..f3100989a31515 100644 --- a/src/libraries/Microsoft.Extensions.Logging.TraceSource/src/TraceSourceFactoryExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Logging.TraceSource/src/TraceSourceFactoryExtensions.cs @@ -25,9 +25,9 @@ public static class TraceSourceFactoryExtensions [Obsolete("This method is retained only for compatibility. The recommended alternative is AddTraceSource(this ILoggingBuilder builder).", error: true)] public static ILoggerFactory AddTraceSource(this ILoggerFactory factory, System.Diagnostics.SourceSwitch sourceSwitch, System.Diagnostics.TraceListener listener) { - ThrowHelper.ThrowIfNull(factory); - ThrowHelper.ThrowIfNull(sourceSwitch); - ThrowHelper.ThrowIfNull(listener); + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(sourceSwitch); + ArgumentNullException.ThrowIfNull(listener); factory.AddProvider(new TraceSourceLoggerProvider(sourceSwitch, listener)); @@ -44,8 +44,8 @@ public static ILoggerFactory AddTraceSource(this ILoggerFactory factory, System. [Obsolete("This method is retained only for compatibility. The recommended alternative is AddTraceSource(this ILoggingBuilder builder).", error: true)] public static ILoggerFactory AddTraceSource(this ILoggerFactory factory, System.Diagnostics.SourceSwitch sourceSwitch) { - ThrowHelper.ThrowIfNull(factory); - ThrowHelper.ThrowIfNull(sourceSwitch); + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(sourceSwitch); factory.AddProvider(new TraceSourceLoggerProvider(sourceSwitch)); @@ -63,9 +63,9 @@ public static ILoggerFactory AddTraceSource(this ILoggerFactory factory, System. [Obsolete("This method is retained only for compatibility. The recommended alternative is AddTraceSource(this ILoggingBuilder builder).", error: true)] public static ILoggerFactory AddTraceSource(this ILoggerFactory factory, string switchName, System.Diagnostics.TraceListener listener) { - ThrowHelper.ThrowIfNull(factory); - ThrowHelper.ThrowIfNull(switchName); - ThrowHelper.ThrowIfNull(listener); + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(switchName); + ArgumentNullException.ThrowIfNull(listener); factory.AddProvider(new TraceSourceLoggerProvider(new SourceSwitch(switchName), listener)); @@ -82,8 +82,8 @@ public static ILoggerFactory AddTraceSource(this ILoggerFactory factory, string [Obsolete("This method is retained only for compatibility. The recommended alternative is AddTraceSource(this ILoggingBuilder builder).", error: true)] public static ILoggerFactory AddTraceSource(this ILoggerFactory factory, string switchName) { - ThrowHelper.ThrowIfNull(factory); - ThrowHelper.ThrowIfNull(switchName); + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(switchName); factory.AddProvider(new TraceSourceLoggerProvider(new SourceSwitch(switchName))); @@ -100,8 +100,8 @@ public static ILoggingBuilder AddTraceSource( this ILoggingBuilder builder, string switchName) { - ThrowHelper.ThrowIfNull(builder); - ThrowHelper.ThrowIfNull(switchName); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(switchName); return builder.AddTraceSource(new SourceSwitch(switchName)); } @@ -118,9 +118,9 @@ public static ILoggingBuilder AddTraceSource( string switchName, TraceListener listener) { - ThrowHelper.ThrowIfNull(builder); - ThrowHelper.ThrowIfNull(switchName); - ThrowHelper.ThrowIfNull(listener); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(switchName); + ArgumentNullException.ThrowIfNull(listener); return builder.AddTraceSource(new SourceSwitch(switchName), listener); } @@ -135,8 +135,8 @@ public static ILoggingBuilder AddTraceSource( this ILoggingBuilder builder, SourceSwitch sourceSwitch) { - ThrowHelper.ThrowIfNull(builder); - ThrowHelper.ThrowIfNull(sourceSwitch); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(sourceSwitch); builder.Services.AddSingleton(_ => new TraceSourceLoggerProvider(sourceSwitch)); @@ -155,9 +155,9 @@ public static ILoggingBuilder AddTraceSource( SourceSwitch sourceSwitch, TraceListener listener) { - ThrowHelper.ThrowIfNull(builder); - ThrowHelper.ThrowIfNull(sourceSwitch); - ThrowHelper.ThrowIfNull(listener); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(sourceSwitch); + ArgumentNullException.ThrowIfNull(listener); builder.Services.AddSingleton(_ => new TraceSourceLoggerProvider(sourceSwitch, listener)); diff --git a/src/libraries/Microsoft.Extensions.Logging.TraceSource/src/TraceSourceLoggerProvider.cs b/src/libraries/Microsoft.Extensions.Logging.TraceSource/src/TraceSourceLoggerProvider.cs index d5aa6ffefda55d..d3e4d8aea506dc 100644 --- a/src/libraries/Microsoft.Extensions.Logging.TraceSource/src/TraceSourceLoggerProvider.cs +++ b/src/libraries/Microsoft.Extensions.Logging.TraceSource/src/TraceSourceLoggerProvider.cs @@ -37,7 +37,7 @@ public TraceSourceLoggerProvider(SourceSwitch rootSourceSwitch) /// The to use. public TraceSourceLoggerProvider(SourceSwitch rootSourceSwitch, TraceListener? rootTraceListener) { - ThrowHelper.ThrowIfNull(rootSourceSwitch); + ArgumentNullException.ThrowIfNull(rootSourceSwitch); _rootSourceSwitch = rootSourceSwitch; _rootTraceListener = rootTraceListener; diff --git a/src/libraries/Microsoft.Extensions.Logging/src/LoggerFactory.cs b/src/libraries/Microsoft.Extensions.Logging/src/LoggerFactory.cs index 8260ea6381ba70..3ff5e4714613ab 100644 --- a/src/libraries/Microsoft.Extensions.Logging/src/LoggerFactory.cs +++ b/src/libraries/Microsoft.Extensions.Logging/src/LoggerFactory.cs @@ -172,7 +172,7 @@ public void AddProvider(ILoggerProvider provider) throw new ObjectDisposedException(nameof(LoggerFactory)); } - ThrowHelper.ThrowIfNull(provider); + ArgumentNullException.ThrowIfNull(provider); lock (_sync) { diff --git a/src/libraries/Microsoft.Extensions.Logging/src/LoggingServiceCollectionExtensions.cs b/src/libraries/Microsoft.Extensions.Logging/src/LoggingServiceCollectionExtensions.cs index eb324bd8bb5b03..ef8433cdafa5d8 100644 --- a/src/libraries/Microsoft.Extensions.Logging/src/LoggingServiceCollectionExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Logging/src/LoggingServiceCollectionExtensions.cs @@ -31,7 +31,7 @@ public static IServiceCollection AddLogging(this IServiceCollection services) /// The so that additional calls can be chained. public static IServiceCollection AddLogging(this IServiceCollection services, Action configure) { - ThrowHelper.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(services); services.AddOptions(); diff --git a/src/libraries/Microsoft.Extensions.Logging/src/Microsoft.Extensions.Logging.csproj b/src/libraries/Microsoft.Extensions.Logging/src/Microsoft.Extensions.Logging.csproj index 8501fd465db6e5..f8829a5a0a0cd4 100644 --- a/src/libraries/Microsoft.Extensions.Logging/src/Microsoft.Extensions.Logging.csproj +++ b/src/libraries/Microsoft.Extensions.Logging/src/Microsoft.Extensions.Logging.csproj @@ -16,8 +16,6 @@ Link="Common\src\Extensions\Logging\NullScope.cs" /> - diff --git a/src/libraries/Microsoft.Extensions.Logging/tests/DI.Common/Common/src/LogValuesAssert.cs b/src/libraries/Microsoft.Extensions.Logging/tests/DI.Common/Common/src/LogValuesAssert.cs index 6ebdf7d1c4c4ef..996ebdabb7a475 100644 --- a/src/libraries/Microsoft.Extensions.Logging/tests/DI.Common/Common/src/LogValuesAssert.cs +++ b/src/libraries/Microsoft.Extensions.Logging/tests/DI.Common/Common/src/LogValuesAssert.cs @@ -34,12 +34,11 @@ public static void Contains( IEnumerable> expectedValues, IEnumerable> actualValues) { - if (expectedValues == null) + if (expectedValues is null) { throw new ArgumentNullException(nameof(expectedValues)); } - - if (actualValues == null) + if (actualValues is null) { throw new ArgumentNullException(nameof(actualValues)); } diff --git a/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/ConfigurationChangeTokenSource.cs b/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/ConfigurationChangeTokenSource.cs index 3fbc7b9c85de0c..416674a0166b4b 100644 --- a/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/ConfigurationChangeTokenSource.cs +++ b/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/ConfigurationChangeTokenSource.cs @@ -31,7 +31,7 @@ public ConfigurationChangeTokenSource(IConfiguration config) : this(Options.Defa /// The configuration instance. public ConfigurationChangeTokenSource(string? name, IConfiguration config) { - ThrowHelper.ThrowIfNull(config); + ArgumentNullException.ThrowIfNull(config); _config = config; Name = name ?? Options.DefaultName; diff --git a/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/ConfigureFromConfigurationOptions.cs b/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/ConfigureFromConfigurationOptions.cs index 4d34c429f44487..d85a8ce9b555b2 100644 --- a/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/ConfigureFromConfigurationOptions.cs +++ b/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/ConfigureFromConfigurationOptions.cs @@ -27,7 +27,7 @@ public class ConfigureFromConfigurationOptions<[DynamicallyAccessedMembers(Dynam public ConfigureFromConfigurationOptions(IConfiguration config) : base(options => ConfigurationBinder.Bind(config, options)) { - ThrowHelper.ThrowIfNull(config); + ArgumentNullException.ThrowIfNull(config); } } } diff --git a/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/Microsoft.Extensions.Options.ConfigurationExtensions.csproj b/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/Microsoft.Extensions.Options.ConfigurationExtensions.csproj index 7ebe9baf9402c9..3231765bade214 100644 --- a/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/Microsoft.Extensions.Options.ConfigurationExtensions.csproj +++ b/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/Microsoft.Extensions.Options.ConfigurationExtensions.csproj @@ -7,10 +7,6 @@ Provides additional configuration specific functionality related to Options. - - - - diff --git a/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/NamedConfigureFromConfigurationOptions.cs b/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/NamedConfigureFromConfigurationOptions.cs index 5eb03033e1db9d..112e572f7af28e 100644 --- a/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/NamedConfigureFromConfigurationOptions.cs +++ b/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/NamedConfigureFromConfigurationOptions.cs @@ -37,7 +37,7 @@ public NamedConfigureFromConfigurationOptions(string? name, IConfiguration confi public NamedConfigureFromConfigurationOptions(string? name, IConfiguration config, Action? configureBinder) : base(name, options => config.Bind(options, configureBinder)) { - ThrowHelper.ThrowIfNull(config); + ArgumentNullException.ThrowIfNull(config); } } } diff --git a/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/OptionsBuilderConfigurationExtensions.cs b/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/OptionsBuilderConfigurationExtensions.cs index 3eff0ee65bf9a4..2deb91d97ad5b8 100644 --- a/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/OptionsBuilderConfigurationExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/OptionsBuilderConfigurationExtensions.cs @@ -40,7 +40,7 @@ public static class OptionsBuilderConfigurationExtensions [RequiresUnreferencedCode(TrimmingRequiredUnreferencedCodeMessage)] public static OptionsBuilder Bind<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TOptions>(this OptionsBuilder optionsBuilder, IConfiguration config, Action? configureBinder) where TOptions : class { - ThrowHelper.ThrowIfNull(optionsBuilder); + ArgumentNullException.ThrowIfNull(optionsBuilder); optionsBuilder.Services.Configure(optionsBuilder.Name, config, configureBinder); return optionsBuilder; @@ -67,8 +67,8 @@ public static class OptionsBuilderConfigurationExtensions Action? configureBinder = null) where TOptions : class { - ThrowHelper.ThrowIfNull(optionsBuilder); - ThrowHelper.ThrowIfNull(configSectionPath); + ArgumentNullException.ThrowIfNull(optionsBuilder); + ArgumentNullException.ThrowIfNull(configSectionPath); optionsBuilder.Configure((opts, config) => { diff --git a/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/OptionsConfigurationServiceCollectionExtensions.cs b/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/OptionsConfigurationServiceCollectionExtensions.cs index aae277058fe3c4..9fa33a2ec2bded 100644 --- a/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/OptionsConfigurationServiceCollectionExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/OptionsConfigurationServiceCollectionExtensions.cs @@ -66,8 +66,8 @@ public static class OptionsConfigurationServiceCollectionExtensions public static IServiceCollection Configure<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TOptions>(this IServiceCollection services, string? name, IConfiguration config, Action? configureBinder) where TOptions : class { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(config); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(config); services.AddOptions(); services.AddSingleton>(new ConfigurationChangeTokenSource(name, config)); diff --git a/src/libraries/Microsoft.Extensions.Options.DataAnnotations/src/DataAnnotationValidateOptions.cs b/src/libraries/Microsoft.Extensions.Options.DataAnnotations/src/DataAnnotationValidateOptions.cs index aadf4d4d1cbec9..2b85690478eff2 100644 --- a/src/libraries/Microsoft.Extensions.Options.DataAnnotations/src/DataAnnotationValidateOptions.cs +++ b/src/libraries/Microsoft.Extensions.Options.DataAnnotations/src/DataAnnotationValidateOptions.cs @@ -53,7 +53,7 @@ public ValidateOptionsResult Validate(string? name, TOptions options) } // Ensure options are provided to validate against - ThrowHelper.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(options); var validationResults = new List(); HashSet? visited = null; diff --git a/src/libraries/Microsoft.Extensions.Options.DataAnnotations/src/Microsoft.Extensions.Options.DataAnnotations.csproj b/src/libraries/Microsoft.Extensions.Options.DataAnnotations/src/Microsoft.Extensions.Options.DataAnnotations.csproj index 0fdd978a1cfb1b..7fc21d972053f3 100644 --- a/src/libraries/Microsoft.Extensions.Options.DataAnnotations/src/Microsoft.Extensions.Options.DataAnnotations.csproj +++ b/src/libraries/Microsoft.Extensions.Options.DataAnnotations/src/Microsoft.Extensions.Options.DataAnnotations.csproj @@ -7,10 +7,6 @@ Provides additional DataAnnotations specific functionality related to Options. - - - - diff --git a/src/libraries/Microsoft.Extensions.Options/src/ConfigureNamedOptions.cs b/src/libraries/Microsoft.Extensions.Options/src/ConfigureNamedOptions.cs index d9f9595c161488..c459a30a725191 100644 --- a/src/libraries/Microsoft.Extensions.Options/src/ConfigureNamedOptions.cs +++ b/src/libraries/Microsoft.Extensions.Options/src/ConfigureNamedOptions.cs @@ -39,7 +39,7 @@ public ConfigureNamedOptions(string? name, Action? action) /// The options instance to configure. public virtual void Configure(string? name, TOptions options) { - ThrowHelper.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(options); // Null name is used to configure all named options. if (Name == null || name == Name) @@ -99,7 +99,7 @@ public ConfigureNamedOptions(string? name, TDep dependency, ActionThe options instance to configure. public virtual void Configure(string? name, TOptions options) { - ThrowHelper.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(options); // Null name is used to configure all named options. if (Name == null || name == Name) @@ -168,7 +168,7 @@ public ConfigureNamedOptions(string? name, TDep1 dependency, TDep2 dependency2, /// The options instance to configure. public virtual void Configure(string? name, TOptions options) { - ThrowHelper.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(options); // Null name is used to configure all named options. if (Name == null || name == Name) @@ -246,7 +246,7 @@ public ConfigureNamedOptions(string? name, TDep1 dependency, TDep2 dependency2, /// The options instance to configure. public virtual void Configure(string? name, TOptions options) { - ThrowHelper.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(options); // Null name is used to configure all named options. if (Name == null || name == Name) @@ -333,7 +333,7 @@ public ConfigureNamedOptions(string? name, TDep1 dependency1, TDep2 dependency2, /// The options instance to configure. public virtual void Configure(string? name, TOptions options) { - ThrowHelper.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(options); // Null name is used to configure all named options. if (Name == null || name == Name) @@ -429,7 +429,7 @@ public ConfigureNamedOptions(string? name, TDep1 dependency1, TDep2 dependency2, /// The options instance to configure. public virtual void Configure(string? name, TOptions options) { - ThrowHelper.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(options); // Null name is used to configure all named options. if (Name == null || name == Name) diff --git a/src/libraries/Microsoft.Extensions.Options/src/ConfigureOptions.cs b/src/libraries/Microsoft.Extensions.Options/src/ConfigureOptions.cs index b6be8af03cc07e..7d64bf6521fc0e 100644 --- a/src/libraries/Microsoft.Extensions.Options/src/ConfigureOptions.cs +++ b/src/libraries/Microsoft.Extensions.Options/src/ConfigureOptions.cs @@ -31,7 +31,7 @@ public ConfigureOptions(Action? action) /// The options instance to configure. public virtual void Configure(TOptions options) { - ThrowHelper.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(options); Action?.Invoke(options); } diff --git a/src/libraries/Microsoft.Extensions.Options/src/Microsoft.Extensions.Options.csproj b/src/libraries/Microsoft.Extensions.Options/src/Microsoft.Extensions.Options.csproj index c7ea3e00049e3e..54b1d96ddbfaca 100644 --- a/src/libraries/Microsoft.Extensions.Options/src/Microsoft.Extensions.Options.csproj +++ b/src/libraries/Microsoft.Extensions.Options/src/Microsoft.Extensions.Options.csproj @@ -7,10 +7,6 @@ Provides a strongly typed way of specifying and accessing settings using dependency injection. - - - - diff --git a/src/libraries/Microsoft.Extensions.Options/src/OptionsBuilder.cs b/src/libraries/Microsoft.Extensions.Options/src/OptionsBuilder.cs index e35b76c4fa7698..37704e947e9eb3 100644 --- a/src/libraries/Microsoft.Extensions.Options/src/OptionsBuilder.cs +++ b/src/libraries/Microsoft.Extensions.Options/src/OptionsBuilder.cs @@ -31,7 +31,7 @@ public class OptionsBuilder where TOptions : class /// The default name of the instance; if , is used. public OptionsBuilder(IServiceCollection services, string? name) { - ThrowHelper.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(services); Services = services; Name = name ?? Options.DefaultName; @@ -47,7 +47,7 @@ public OptionsBuilder(IServiceCollection services, string? name) /// public virtual OptionsBuilder Configure(Action configureOptions) { - ThrowHelper.ThrowIfNull(configureOptions); + ArgumentNullException.ThrowIfNull(configureOptions); Services.AddSingleton>(new ConfigureNamedOptions(Name, configureOptions)); return this; @@ -65,7 +65,7 @@ public virtual OptionsBuilder Configure(Action configureOpti public virtual OptionsBuilder Configure(Action configureOptions) where TDep : class { - ThrowHelper.ThrowIfNull(configureOptions); + ArgumentNullException.ThrowIfNull(configureOptions); Services.AddTransient>(sp => new ConfigureNamedOptions(Name, sp.GetRequiredService(), configureOptions)); @@ -86,7 +86,7 @@ public virtual OptionsBuilder Configure(Action>(sp => new ConfigureNamedOptions(Name, sp.GetRequiredService(), sp.GetRequiredService(), configureOptions)); @@ -109,7 +109,7 @@ public virtual OptionsBuilder Configure(Action>( sp => new ConfigureNamedOptions( @@ -139,7 +139,7 @@ public virtual OptionsBuilder Configure(Ac where TDep3 : class where TDep4 : class { - ThrowHelper.ThrowIfNull(configureOptions); + ArgumentNullException.ThrowIfNull(configureOptions); Services.AddTransient>( sp => new ConfigureNamedOptions( @@ -172,7 +172,7 @@ public virtual OptionsBuilder Configure>( sp => new ConfigureNamedOptions( @@ -196,7 +196,7 @@ public virtual OptionsBuilder Configure public virtual OptionsBuilder PostConfigure(Action configureOptions) { - ThrowHelper.ThrowIfNull(configureOptions); + ArgumentNullException.ThrowIfNull(configureOptions); Services.AddSingleton>(new PostConfigureOptions(Name, configureOptions)); return this; @@ -214,7 +214,7 @@ public virtual OptionsBuilder PostConfigure(Action configure public virtual OptionsBuilder PostConfigure(Action configureOptions) where TDep : class { - ThrowHelper.ThrowIfNull(configureOptions); + ArgumentNullException.ThrowIfNull(configureOptions); Services.AddTransient>(sp => new PostConfigureOptions(Name, sp.GetRequiredService(), configureOptions)); @@ -235,7 +235,7 @@ public virtual OptionsBuilder PostConfigure(Action>(sp => new PostConfigureOptions(Name, sp.GetRequiredService(), sp.GetRequiredService(), configureOptions)); @@ -258,7 +258,7 @@ public virtual OptionsBuilder PostConfigure(Actio where TDep2 : class where TDep3 : class { - ThrowHelper.ThrowIfNull(configureOptions); + ArgumentNullException.ThrowIfNull(configureOptions); Services.AddTransient>( sp => new PostConfigureOptions( @@ -288,7 +288,7 @@ public virtual OptionsBuilder PostConfigure>( sp => new PostConfigureOptions( @@ -321,7 +321,7 @@ public virtual OptionsBuilder PostConfigure>( sp => new PostConfigureOptions( @@ -351,7 +351,7 @@ public virtual OptionsBuilder Validate(Func validation /// The current . public virtual OptionsBuilder Validate(Func validation, string failureMessage) { - ThrowHelper.ThrowIfNull(validation); + ArgumentNullException.ThrowIfNull(validation); Services.AddSingleton>(new ValidateOptions(Name, validation, failureMessage)); return this; @@ -375,7 +375,7 @@ public virtual OptionsBuilder Validate(FuncThe current . public virtual OptionsBuilder Validate(Func validation, string failureMessage) where TDep : notnull { - ThrowHelper.ThrowIfNull(validation); + ArgumentNullException.ThrowIfNull(validation); Services.AddTransient>(sp => new ValidateOptions(Name, sp.GetRequiredService(), validation, failureMessage)); @@ -406,7 +406,7 @@ public virtual OptionsBuilder Validate(Func>(sp => new ValidateOptions(Name, @@ -445,7 +445,7 @@ public virtual OptionsBuilder Validate(Func>(sp => new ValidateOptions(Name, @@ -489,7 +489,7 @@ public virtual OptionsBuilder Validate(Fun where TDep3 : notnull where TDep4 : notnull { - ThrowHelper.ThrowIfNull(validation); + ArgumentNullException.ThrowIfNull(validation); Services.AddTransient>(sp => new ValidateOptions(Name, @@ -538,7 +538,7 @@ public virtual OptionsBuilder Validate>(sp => new ValidateOptions(Name, diff --git a/src/libraries/Microsoft.Extensions.Options/src/OptionsBuilderExtensions.cs b/src/libraries/Microsoft.Extensions.Options/src/OptionsBuilderExtensions.cs index 92eb966ca30ddd..789d6718f41519 100644 --- a/src/libraries/Microsoft.Extensions.Options/src/OptionsBuilderExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Options/src/OptionsBuilderExtensions.cs @@ -24,7 +24,7 @@ public static class OptionsBuilderExtensions public static OptionsBuilder ValidateOnStart<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] TOptions>(this OptionsBuilder optionsBuilder) where TOptions : class { - ThrowHelper.ThrowIfNull(optionsBuilder); + ArgumentNullException.ThrowIfNull(optionsBuilder); optionsBuilder.Services.TryAddTransient(); optionsBuilder.Services.AddOptions() diff --git a/src/libraries/Microsoft.Extensions.Options/src/OptionsCache.cs b/src/libraries/Microsoft.Extensions.Options/src/OptionsCache.cs index a47ba7061aab07..ac6bab4c221656 100644 --- a/src/libraries/Microsoft.Extensions.Options/src/OptionsCache.cs +++ b/src/libraries/Microsoft.Extensions.Options/src/OptionsCache.cs @@ -30,7 +30,7 @@ public class OptionsCache<[DynamicallyAccessedMembers(Options.DynamicallyAccesse /// The options instance. public virtual TOptions GetOrAdd(string? name, Func createOptions) { - ThrowHelper.ThrowIfNull(createOptions); + ArgumentNullException.ThrowIfNull(createOptions); name ??= Options.DefaultName; Lazy value; @@ -95,7 +95,7 @@ internal bool TryGetValue(string? name, [MaybeNullWhen(false)] out TOptions opti /// if the option was added; if the name already exists. public virtual bool TryAdd(string? name, TOptions options) { - ThrowHelper.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(options); return _cache.TryAdd(name ?? Options.DefaultName, new Lazy( #if !(NET || NETSTANDARD2_1) diff --git a/src/libraries/Microsoft.Extensions.Options/src/OptionsServiceCollectionExtensions.cs b/src/libraries/Microsoft.Extensions.Options/src/OptionsServiceCollectionExtensions.cs index 29cd88843687f0..00b36efbb4ca75 100644 --- a/src/libraries/Microsoft.Extensions.Options/src/OptionsServiceCollectionExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Options/src/OptionsServiceCollectionExtensions.cs @@ -21,7 +21,7 @@ public static class OptionsServiceCollectionExtensions /// The so that additional calls can be chained. public static IServiceCollection AddOptions(this IServiceCollection services) { - ThrowHelper.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(services); services.TryAdd(ServiceDescriptor.Singleton(typeof(IOptions<>), typeof(UnnamedOptionsManager<>))); services.TryAdd(ServiceDescriptor.Scoped(typeof(IOptionsSnapshot<>), typeof(OptionsManager<>))); @@ -95,8 +95,8 @@ public static IServiceCollection Configure(this IServiceCollection ser public static IServiceCollection Configure(this IServiceCollection services, string? name, Action configureOptions) where TOptions : class { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(configureOptions); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configureOptions); services.AddOptions(); services.AddSingleton>(new ConfigureNamedOptions(name, configureOptions)); @@ -136,8 +136,8 @@ public static IServiceCollection PostConfigure(this IServiceCollection public static IServiceCollection PostConfigure(this IServiceCollection services, string? name, Action configureOptions) where TOptions : class { - ThrowHelper.ThrowIfNull(services); - ThrowHelper.ThrowIfNull(configureOptions); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configureOptions); services.AddOptions(); services.AddSingleton>(new PostConfigureOptions(name, configureOptions)); @@ -277,7 +277,7 @@ public static OptionsBuilder AddOptions(this IServiceCollect public static OptionsBuilder AddOptions(this IServiceCollection services, string? name) where TOptions : class { - ThrowHelper.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(services); services.AddOptions(); return new OptionsBuilder(services, name); diff --git a/src/libraries/Microsoft.Extensions.Options/src/OptionsValidationException.cs b/src/libraries/Microsoft.Extensions.Options/src/OptionsValidationException.cs index 9e03b94d79ffd0..844fe8ce3662b6 100644 --- a/src/libraries/Microsoft.Extensions.Options/src/OptionsValidationException.cs +++ b/src/libraries/Microsoft.Extensions.Options/src/OptionsValidationException.cs @@ -19,8 +19,8 @@ public class OptionsValidationException : Exception /// The validation failure messages. public OptionsValidationException(string optionsName, Type optionsType, IEnumerable? failureMessages) { - ThrowHelper.ThrowIfNull(optionsName); - ThrowHelper.ThrowIfNull(optionsType); + ArgumentNullException.ThrowIfNull(optionsName); + ArgumentNullException.ThrowIfNull(optionsType); Failures = failureMessages ?? new List(); OptionsType = optionsType; diff --git a/src/libraries/Microsoft.Extensions.Options/src/PostConfigureOptions.cs b/src/libraries/Microsoft.Extensions.Options/src/PostConfigureOptions.cs index c880102717fdb2..2822fc48161290 100644 --- a/src/libraries/Microsoft.Extensions.Options/src/PostConfigureOptions.cs +++ b/src/libraries/Microsoft.Extensions.Options/src/PostConfigureOptions.cs @@ -39,7 +39,7 @@ public PostConfigureOptions(string? name, Action? action) /// The options to use in initialization. public virtual void PostConfigure(string? name, TOptions options) { - ThrowHelper.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(options); // Null name is used to initialize all named options. if (Name == null || name == Name) @@ -93,7 +93,7 @@ public PostConfigureOptions(string? name, TDep dependency, ActionThe options instance to configured. public virtual void PostConfigure(string? name, TOptions options) { - ThrowHelper.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(options); // Null name is used to configure all named options. if (Name == null || name == Name) @@ -162,7 +162,7 @@ public PostConfigureOptions(string? name, TDep1 dependency, TDep2 dependency2, A /// The options instance to configured. public virtual void PostConfigure(string? name, TOptions options) { - ThrowHelper.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(options); // Null name is used to configure all named options. if (Name == null || name == Name) @@ -240,7 +240,7 @@ public PostConfigureOptions(string? name, TDep1 dependency, TDep2 dependency2, T /// The options instance to configured. public virtual void PostConfigure(string? name, TOptions options) { - ThrowHelper.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(options); // Null name is used to configure all named options. if (Name == null || name == Name) @@ -327,7 +327,7 @@ public PostConfigureOptions(string? name, TDep1 dependency1, TDep2 dependency2, /// The options instance to configured. public virtual void PostConfigure(string? name, TOptions options) { - ThrowHelper.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(options); // Null name is used to configure all named options. if (Name == null || name == Name) @@ -423,7 +423,7 @@ public PostConfigureOptions(string? name, TDep1 dependency1, TDep2 dependency2, /// The options instance to configured. public virtual void PostConfigure(string? name, TOptions options) { - ThrowHelper.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(options); // Null name is used to configure all named options. if (Name == null || name == Name) diff --git a/src/libraries/Microsoft.Extensions.Options/src/ValidateOptions.cs b/src/libraries/Microsoft.Extensions.Options/src/ValidateOptions.cs index 11a539c823c450..6e12a6f4943fed 100644 --- a/src/libraries/Microsoft.Extensions.Options/src/ValidateOptions.cs +++ b/src/libraries/Microsoft.Extensions.Options/src/ValidateOptions.cs @@ -19,7 +19,7 @@ public class ValidateOptions : IValidateOptions where TOptio /// Validation failure message. public ValidateOptions(string? name, Func validation, string failureMessage) { - ThrowHelper.ThrowIfNull(validation); + ArgumentNullException.ThrowIfNull(validation); Name = name; Validation = validation; @@ -80,7 +80,7 @@ public class ValidateOptions : IValidateOptions where /// Validation failure message. public ValidateOptions(string? name, TDep dependency, Func validation, string failureMessage) { - ThrowHelper.ThrowIfNull(validation); + ArgumentNullException.ThrowIfNull(validation); Name = name; Validation = validation; @@ -149,7 +149,7 @@ public class ValidateOptions : IValidateOptionsValidation failure message. public ValidateOptions(string? name, TDep1 dependency1, TDep2 dependency2, Func validation, string failureMessage) { - ThrowHelper.ThrowIfNull(validation); + ArgumentNullException.ThrowIfNull(validation); Name = name; Validation = validation; @@ -226,7 +226,7 @@ public class ValidateOptions : IValidateOptionsValidation failure message. public ValidateOptions(string? name, TDep1 dependency1, TDep2 dependency2, TDep3 dependency3, Func validation, string failureMessage) { - ThrowHelper.ThrowIfNull(validation); + ArgumentNullException.ThrowIfNull(validation); Name = name; Validation = validation; @@ -311,7 +311,7 @@ public class ValidateOptions : IValidateOp /// Validation failure message. public ValidateOptions(string? name, TDep1 dependency1, TDep2 dependency2, TDep3 dependency3, TDep4 dependency4, Func validation, string failureMessage) { - ThrowHelper.ThrowIfNull(validation); + ArgumentNullException.ThrowIfNull(validation); Name = name; Validation = validation; @@ -404,7 +404,7 @@ public class ValidateOptions : IVal /// Validation failure message. public ValidateOptions(string? name, TDep1 dependency1, TDep2 dependency2, TDep3 dependency3, TDep4 dependency4, TDep5 dependency5, Func validation, string failureMessage) { - ThrowHelper.ThrowIfNull(validation); + ArgumentNullException.ThrowIfNull(validation); Name = name; Validation = validation; diff --git a/src/libraries/Microsoft.Extensions.Options/src/ValidateOptionsResultBuilder.cs b/src/libraries/Microsoft.Extensions.Options/src/ValidateOptionsResultBuilder.cs index 0e509b8d0ce13d..a7fcc9659d2390 100644 --- a/src/libraries/Microsoft.Extensions.Options/src/ValidateOptionsResultBuilder.cs +++ b/src/libraries/Microsoft.Extensions.Options/src/ValidateOptionsResultBuilder.cs @@ -31,7 +31,7 @@ public ValidateOptionsResultBuilder() { } /// The property in the option object which contains an error. public void AddError(string error, string? propertyName = null) { - ThrowHelper.ThrowIfNull(error); + ArgumentNullException.ThrowIfNull(error); Errors.Add(propertyName is null ? error : $"Property {propertyName}: {error}"); } @@ -71,7 +71,7 @@ public void AddResults(IEnumerable? results) /// The instance to consume the errors from. public void AddResult(ValidateOptionsResult result) { - ThrowHelper.ThrowIfNull(result); + ArgumentNullException.ThrowIfNull(result); if (result.Failed) { diff --git a/src/libraries/Microsoft.Extensions.Options/tests/SourceGenerationTests/Microsoft.Extensions.Options.SourceGeneration.Tests.csproj b/src/libraries/Microsoft.Extensions.Options/tests/SourceGenerationTests/Microsoft.Extensions.Options.SourceGeneration.Tests.csproj index 7f2cd358d95991..2507fb84c7b5d8 100644 --- a/src/libraries/Microsoft.Extensions.Options/tests/SourceGenerationTests/Microsoft.Extensions.Options.SourceGeneration.Tests.csproj +++ b/src/libraries/Microsoft.Extensions.Options/tests/SourceGenerationTests/Microsoft.Extensions.Options.SourceGeneration.Tests.csproj @@ -11,7 +11,6 @@ - diff --git a/src/libraries/Microsoft.Win32.Registry.AccessControl/src/Microsoft/Win32/RegistryAclExtensions.cs b/src/libraries/Microsoft.Win32.Registry.AccessControl/src/Microsoft/Win32/RegistryAclExtensions.cs index 119b12295f6600..6cacc355f1edf3 100644 --- a/src/libraries/Microsoft.Win32.Registry.AccessControl/src/Microsoft/Win32/RegistryAclExtensions.cs +++ b/src/libraries/Microsoft.Win32.Registry.AccessControl/src/Microsoft/Win32/RegistryAclExtensions.cs @@ -10,30 +10,21 @@ public static class RegistryAclExtensions { public static RegistrySecurity GetAccessControl(this RegistryKey key) { - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); return key.GetAccessControl(); } public static RegistrySecurity GetAccessControl(this RegistryKey key, AccessControlSections includeSections) { - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); return key.GetAccessControl(includeSections); } public static void SetAccessControl(this RegistryKey key, RegistrySecurity registrySecurity) { - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); key.SetAccessControl(registrySecurity); } diff --git a/src/libraries/Microsoft.XmlSerializer.Generator/src/Sgen.cs b/src/libraries/Microsoft.XmlSerializer.Generator/src/Sgen.cs index dadf7d5af116b5..74f2d111df056d 100644 --- a/src/libraries/Microsoft.XmlSerializer.Generator/src/Sgen.cs +++ b/src/libraries/Microsoft.XmlSerializer.Generator/src/Sgen.cs @@ -547,10 +547,7 @@ private static string GetXmlSerializerAssemblyName(Type type) private static string GetXmlSerializerAssemblyName(Type type, string defaultNamespace) { - if (type is null) - { - throw new ArgumentNullException(nameof(type)); - } + ArgumentNullException.ThrowIfNull(type); return GetTempAssemblyName(type.Assembly.GetName(), defaultNamespace); } diff --git a/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.cs b/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.cs index 49b8bd42d6513c..c95e52baf5600a 100644 --- a/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.cs +++ b/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.cs @@ -531,10 +531,7 @@ private void GenerateNamespace(CodeNamespace e) private void GenerateStatement(CodeStatement e) { - if (e is null) - { - throw new ArgumentNullException(nameof(e)); - } + ArgumentNullException.ThrowIfNull(e); if (e.StartDirectives.Count > 0) { @@ -1233,14 +1230,8 @@ private void GenerateExpression(CodeExpression e) } else { - if (e == null) - { - throw new ArgumentNullException(nameof(e)); - } - else - { - throw new ArgumentException(SR.Format(SR.InvalidElementType, e.GetType().FullName), nameof(e)); - } + ArgumentNullException.ThrowIfNull(e); + throw new ArgumentException(SR.Format(SR.InvalidElementType, e.GetType().FullName), nameof(e)); } } @@ -2695,10 +2686,7 @@ public void ValidateIdentifier(string value) public string CreateValidIdentifier(string name) { - if (name is null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); if (CSharpHelpers.IsPrefixTwoUnderscore(name)) { @@ -2715,10 +2703,7 @@ public string CreateValidIdentifier(string name) public string CreateEscapedIdentifier(string name) { - if (name is null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); return CSharpHelpers.CreateEscapedIdentifier(name); } @@ -2902,10 +2887,7 @@ private void OutputStartingBrace() CompilerResults ICodeCompiler.CompileAssemblyFromDom(CompilerParameters options, CodeCompileUnit e) { - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); try { @@ -2919,10 +2901,7 @@ CompilerResults ICodeCompiler.CompileAssemblyFromDom(CompilerParameters options, CompilerResults ICodeCompiler.CompileAssemblyFromFile(CompilerParameters options, string fileName) { - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); try { @@ -2936,10 +2915,7 @@ CompilerResults ICodeCompiler.CompileAssemblyFromFile(CompilerParameters options CompilerResults ICodeCompiler.CompileAssemblyFromSource(CompilerParameters options, string source) { - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); try { @@ -2953,10 +2929,7 @@ CompilerResults ICodeCompiler.CompileAssemblyFromSource(CompilerParameters optio CompilerResults ICodeCompiler.CompileAssemblyFromSourceBatch(CompilerParameters options, string[] sources) { - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); try { @@ -2970,14 +2943,8 @@ CompilerResults ICodeCompiler.CompileAssemblyFromSourceBatch(CompilerParameters CompilerResults ICodeCompiler.CompileAssemblyFromFileBatch(CompilerParameters options, string[] fileNames) { - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } - if (fileNames is null) - { - throw new ArgumentNullException(nameof(fileNames)); - } + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(fileNames); try { @@ -2998,10 +2965,7 @@ CompilerResults ICodeCompiler.CompileAssemblyFromFileBatch(CompilerParameters op CompilerResults ICodeCompiler.CompileAssemblyFromDomBatch(CompilerParameters options, CodeCompileUnit[] ea) { - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); try { @@ -3015,10 +2979,7 @@ CompilerResults ICodeCompiler.CompileAssemblyFromDomBatch(CompilerParameters opt private CompilerResults FromDom(CompilerParameters options, CodeCompileUnit e) { - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); return FromDomBatch(options, new CodeCompileUnit[1] { e }); } @@ -3026,14 +2987,8 @@ private CompilerResults FromDom(CompilerParameters options, CodeCompileUnit e) private static CompilerResults FromFile(CompilerParameters options, string fileName) { - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } - if (fileName is null) - { - throw new ArgumentNullException(nameof(fileName)); - } + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(fileName); // Try opening the file to make sure it exists. This will throw an exception // if it doesn't @@ -3044,24 +2999,15 @@ private static CompilerResults FromFile(CompilerParameters options, string fileN private static CompilerResults FromSource(CompilerParameters options, string source) { - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); return FromSourceBatch(options, new string[1] { source }); } private CompilerResults FromDomBatch(CompilerParameters options, CodeCompileUnit[] ea) { - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } - if (ea is null) - { - throw new ArgumentNullException(nameof(ea)); - } + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(ea); string[] filenames = new string[ea.Length]; @@ -3101,14 +3047,8 @@ private static void ResolveReferencedAssemblies(CompilerParameters options, Code private static CompilerResults FromSourceBatch(CompilerParameters options, string[] sources) { - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } - if (sources is null) - { - throw new ArgumentNullException(nameof(sources)); - } + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(sources); string[] filenames = new string[sources.Length]; diff --git a/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeProvider.cs b/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeProvider.cs index cbc1defe51e4a3..f2694184708c00 100644 --- a/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeProvider.cs +++ b/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeProvider.cs @@ -22,10 +22,7 @@ public CSharpCodeProvider() public CSharpCodeProvider(IDictionary providerOptions) { - if (providerOptions is null) - { - throw new ArgumentNullException(nameof(providerOptions)); - } + ArgumentNullException.ThrowIfNull(providerOptions); _generator = new CSharpCodeGenerator(providerOptions); } diff --git a/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpModifierAttributeConverter.cs b/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpModifierAttributeConverter.cs index 8be7071ce5ccf3..eea411ac1bb356 100644 --- a/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpModifierAttributeConverter.cs +++ b/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpModifierAttributeConverter.cs @@ -36,10 +36,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType is null) - { - throw new ArgumentNullException(nameof(destinationType)); - } + ArgumentNullException.ThrowIfNull(destinationType); if (destinationType == typeof(string)) { diff --git a/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBCodeProvider.cs b/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBCodeProvider.cs index 8c26d96945ee18..75a4271f05250e 100644 --- a/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBCodeProvider.cs +++ b/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBCodeProvider.cs @@ -22,10 +22,7 @@ public VBCodeProvider() public VBCodeProvider(IDictionary providerOptions) { - if (providerOptions is null) - { - throw new ArgumentNullException(nameof(providerOptions)); - } + ArgumentNullException.ThrowIfNull(providerOptions); _generator = new VBCodeGenerator(providerOptions); } diff --git a/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBModifierAttributeConverter.cs b/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBModifierAttributeConverter.cs index ce87cec1ec214a..a8efb8f683edd0 100644 --- a/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBModifierAttributeConverter.cs +++ b/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBModifierAttributeConverter.cs @@ -36,10 +36,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType is null) - { - throw new ArgumentNullException(nameof(destinationType)); - } + ArgumentNullException.ThrowIfNull(destinationType); if (destinationType == typeof(string)) { diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeAttributeArgumentCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeAttributeArgumentCollection.cs index e284e13c5ee872..f11163cbd62a53 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeAttributeArgumentCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeAttributeArgumentCollection.cs @@ -29,10 +29,7 @@ public CodeAttributeArgument this[int index] public void AddRange(CodeAttributeArgument[] value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); for (int i = 0; i < value.Length; i++) { @@ -42,10 +39,7 @@ public void AddRange(CodeAttributeArgument[] value) public void AddRange(CodeAttributeArgumentCollection value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); int currentCount = value.Count; for (int i = 0; i < currentCount; i++) diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeAttributeDeclarationCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeAttributeDeclarationCollection.cs index 581867095be7d9..2f8284fe6edd7a 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeAttributeDeclarationCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeAttributeDeclarationCollection.cs @@ -31,10 +31,7 @@ public CodeAttributeDeclaration this[int index] public void AddRange(CodeAttributeDeclaration[] value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); for (int i = 0; i < value.Length; i++) { @@ -44,10 +41,7 @@ public void AddRange(CodeAttributeDeclaration[] value) public void AddRange(CodeAttributeDeclarationCollection value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); int currentCount = value.Count; for (int i = 0; i < currentCount; i++) diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeCatchClauseCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeCatchClauseCollection.cs index f84c2c6daa19be..bbd3409958149c 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeCatchClauseCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeCatchClauseCollection.cs @@ -29,10 +29,7 @@ public CodeCatchClause this[int index] public void AddRange(CodeCatchClause[] value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); for (int i = 0; i < value.Length; i++) { @@ -42,10 +39,7 @@ public void AddRange(CodeCatchClause[] value) public void AddRange(CodeCatchClauseCollection value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); int currentCount = value.Count; for (int i = 0; i < currentCount; i++) diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeCommentStatementCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeCommentStatementCollection.cs index 82fa21f9d60f81..a1ef4848589726 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeCommentStatementCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeCommentStatementCollection.cs @@ -29,10 +29,7 @@ public CodeCommentStatement this[int index] public void AddRange(CodeCommentStatement[] value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); for (int i = 0; i < value.Length; i++) { @@ -42,10 +39,7 @@ public void AddRange(CodeCommentStatement[] value) public void AddRange(CodeCommentStatementCollection value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); int currentCount = value.Count; for (int i = 0; i < currentCount; i++) diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeDirectiveCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeDirectiveCollection.cs index a83e61bd1da1f4..112396ca186049 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeDirectiveCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeDirectiveCollection.cs @@ -29,10 +29,7 @@ public CodeDirective this[int index] public void AddRange(CodeDirective[] value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); for (int i = 0; i < value.Length; i++) { @@ -42,10 +39,7 @@ public void AddRange(CodeDirective[] value) public void AddRange(CodeDirectiveCollection value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); int currentCount = value.Count; for (int i = 0; i < currentCount; i++) diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeExpressionCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeExpressionCollection.cs index 81378ae61857ad..afc6db6f3f914e 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeExpressionCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeExpressionCollection.cs @@ -29,10 +29,7 @@ public CodeExpression this[int index] public void AddRange(CodeExpression[] value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); for (int i = 0; i < value.Length; i++) { @@ -42,10 +39,7 @@ public void AddRange(CodeExpression[] value) public void AddRange(CodeExpressionCollection value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); int currentCount = value.Count; for (int i = 0; i < currentCount; i++) diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeNamespaceCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeNamespaceCollection.cs index 10b54980c9fea2..67010f9c18fe15 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeNamespaceCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeNamespaceCollection.cs @@ -29,10 +29,7 @@ public CodeNamespace this[int index] public void AddRange(CodeNamespace[] value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); for (int i = 0; i < value.Length; i++) { @@ -42,10 +39,7 @@ public void AddRange(CodeNamespace[] value) public void AddRange(CodeNamespaceCollection value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); int currentCount = value.Count; for (int i = 0; i < currentCount; i++) diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeNamespaceImportCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeNamespaceImportCollection.cs index ce6e6e50153912..c55024ac1de8bf 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeNamespaceImportCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeNamespaceImportCollection.cs @@ -38,10 +38,7 @@ public void Add(CodeNamespaceImport value) public void AddRange(CodeNamespaceImport[] value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); foreach (CodeNamespaceImport c in value) { diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeParameterDeclarationExpressionCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeParameterDeclarationExpressionCollection.cs index 1991e01236964b..c3d7fa01e59441 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeParameterDeclarationExpressionCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeParameterDeclarationExpressionCollection.cs @@ -29,10 +29,7 @@ public CodeParameterDeclarationExpression this[int index] public void AddRange(CodeParameterDeclarationExpression[] value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); for (int i = 0; i < value.Length; i++) { @@ -42,10 +39,7 @@ public void AddRange(CodeParameterDeclarationExpression[] value) public void AddRange(CodeParameterDeclarationExpressionCollection value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); int currentCount = value.Count; for (int i = 0; i < currentCount; i++) diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeStatementCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeStatementCollection.cs index 51ceda89b44edc..dcb88b7884c25c 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeStatementCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeStatementCollection.cs @@ -31,10 +31,7 @@ public CodeStatement this[int index] public void AddRange(CodeStatement[] value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); for (int i = 0; i < value.Length; i++) { @@ -44,10 +41,7 @@ public void AddRange(CodeStatement[] value) public void AddRange(CodeStatementCollection value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); int currentCount = value.Count; for (int i = 0; i < currentCount; i++) diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeDeclarationCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeDeclarationCollection.cs index ceafd0c51eb83a..d64bda65dba785 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeDeclarationCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeDeclarationCollection.cs @@ -29,10 +29,7 @@ public CodeTypeDeclaration this[int index] public void AddRange(CodeTypeDeclaration[] value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); for (int i = 0; i < value.Length; i++) { @@ -42,10 +39,7 @@ public void AddRange(CodeTypeDeclaration[] value) public void AddRange(CodeTypeDeclarationCollection value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); int currentCount = value.Count; for (int i = 0; i < currentCount; i++) diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeMemberCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeMemberCollection.cs index 2d63d3a87300b6..17b8337fc8b07a 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeMemberCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeMemberCollection.cs @@ -29,10 +29,7 @@ public CodeTypeMember this[int index] public void AddRange(CodeTypeMember[] value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); for (int i = 0; i < value.Length; i++) { @@ -42,10 +39,7 @@ public void AddRange(CodeTypeMember[] value) public void AddRange(CodeTypeMemberCollection value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); int currentCount = value.Count; for (int i = 0; i < currentCount; i++) diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeParameterCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeParameterCollection.cs index 1f403870043e9a..02821362b63c57 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeParameterCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeParameterCollection.cs @@ -31,10 +31,7 @@ public CodeTypeParameter this[int index] public void AddRange(CodeTypeParameter[] value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); for (int i = 0; i < value.Length; i++) { @@ -44,10 +41,7 @@ public void AddRange(CodeTypeParameter[] value) public void AddRange(CodeTypeParameterCollection value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); int currentCount = value.Count; for (int i = 0; i < currentCount; i++) diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeCompiler.cs b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeCompiler.cs index ab60ffc8c7a738..65300e8602eac8 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeCompiler.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeCompiler.cs @@ -10,10 +10,7 @@ public abstract class CodeCompiler : CodeGenerator, ICodeCompiler { CompilerResults ICodeCompiler.CompileAssemblyFromDom(CompilerParameters options, CodeCompileUnit e) { - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); try { @@ -27,10 +24,7 @@ CompilerResults ICodeCompiler.CompileAssemblyFromDom(CompilerParameters options, CompilerResults ICodeCompiler.CompileAssemblyFromFile(CompilerParameters options, string fileName) { - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); try { @@ -44,10 +38,7 @@ CompilerResults ICodeCompiler.CompileAssemblyFromFile(CompilerParameters options CompilerResults ICodeCompiler.CompileAssemblyFromSource(CompilerParameters options, string source) { - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); try { @@ -61,10 +52,7 @@ CompilerResults ICodeCompiler.CompileAssemblyFromSource(CompilerParameters optio CompilerResults ICodeCompiler.CompileAssemblyFromSourceBatch(CompilerParameters options, string[] sources) { - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); try { @@ -78,14 +66,8 @@ CompilerResults ICodeCompiler.CompileAssemblyFromSourceBatch(CompilerParameters CompilerResults ICodeCompiler.CompileAssemblyFromFileBatch(CompilerParameters options, string[] fileNames) { - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } - if (fileNames is null) - { - throw new ArgumentNullException(nameof(fileNames)); - } + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(fileNames); try { @@ -105,10 +87,7 @@ CompilerResults ICodeCompiler.CompileAssemblyFromFileBatch(CompilerParameters op CompilerResults ICodeCompiler.CompileAssemblyFromDomBatch(CompilerParameters options, CodeCompileUnit[] ea) { - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); try { @@ -126,24 +105,15 @@ CompilerResults ICodeCompiler.CompileAssemblyFromDomBatch(CompilerParameters opt protected virtual CompilerResults FromDom(CompilerParameters options, CodeCompileUnit e) { - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); return FromDomBatch(options, new CodeCompileUnit[1] { e }); } protected virtual CompilerResults FromFile(CompilerParameters options, string fileName) { - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } - if (fileName is null) - { - throw new ArgumentNullException(nameof(fileName)); - } + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(fileName); // Try opening the file to make sure it exists. This will throw an exception if it doesn't File.OpenRead(fileName).Dispose(); @@ -153,24 +123,15 @@ protected virtual CompilerResults FromFile(CompilerParameters options, string fi protected virtual CompilerResults FromSource(CompilerParameters options, string source) { - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); return FromSourceBatch(options, new string[1] { source }); } protected virtual CompilerResults FromDomBatch(CompilerParameters options, CodeCompileUnit[] ea) { - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } - if (ea is null) - { - throw new ArgumentNullException(nameof(ea)); - } + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(ea); var filenames = new string[ea.Length]; @@ -210,14 +171,8 @@ private static void ResolveReferencedAssemblies(CompilerParameters options, Code protected virtual CompilerResults FromFileBatch(CompilerParameters options, string[] fileNames) { - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } - if (fileNames is null) - { - throw new ArgumentNullException(nameof(fileNames)); - } + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(fileNames); throw new PlatformNotSupportedException(); } @@ -242,14 +197,8 @@ protected virtual string GetResponseFileCmdArgs(CompilerParameters options, stri protected virtual CompilerResults FromSourceBatch(CompilerParameters options, string[] sources) { - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } - if (sources is null) - { - throw new ArgumentNullException(nameof(sources)); - } + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(sources); var filenames = new string[sources.Length]; diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeDomProvider.cs b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeDomProvider.cs index 60ae6e69600dde..44d3b4520e23d5 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeDomProvider.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeDomProvider.cs @@ -88,10 +88,7 @@ public static CompilerInfo GetCompilerInfo(string language) private static CompilerInfo GetCompilerInfoForLanguageNoThrow(string language) { - if (language is null) - { - throw new ArgumentNullException(nameof(language)); - } + ArgumentNullException.ThrowIfNull(language); CompilerInfo value; s_compilerLanguages.TryGetValue(language.Trim(), out value); @@ -100,10 +97,7 @@ private static CompilerInfo GetCompilerInfoForLanguageNoThrow(string language) private static CompilerInfo GetCompilerInfoForExtensionNoThrow(string extension) { - if (extension is null) - { - throw new ArgumentNullException(nameof(extension)); - } + ArgumentNullException.ThrowIfNull(extension); CompilerInfo value; s_compilerExtensions.TryGetValue(extension.Trim(), out value); diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeGenerator.cs b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeGenerator.cs index ef2ed70abe7994..87f4f92ddac3bd 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeGenerator.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeGenerator.cs @@ -234,10 +234,7 @@ protected void GenerateNamespaces(CodeCompileUnit e) protected void GenerateTypes(CodeNamespace e) { - if (e is null) - { - throw new ArgumentNullException(nameof(e)); - } + ArgumentNullException.ThrowIfNull(e); foreach (CodeTypeDeclaration c in e.Types) { @@ -400,10 +397,7 @@ void ICodeGenerator.GenerateCodeFromStatement(CodeStatement e, TextWriter w, Cod public virtual void GenerateCodeFromMember(CodeTypeMember member, TextWriter writer, CodeGeneratorOptions options) { - if (member is null) - { - throw new ArgumentNullException(nameof(member)); - } + ArgumentNullException.ThrowIfNull(member); if (_output != null) { @@ -610,14 +604,8 @@ protected void GenerateExpression(CodeExpression e) } else { - if (e == null) - { - throw new ArgumentNullException(nameof(e)); - } - else - { - throw new ArgumentException(SR.Format(SR.InvalidElementType, e.GetType().FullName), nameof(e)); - } + ArgumentNullException.ThrowIfNull(e); + throw new ArgumentException(SR.Format(SR.InvalidElementType, e.GetType().FullName), nameof(e)); } } @@ -713,10 +701,7 @@ private void GenerateSnippetMembers(CodeTypeDeclaration e) protected virtual void GenerateSnippetCompileUnit(CodeSnippetCompileUnit e) { - if (e is null) - { - throw new ArgumentNullException(nameof(e)); - } + ArgumentNullException.ThrowIfNull(e); GenerateDirectives(e.StartDirectives); @@ -803,10 +788,7 @@ protected virtual void GenerateCompileUnit(CodeCompileUnit e) protected virtual void GenerateNamespace(CodeNamespace e) { - if (e is null) - { - throw new ArgumentNullException(nameof(e)); - } + ArgumentNullException.ThrowIfNull(e); GenerateCommentStatements(e.Comments); GenerateNamespaceStart(e); @@ -820,10 +802,7 @@ protected virtual void GenerateNamespace(CodeNamespace e) protected void GenerateNamespaceImports(CodeNamespace e) { - if (e is null) - { - throw new ArgumentNullException(nameof(e)); - } + ArgumentNullException.ThrowIfNull(e); foreach (CodeNamespaceImport imp in e.Imports) { @@ -877,10 +856,7 @@ private void GenerateProperties(CodeTypeDeclaration e) protected void GenerateStatement(CodeStatement e) { - if (e is null) - { - throw new ArgumentNullException(nameof(e)); - } + ArgumentNullException.ThrowIfNull(e); if (e.StartDirectives.Count > 0) { @@ -974,10 +950,7 @@ protected void GenerateStatement(CodeStatement e) protected void GenerateStatements(CodeStatementCollection stmts) { - if (stmts is null) - { - throw new ArgumentNullException(nameof(stmts)); - } + ArgumentNullException.ThrowIfNull(stmts); foreach (CodeStatement stmt in stmts) { @@ -987,10 +960,7 @@ protected void GenerateStatements(CodeStatementCollection stmts) protected virtual void OutputAttributeDeclarations(CodeAttributeDeclarationCollection attributes) { - if (attributes is null) - { - throw new ArgumentNullException(nameof(attributes)); - } + ArgumentNullException.ThrowIfNull(attributes); if (attributes.Count == 0) { @@ -1035,10 +1005,7 @@ protected virtual void OutputAttributeDeclarations(CodeAttributeDeclarationColle protected virtual void OutputAttributeArgument(CodeAttributeArgument arg) { - if (arg is null) - { - throw new ArgumentNullException(nameof(arg)); - } + ArgumentNullException.ThrowIfNull(arg); if (!string.IsNullOrEmpty(arg.Name)) { @@ -1291,10 +1258,7 @@ protected virtual void OutputOperator(CodeBinaryOperatorType op) protected virtual void OutputParameters(CodeParameterDeclarationExpressionCollection parameters) { - if (parameters is null) - { - throw new ArgumentNullException(nameof(parameters)); - } + ArgumentNullException.ThrowIfNull(parameters); bool first = true; bool multiline = parameters.Count > ParameterMultilineThreshold; @@ -1329,10 +1293,7 @@ protected virtual void OutputParameters(CodeParameterDeclarationExpressionCollec protected virtual void GenerateBinaryOperatorExpression(CodeBinaryOperatorExpression e) { - if (e is null) - { - throw new ArgumentNullException(nameof(e)); - } + ArgumentNullException.ThrowIfNull(e); bool indentedExpression = false; Output.Write('('); @@ -1385,10 +1346,7 @@ protected virtual void GenerateBinaryOperatorExpression(CodeBinaryOperatorExpres protected virtual void GenerateParameterDeclarationExpression(CodeParameterDeclarationExpression e) { - if (e is null) - { - throw new ArgumentNullException(nameof(e)); - } + ArgumentNullException.ThrowIfNull(e); if (e.CustomAttributes.Count > 0) { @@ -1402,10 +1360,7 @@ protected virtual void GenerateParameterDeclarationExpression(CodeParameterDecla protected virtual void GenerateDirectionExpression(CodeDirectionExpression e) { - if (e is null) - { - throw new ArgumentNullException(nameof(e)); - } + ArgumentNullException.ThrowIfNull(e); OutputDirection(e.Direction); GenerateExpression(e.Expression); @@ -1413,10 +1368,7 @@ protected virtual void GenerateDirectionExpression(CodeDirectionExpression e) protected virtual void GeneratePrimitiveExpression(CodePrimitiveExpression e) { - if (e is null) - { - throw new ArgumentNullException(nameof(e)); - } + ArgumentNullException.ThrowIfNull(e); if (e.Value == null) { @@ -1493,20 +1445,14 @@ protected virtual void GenerateDefaultValueExpression(CodeDefaultValueExpression protected virtual void GenerateTypeReferenceExpression(CodeTypeReferenceExpression e) { - if (e is null) - { - throw new ArgumentNullException(nameof(e)); - } + ArgumentNullException.ThrowIfNull(e); OutputType(e.Type); } protected virtual void GenerateTypeOfExpression(CodeTypeOfExpression e) { - if (e is null) - { - throw new ArgumentNullException(nameof(e)); - } + ArgumentNullException.ThrowIfNull(e); Output.Write("typeof("); OutputType(e.Type); @@ -1518,10 +1464,7 @@ protected virtual void GenerateTypeOfExpression(CodeTypeOfExpression e) protected abstract void GenerateThrowExceptionStatement(CodeThrowExceptionStatement e); protected virtual void GenerateCommentStatement(CodeCommentStatement e) { - if (e is null) - { - throw new ArgumentNullException(nameof(e)); - } + ArgumentNullException.ThrowIfNull(e); if (e.Comment == null) { @@ -1532,10 +1475,7 @@ protected virtual void GenerateCommentStatement(CodeCommentStatement e) protected virtual void GenerateCommentStatements(CodeCommentStatementCollection e) { - if (e is null) - { - throw new ArgumentNullException(nameof(e)); - } + ArgumentNullException.ThrowIfNull(e); foreach (CodeCommentStatement comment in e) { @@ -1555,10 +1495,7 @@ protected virtual void GenerateCommentStatements(CodeCommentStatementCollection protected virtual void GenerateSnippetStatement(CodeSnippetStatement e) { - if (e is null) - { - throw new ArgumentNullException(nameof(e)); - } + ArgumentNullException.ThrowIfNull(e); Output.WriteLine(e.Value); } @@ -1579,10 +1516,7 @@ protected virtual void GenerateSnippetStatement(CodeSnippetStatement e) protected virtual void GenerateCompileUnitStart(CodeCompileUnit e) { - if (e is null) - { - throw new ArgumentNullException(nameof(e)); - } + ArgumentNullException.ThrowIfNull(e); if (e.StartDirectives.Count > 0) { @@ -1592,10 +1526,7 @@ protected virtual void GenerateCompileUnitStart(CodeCompileUnit e) protected virtual void GenerateCompileUnitEnd(CodeCompileUnit e) { - if (e is null) - { - throw new ArgumentNullException(nameof(e)); - } + ArgumentNullException.ThrowIfNull(e); if (e.EndDirectives.Count > 0) { diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeValidator.cs b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeValidator.cs index ed73caf55325d4..4e8198d8eae01a 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeValidator.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeValidator.cs @@ -53,12 +53,9 @@ internal void ValidateIdentifiers(CodeObject e) { ValidateCodeDirective((CodeDirective)e); } - else if (e == null) - { - throw new ArgumentNullException(nameof(e)); - } else { + ArgumentNullException.ThrowIfNull(e); throw new ArgumentException(SR.Format(SR.InvalidElementType, e.GetType().FullName), nameof(e)); } } @@ -392,10 +389,7 @@ private void ValidateTypeStart(CodeTypeDeclaration e) private void ValidateStatement(CodeStatement e) { - if (e is null) - { - throw new ArgumentNullException(nameof(e)); - } + ArgumentNullException.ThrowIfNull(e); ValidateCodeDirectives(e.StartDirectives); ValidateCodeDirectives(e.EndDirectives); @@ -770,14 +764,8 @@ private void ValidateExpression(CodeExpression e) } else { - if (e == null) - { - throw new ArgumentNullException(nameof(e)); - } - else - { - throw new ArgumentException(SR.Format(SR.InvalidElementType, e.GetType().FullName), nameof(e)); - } + ArgumentNullException.ThrowIfNull(e); + throw new ArgumentException(SR.Format(SR.InvalidElementType, e.GetType().FullName), nameof(e)); } } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerErrorCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerErrorCollection.cs index 91351cb6290873..ed4a27ffba1140 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerErrorCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerErrorCollection.cs @@ -29,10 +29,7 @@ public CompilerError this[int index] public void AddRange(CompilerError[] value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); for (int i = 0; i < value.Length; i++) { @@ -42,10 +39,7 @@ public void AddRange(CompilerError[] value) public void AddRange(CompilerErrorCollection value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); int currentCount = value.Count; for (int i = 0; i < currentCount; i++) diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerInfo.cs b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerInfo.cs index b2a08cf3349427..b60f3f4d5f037d 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerInfo.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerInfo.cs @@ -62,10 +62,7 @@ public CodeDomProvider CreateProvider() public CodeDomProvider CreateProvider(IDictionary providerOptions) { - if (providerOptions is null) - { - throw new ArgumentNullException(nameof(providerOptions)); - } + ArgumentNullException.ThrowIfNull(providerOptions); ConstructorInfo constructor = CodeDomProviderType.GetConstructor(new Type[] { typeof(IDictionary) }); if (constructor != null) diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Frozen/FrozenDictionary.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Frozen/FrozenDictionary.cs index bf0a645bd16b4e..b9ddcb1b4e484f 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Frozen/FrozenDictionary.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Frozen/FrozenDictionary.cs @@ -116,7 +116,7 @@ public static FrozenDictionary ToFrozenDictionary? newDictionary) where TKey : notnull { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); comparer ??= EqualityComparer.Default; // If the source is already frozen with the same comparer, it can simply be returned. @@ -373,7 +373,7 @@ public abstract partial class FrozenDictionary : IDictionaryThe zero-based index in at which copying begins. public void CopyTo(KeyValuePair[] destination, int destinationIndex) { - ThrowHelper.ThrowIfNull(destination); + ArgumentNullException.ThrowIfNull(destination); CopyTo(destination.AsSpan(destinationIndex)); } @@ -399,7 +399,7 @@ public void CopyTo(Span> destination) /// void ICollection.CopyTo(Array array, int index) { - ThrowHelper.ThrowIfNull(array); + ArgumentNullException.ThrowIfNull(array); if (array.Rank != 1) { @@ -476,7 +476,7 @@ void ICollection.CopyTo(Array array, int index) { get { - ThrowHelper.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(key); return key is TKey tkey && TryGetValue(tkey, out TValue? value) ? value : (object?)null; @@ -593,7 +593,7 @@ public bool ContainsKey(TKey key) => /// bool IDictionary.Contains(object key) { - ThrowHelper.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(key); return key is TKey tkey && ContainsKey(tkey); } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Frozen/FrozenSet.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Frozen/FrozenSet.cs index 2e7fb33b0e81c6..69912b5a00078f 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Frozen/FrozenSet.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Frozen/FrozenSet.cs @@ -61,7 +61,7 @@ public static FrozenSet ToFrozenSet(this IEnumerable source, IEqualityC /// Extracts from the source either an existing instance or a containing the values and the specified . private static FrozenSet? GetExistingFrozenOrNewSet(IEnumerable source, IEqualityComparer? comparer, out HashSet? newSet) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); comparer ??= EqualityComparer.Default; // If the source is already frozen with the same comparer, it can simply be returned. @@ -271,7 +271,7 @@ public abstract partial class FrozenSet : ISet, /// The zero-based index in at which copying begins. public void CopyTo(T[] destination, int destinationIndex) { - ThrowHelper.ThrowIfNull(destination); + ArgumentNullException.ThrowIfNull(destination); CopyTo(destination.AsSpan(destinationIndex)); } @@ -424,7 +424,7 @@ IEnumerator IEnumerable.GetEnumerator() => /// public bool IsProperSubsetOf(IEnumerable other) { - ThrowHelper.ThrowIfNull(other); + ArgumentNullException.ThrowIfNull(other); return IsProperSubsetOfCore(other); } @@ -434,7 +434,7 @@ public bool IsProperSubsetOf(IEnumerable other) /// public bool IsProperSupersetOf(IEnumerable other) { - ThrowHelper.ThrowIfNull(other); + ArgumentNullException.ThrowIfNull(other); return IsProperSupersetOfCore(other); } @@ -444,7 +444,7 @@ public bool IsProperSupersetOf(IEnumerable other) /// public bool IsSubsetOf(IEnumerable other) { - ThrowHelper.ThrowIfNull(other); + ArgumentNullException.ThrowIfNull(other); return IsSubsetOfCore(other); } @@ -454,7 +454,7 @@ public bool IsSubsetOf(IEnumerable other) /// public bool IsSupersetOf(IEnumerable other) { - ThrowHelper.ThrowIfNull(other); + ArgumentNullException.ThrowIfNull(other); return IsSupersetOfCore(other); } @@ -464,7 +464,7 @@ public bool IsSupersetOf(IEnumerable other) /// public bool Overlaps(IEnumerable other) { - ThrowHelper.ThrowIfNull(other); + ArgumentNullException.ThrowIfNull(other); return OverlapsCore(other); } @@ -474,7 +474,7 @@ public bool Overlaps(IEnumerable other) /// public bool SetEquals(IEnumerable other) { - ThrowHelper.ThrowIfNull(other); + ArgumentNullException.ThrowIfNull(other); return SetEqualsCore(other); } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/ThrowHelper.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/ThrowHelper.cs index 1b683ed05db77c..181d3d214bef62 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/ThrowHelper.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/ThrowHelper.cs @@ -9,14 +9,6 @@ namespace System.Collections { internal static class ThrowHelper { - public static void ThrowIfNull(object arg, [CallerArgumentExpression(nameof(arg))] string? paramName = null) - { - if (arg is null) - { - ThrowArgumentNullException(paramName); - } - } - [DoesNotReturn] public static void ThrowIfDestinationTooSmall() => throw new ArgumentException(SR.CapacityMustBeGreaterThanOrEqualToCount, "destination"); diff --git a/src/libraries/System.Collections.Immutable/src/System/Polyfills.cs b/src/libraries/System.Collections.Immutable/src/System/Polyfills.cs index eeb82f0960ccc4..695058294a7a6f 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Polyfills.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Polyfills.cs @@ -42,16 +42,3 @@ internal static class BitOperations } #endif } - -namespace System.Runtime.CompilerServices -{ -#if !NET - [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] - internal sealed class CallerArgumentExpressionAttribute : Attribute - { - public CallerArgumentExpressionAttribute(string parameterName) => ParameterName = parameterName; - - public string ParameterName { get; } - } -#endif -} diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/OrderedDictionary.cs b/src/libraries/System.Collections/src/System/Collections/Generic/OrderedDictionary.cs index 17587257472234..689fec12f12d6c 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/OrderedDictionary.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/OrderedDictionary.cs @@ -7,7 +7,6 @@ using System.Runtime.InteropServices; #if NET -using static System.ArgumentNullException; using static System.ArgumentOutOfRangeException; #else using static System.Collections.ThrowHelper; @@ -166,7 +165,7 @@ public OrderedDictionary(IDictionary dictionary) : this(dictionary public OrderedDictionary(IDictionary dictionary, IEqualityComparer? comparer) : this(dictionary?.Count ?? 0, comparer) { - ThrowIfNull(dictionary); + ArgumentNullException.ThrowIfNull(dictionary); AddRange(dictionary); } @@ -200,7 +199,7 @@ public OrderedDictionary(IEnumerable> collection) : t public OrderedDictionary(IEnumerable> collection, IEqualityComparer? comparer) : this((collection as ICollection>)?.Count ?? 0, comparer) { - ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(collection); AddRange(collection); } @@ -293,7 +292,7 @@ public IEqualityComparer Comparer get => GetAt(index); set { - ThrowIfNull(value); + ArgumentNullException.ThrowIfNull(value); if (value is not KeyValuePair tpair) { @@ -309,7 +308,7 @@ public IEqualityComparer Comparer { get { - ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(key); if (key is TKey tkey && TryGetValue(tkey, out TValue? value)) { @@ -320,10 +319,10 @@ public IEqualityComparer Comparer } set { - ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(key); if (default(TValue) is not null) { - ThrowIfNull(value); + ArgumentNullException.ThrowIfNull(value); } if (key is not TKey tkey) @@ -375,7 +374,7 @@ public TValue this[TKey key] } set { - ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(key); bool modified = TryInsert(index: -1, key, value, InsertionBehavior.OverwriteExisting, out _); Debug.Assert(modified); @@ -484,7 +483,7 @@ private bool TryInsert(int index, TKey key, TValue value, InsertionBehavior beha /// An element with the same key already exists in the . public void Add(TKey key, TValue value) { - ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(key); TryInsert(index: -1, key, value, InsertionBehavior.ThrowOnExisting, out _); } @@ -504,7 +503,7 @@ public void Add(TKey key, TValue value) /// if the key didn't exist and the key and value were added to the dictionary; otherwise, . public bool TryAdd(TKey key, TValue value, out int index) { - ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(key); return TryInsert(index: -1, key, value, InsertionBehavior.IgnoreInsertion, out index); } @@ -611,7 +610,7 @@ public KeyValuePair GetAt(int index) /// is . public int IndexOf(TKey key) { - ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(key); uint _ = 0; return IndexOf(key, ref _, ref _); @@ -728,7 +727,7 @@ public void Insert(int index, TKey key, TValue value) ThrowHelper.ThrowIndexArgumentOutOfRange(); } - ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(key); TryInsert(index, key, value, InsertionBehavior.ThrowOnExisting, out _); } @@ -746,7 +745,7 @@ public void Insert(int index, TKey key, TValue value) /// is . public bool Remove(TKey key, [MaybeNullWhen(false)] out TValue value) { - ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(key); // Find the key. int index = IndexOf(key); @@ -822,7 +821,7 @@ public void SetAt(int index, TKey key, TValue value) ThrowHelper.ThrowIndexArgumentOutOfRange(); } - ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(key); Debug.Assert(_entries is not null); ref Entry e = ref _entries[index]; @@ -932,7 +931,7 @@ public void TrimExcess(int capacity) /// is . public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value, out int index) { - ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(key); // Find the key. index = IndexOf(key); @@ -1175,7 +1174,7 @@ IEnumerator> IEnumerable>. /// int IList>.IndexOf(KeyValuePair item) { - ThrowIfNull(item.Key, nameof(item)); + ArgumentNullException.ThrowIfNull(item.Key, nameof(item)); int index = IndexOf(item.Key); if (index >= 0) @@ -1199,7 +1198,7 @@ int IList>.IndexOf(KeyValuePair item) /// bool ICollection>.Contains(KeyValuePair item) { - ThrowIfNull(item.Key, nameof(item)); + ArgumentNullException.ThrowIfNull(item.Key, nameof(item)); return TryGetValue(item.Key, out TValue? value) && @@ -1209,7 +1208,7 @@ bool ICollection>.Contains(KeyValuePair /// void ICollection>.CopyTo(KeyValuePair[] array, int arrayIndex) { - ThrowIfNull(array); + ArgumentNullException.ThrowIfNull(array); ThrowIfNegative(arrayIndex); if (array.Length - arrayIndex < _count) { @@ -1232,10 +1231,10 @@ bool ICollection>.Remove(KeyValuePair i /// void IDictionary.Add(object key, object? value) { - ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(key); if (default(TValue) is not null) { - ThrowIfNull(value); + ArgumentNullException.ThrowIfNull(value); } if (key is not TKey tkey) @@ -1245,7 +1244,7 @@ void IDictionary.Add(object key, object? value) if (default(TValue) is not null) { - ThrowIfNull(value); + ArgumentNullException.ThrowIfNull(value); } TValue tvalue = default!; @@ -1265,7 +1264,7 @@ void IDictionary.Add(object key, object? value) /// bool IDictionary.Contains(object key) { - ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(key); return key is TKey tkey && ContainsKey(tkey); } @@ -1273,7 +1272,7 @@ bool IDictionary.Contains(object key) /// void IDictionary.Remove(object key) { - ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(key); if (key is TKey tkey) { @@ -1284,7 +1283,7 @@ void IDictionary.Remove(object key) /// void ICollection.CopyTo(Array array, int index) { - ThrowIfNull(array); + ArgumentNullException.ThrowIfNull(array); if (array.Rank != 1) { @@ -1505,7 +1504,7 @@ public sealed class KeyCollection : IList, IReadOnlyList, IList /// public void CopyTo(TKey[] array, int arrayIndex) { - ThrowIfNull(array); + ArgumentNullException.ThrowIfNull(array); ThrowIfNegative(arrayIndex); OrderedDictionary dictionary = _dictionary; @@ -1527,7 +1526,7 @@ public void CopyTo(TKey[] array, int arrayIndex) /// void ICollection.CopyTo(Array array, int index) { - ThrowIfNull(array); + ArgumentNullException.ThrowIfNull(array); if (array.Rank != 1) { @@ -1694,7 +1693,7 @@ public sealed class ValueCollection : IList, IReadOnlyList, ILis /// public void CopyTo(TValue[] array, int arrayIndex) { - ThrowIfNull(array); + ArgumentNullException.ThrowIfNull(array); ThrowIfNegative(arrayIndex); OrderedDictionary dictionary = _dictionary; @@ -1836,7 +1835,7 @@ int IList.IndexOf(object? value) /// void ICollection.CopyTo(Array array, int index) { - ThrowIfNull(array); + ArgumentNullException.ThrowIfNull(array); if (array.Rank != 1) { diff --git a/src/libraries/System.Collections/src/System/Collections/ThrowHelper.cs b/src/libraries/System.Collections/src/System/Collections/ThrowHelper.cs index b3d79a3293413b..aca60ad331db0a 100644 --- a/src/libraries/System.Collections/src/System/Collections/ThrowHelper.cs +++ b/src/libraries/System.Collections/src/System/Collections/ThrowHelper.cs @@ -35,17 +35,6 @@ internal static void ThrowVersionCheckFailed() => throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); #if !NET - /// Throws an if is null. - /// The reference type argument to validate as non-null. - /// The name of the parameter with which corresponds. - public static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression(nameof(argument))] string? paramName = null) - { - if (argument is null) - { - ThrowNull(paramName); - } - } - /// Throws an if is negative. /// The argument to validate as non-negative. /// The name of the parameter with which corresponds. diff --git a/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/PartBuilder.cs b/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/PartBuilder.cs index e0f9cb29774dd5..926adf7c7df760 100644 --- a/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/PartBuilder.cs +++ b/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/PartBuilder.cs @@ -99,10 +99,7 @@ public PartBuilder ExportInterfaces() public PartBuilder ExportInterfaces(Predicate interfaceFilter, Action exportConfiguration) { - if (interfaceFilter is null) - { - throw new ArgumentNullException(nameof(interfaceFilter)); - } + ArgumentNullException.ThrowIfNull(interfaceFilter); _interfaceExports.Add(Tuple.Create(interfaceFilter, exportConfiguration)); @@ -112,10 +109,7 @@ public PartBuilder ExportInterfaces(Predicate interfaceFilter, // Choose a property to export then configure it public PartBuilder ExportProperties(Predicate propertyFilter) { - if (propertyFilter is null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } + ArgumentNullException.ThrowIfNull(propertyFilter); return ExportProperties(propertyFilter, null); } @@ -123,10 +117,7 @@ public PartBuilder ExportProperties(Predicate propertyFilter) public PartBuilder ExportProperties(Predicate propertyFilter, Action exportConfiguration) { - if (propertyFilter is null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } + ArgumentNullException.ThrowIfNull(propertyFilter); _propertyExports.Add(Tuple.Create(propertyFilter, exportConfiguration, default(Type))); @@ -136,10 +127,7 @@ public PartBuilder ExportProperties(Predicate propertyFilter, // Choose a property to export then configure it public PartBuilder ExportProperties(Predicate propertyFilter) { - if (propertyFilter is null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } + ArgumentNullException.ThrowIfNull(propertyFilter); return ExportProperties(propertyFilter, null); } @@ -147,10 +135,7 @@ public PartBuilder ExportProperties(Predicate propertyFilter) public PartBuilder ExportProperties(Predicate propertyFilter, Action exportConfiguration) { - if (propertyFilter is null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } + ArgumentNullException.ThrowIfNull(propertyFilter); _propertyExports.Add(Tuple.Create(propertyFilter, exportConfiguration, typeof(T))); @@ -160,10 +145,7 @@ public PartBuilder ExportProperties(Predicate propertyFilter, // Choose a property to export then configure it public PartBuilder ImportProperties(Predicate propertyFilter) { - if (propertyFilter is null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } + ArgumentNullException.ThrowIfNull(propertyFilter); return ImportProperties(propertyFilter, null); } @@ -171,10 +153,7 @@ public PartBuilder ImportProperties(Predicate propertyFilter) public PartBuilder ImportProperties(Predicate propertyFilter, Action importConfiguration) { - if (propertyFilter is null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } + ArgumentNullException.ThrowIfNull(propertyFilter); _propertyImports.Add(Tuple.Create(propertyFilter, importConfiguration, default(Type))); return this; @@ -183,10 +162,7 @@ public PartBuilder ImportProperties(Predicate propertyFilter, // Choose a property to export then configure it public PartBuilder ImportProperties(Predicate propertyFilter) { - if (propertyFilter is null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } + ArgumentNullException.ThrowIfNull(propertyFilter); return ImportProperties(propertyFilter, null); } @@ -194,10 +170,7 @@ public PartBuilder ImportProperties(Predicate propertyFilter) public PartBuilder ImportProperties(Predicate propertyFilter, Action importConfiguration) { - if (propertyFilter is null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } + ArgumentNullException.ThrowIfNull(propertyFilter); _propertyImports.Add(Tuple.Create(propertyFilter, importConfiguration, typeof(T))); return this; diff --git a/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/PartBuilderOfT.cs b/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/PartBuilderOfT.cs index f607ec0f79ff69..ebee862f07707e 100644 --- a/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/PartBuilderOfT.cs +++ b/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/PartBuilderOfT.cs @@ -41,10 +41,7 @@ public void ConfigureExport(PropertyInfo _, ExportBuilder exportBuilder) private static PropertyInfo SelectProperties(Expression> propertyFilter) { - if (propertyFilter is null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } + ArgumentNullException.ThrowIfNull(propertyFilter); Expression expr = Reduce(propertyFilter).Body; if (expr.NodeType == ExpressionType.MemberAccess) @@ -96,10 +93,7 @@ public void ConfigureConstructorImports(ParameterInfo parameterInfo, ImportBuild private void ParseSelectConstructor(Expression> constructorFilter) { - if (constructorFilter is null) - { - throw new ArgumentNullException(nameof(constructorFilter)); - } + ArgumentNullException.ThrowIfNull(constructorFilter); Expression expr = Reduce(constructorFilter).Body; if (expr.NodeType != ExpressionType.New) @@ -153,10 +147,7 @@ internal PartBuilder(Predicate selectType) : base(selectType) public PartBuilder SelectConstructor(Expression> constructorFilter) { - if (constructorFilter is null) - { - throw new ArgumentNullException(nameof(constructorFilter)); - } + ArgumentNullException.ThrowIfNull(constructorFilter); var adapter = new ConstructorExpressionAdapter(constructorFilter); SelectConstructor(adapter.SelectConstructor, adapter.ConfigureConstructorImports); @@ -174,10 +165,7 @@ public PartBuilder ExportProperty( Expression> propertyFilter, Action exportConfiguration) { - if (propertyFilter is null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } + ArgumentNullException.ThrowIfNull(propertyFilter); var adapter = new PropertyExpressionAdapter(propertyFilter, null, exportConfiguration); ExportProperties(adapter.VerifyPropertyInfo, adapter.ConfigureExport); @@ -193,10 +181,7 @@ public PartBuilder ExportProperty(Expression> prop public PartBuilder ExportProperty(Expression> propertyFilter, Action exportConfiguration) { - if (propertyFilter is null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } + ArgumentNullException.ThrowIfNull(propertyFilter); var adapter = new PropertyExpressionAdapter(propertyFilter, null, exportConfiguration); ExportProperties(adapter.VerifyPropertyInfo, adapter.ConfigureExport); @@ -212,10 +197,7 @@ public PartBuilder ImportProperty(Expression> propertyFilter) public PartBuilder ImportProperty(Expression> propertyFilter, Action importConfiguration) { - if (propertyFilter is null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } + ArgumentNullException.ThrowIfNull(propertyFilter); var adapter = new PropertyExpressionAdapter(propertyFilter, importConfiguration, null); ImportProperties(adapter.VerifyPropertyInfo, adapter.ConfigureImport); @@ -231,10 +213,7 @@ public PartBuilder ImportProperty(Expression> prop public PartBuilder ImportProperty(Expression> propertyFilter, Action importConfiguration) { - if (propertyFilter is null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } + ArgumentNullException.ThrowIfNull(propertyFilter); var adapter = new PropertyExpressionAdapter(propertyFilter, importConfiguration, null); ImportProperties(adapter.VerifyPropertyInfo, adapter.ConfigureImport); diff --git a/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/RegistrationBuilder.cs b/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/RegistrationBuilder.cs index 5397b13063aa4a..13862e30745547 100644 --- a/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/RegistrationBuilder.cs +++ b/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/RegistrationBuilder.cs @@ -40,10 +40,7 @@ public PartBuilder ForTypesDerivedFrom() public PartBuilder ForTypesDerivedFrom(Type type) { - if (type is null) - { - throw new ArgumentNullException(nameof(type)); - } + ArgumentNullException.ThrowIfNull(type); var partBuilder = new PartBuilder((t) => type != t && type.IsAssignableFrom(t)); _conventions.Add(partBuilder); @@ -61,10 +58,7 @@ public PartBuilder ForType() public PartBuilder ForType(Type type) { - if (type is null) - { - throw new ArgumentNullException(nameof(type)); - } + ArgumentNullException.ThrowIfNull(type); var partBuilder = new PartBuilder((t) => t == type); _conventions.Add(partBuilder); @@ -74,10 +68,7 @@ public PartBuilder ForType(Type type) public PartBuilder ForTypesMatching(Predicate typeFilter) { - if (typeFilter is null) - { - throw new ArgumentNullException(nameof(typeFilter)); - } + ArgumentNullException.ThrowIfNull(typeFilter); var partBuilder = new PartBuilder(typeFilter); _conventions.Add(partBuilder); @@ -87,10 +78,7 @@ public PartBuilder ForTypesMatching(Predicate typeFilter) public PartBuilder ForTypesMatching(Predicate typeFilter) { - if (typeFilter is null) - { - throw new ArgumentNullException(nameof(typeFilter)); - } + ArgumentNullException.ThrowIfNull(typeFilter); var partBuilder = new PartBuilder(typeFilter); _conventions.Add(partBuilder); diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CatalogReflectionContextAttribute.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CatalogReflectionContextAttribute.cs index ac8af71eaae142..1c0bed36571a52 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CatalogReflectionContextAttribute.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CatalogReflectionContextAttribute.cs @@ -24,10 +24,7 @@ public CatalogReflectionContextAttribute(Type reflectionContextType) public ReflectionContext CreateReflectionContext() { - if (_reflectionContextType == null) - { - throw new ArgumentNullException(nameof(_reflectionContextType)); - } + ArgumentNullException.ThrowIfNull(_reflectionContextType); ReflectionContext reflectionContext; try diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExceptionBuilder.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExceptionBuilder.cs index 97fb367565b7f3..3234f3daa1daba 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExceptionBuilder.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExceptionBuilder.cs @@ -94,10 +94,7 @@ public static ArgumentException CreateReflectionModelInvalidPartDefinition(strin throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(parameterName)), nameof(parameterName)); } - if (partDefinitionType == null) - { - throw new ArgumentNullException(nameof(partDefinitionType)); - } + ArgumentNullException.ThrowIfNull(partDefinitionType); return new ArgumentException(SR.Format(SR.ReflectionModel_InvalidPartDefinition, partDefinitionType), parameterName); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportServices.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportServices.cs index 537bb02687dd73..ad585f1b9dbbc0 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportServices.cs @@ -56,10 +56,7 @@ internal static Func CreateStronglyTypedLazyFactory(Type? export genericMethod = _createStronglyTypedLazyOfT.MakeGenericMethod(exportType ?? ExportServices.DefaultExportedValueType); } - if (genericMethod == null) - { - throw new ArgumentNullException(nameof(genericMethod)); - } + ArgumentNullException.ThrowIfNull(genericMethod); return (Func)Delegate.CreateDelegate(typeof(Func), genericMethod); } @@ -69,10 +66,7 @@ internal static Func> CreateSemiStronglyTypedLazyFa MethodInfo genericMethod = _createSemiStronglyTypedLazy.MakeGenericMethod( exportType ?? ExportServices.DefaultExportedValueType, metadataViewType ?? ExportServices.DefaultMetadataViewType); - if (genericMethod == null) - { - throw new ArgumentNullException(nameof(genericMethod)); - } + ArgumentNullException.ThrowIfNull(genericMethod); return (Func>)Delegate.CreateDelegate(typeof(Func>), genericMethod); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.cs index 8b465a5e0f0f35..5e2afdabcd49c6 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.cs @@ -509,15 +509,8 @@ private CatalogPart GetSharedPart(ComposablePartDefinition partDefinition) { ThrowIfDisposed(); EnsureRunning(); - if (part == null) - { - throw new ArgumentNullException(nameof(part)); - } - - if (export == null) - { - throw new ArgumentNullException(nameof(export)); - } + ArgumentNullException.ThrowIfNull(part); + ArgumentNullException.ThrowIfNull(export); // We don't protect against thread racing here, as "importsSatisfied" is merely an optimization // if two threads satisfy imports twice, the results is the same, just the perf hit is heavier. diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/GenericSpecializationPartCreationInfo.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/GenericSpecializationPartCreationInfo.cs index 4ae89c9869db45..9055c8bf92e1c6 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/GenericSpecializationPartCreationInfo.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/GenericSpecializationPartCreationInfo.cs @@ -109,10 +109,7 @@ public Lazy GetLazyPartType() private MemberInfo[] GetAccessors(LazyMemberInfo originalLazyMember) { BuildTables(); - if (_membersTable == null) - { - throw new ArgumentNullException(nameof(_membersTable)); - } + ArgumentNullException.ThrowIfNull(_membersTable); return _membersTable[originalLazyMember]; } @@ -120,10 +117,7 @@ private MemberInfo[] GetAccessors(LazyMemberInfo originalLazyMember) private ParameterInfo GetParameter(Lazy originalParameter) { BuildTables(); - if (_parametersTable == null) - { - throw new ArgumentNullException(nameof(_parametersTable)); - } + ArgumentNullException.ThrowIfNull(_parametersTable); return _parametersTable[originalParameter]; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionExtensions.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionExtensions.cs index cc21bf792e3fc3..86dc7ba5ded436 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionExtensions.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionExtensions.cs @@ -104,10 +104,7 @@ public static ReflectionParameter ToReflectionParameter(this ParameterInfo param public static ReflectionMethod ToReflectionMethod(this MethodInfo method) { - if (method == null) - { - throw new ArgumentNullException(nameof(method)); - } + ArgumentNullException.ThrowIfNull(method); return new ReflectionMethod(method); } diff --git a/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ConventionBuilder.cs b/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ConventionBuilder.cs index c69ebe91e7aaa1..424c03d8a9026a 100644 --- a/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ConventionBuilder.cs +++ b/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ConventionBuilder.cs @@ -47,10 +47,7 @@ public PartConventionBuilder ForTypesDerivedFrom() /// A that must be used to specify the rule. public PartConventionBuilder ForTypesDerivedFrom(Type type) { - if (type is null) - { - throw new ArgumentNullException(nameof(type)); - } + ArgumentNullException.ThrowIfNull(type); var partBuilder = new PartConventionBuilder((t) => IsDescendentOf(t, type)); _conventions.Add(partBuilder); @@ -76,10 +73,7 @@ public PartConventionBuilder ForType() /// A that must be used to specify the rule. public PartConventionBuilder ForType(Type type) { - if (type is null) - { - throw new ArgumentNullException(nameof(type)); - } + ArgumentNullException.ThrowIfNull(type); var partBuilder = new PartConventionBuilder((t) => t == type); _conventions.Add(partBuilder); @@ -95,10 +89,7 @@ public PartConventionBuilder ForType(Type type) /// A that must be used to specify the rule. public PartConventionBuilder ForTypesMatching(Predicate typeFilter) { - if (typeFilter is null) - { - throw new ArgumentNullException(nameof(typeFilter)); - } + ArgumentNullException.ThrowIfNull(typeFilter); var partBuilder = new PartConventionBuilder(typeFilter); _conventions.Add(partBuilder); @@ -113,10 +104,7 @@ public PartConventionBuilder ForTypesMatching(Predicate typeFilter) /// A that must be used to specify the rule. public PartConventionBuilder ForTypesMatching(Predicate typeFilter) { - if (typeFilter is null) - { - throw new ArgumentNullException(nameof(typeFilter)); - } + ArgumentNullException.ThrowIfNull(typeFilter); var partBuilder = new PartConventionBuilder(typeFilter); _conventions.Add(partBuilder); @@ -158,10 +146,7 @@ private List>> EvaluateThisTypeInfoAgainstTheConve /// The list of applied attributes. public override IEnumerable GetCustomAttributes(Type reflectedType, System.Reflection.MemberInfo member) { - if (member is null) - { - throw new ArgumentNullException(nameof(member)); - } + ArgumentNullException.ThrowIfNull(member); // Now edit the attributes returned from the base type List cachedAttributes = null; @@ -298,10 +283,7 @@ private List ReadMemberCustomAttributes(Type reflectedType, System.Re /// The list of applied attributes. public override IEnumerable GetCustomAttributes(Type reflectedType, System.Reflection.ParameterInfo parameter) { - if (parameter is null) - { - throw new ArgumentNullException(nameof(parameter)); - } + ArgumentNullException.ThrowIfNull(parameter); IEnumerable attributes = parameter.GetCustomAttributes(false); List cachedAttributes = ReadParameterCustomAttributes(reflectedType, parameter); diff --git a/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ExportConventionBuilder.cs b/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ExportConventionBuilder.cs index dea171c75a9913..8960be6a6786cb 100644 --- a/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ExportConventionBuilder.cs +++ b/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ExportConventionBuilder.cs @@ -40,10 +40,7 @@ public ExportConventionBuilder AsContractType() /// An export builder allowing further configuration. public ExportConventionBuilder AsContractType(Type type) { - if (type is null) - { - throw new ArgumentNullException(nameof(type)); - } + ArgumentNullException.ThrowIfNull(type); _contractType = type; return this; @@ -56,10 +53,7 @@ public ExportConventionBuilder AsContractType(Type type) /// An export builder allowing further configuration. public ExportConventionBuilder AsContractName(string contractName) { - if (contractName is null) - { - throw new ArgumentNullException(nameof(contractName)); - } + ArgumentNullException.ThrowIfNull(contractName); if (contractName.Length == 0) { @@ -76,10 +70,7 @@ public ExportConventionBuilder AsContractName(string contractName) /// An export builder allowing further configuration. public ExportConventionBuilder AsContractName(Func getContractNameFromPartType) { - if (getContractNameFromPartType is null) - { - throw new ArgumentNullException(nameof(getContractNameFromPartType)); - } + ArgumentNullException.ThrowIfNull(getContractNameFromPartType); _getContractNameFromPartType = getContractNameFromPartType; return this; @@ -93,10 +84,7 @@ public ExportConventionBuilder AsContractName(Func getContractName /// An export builder allowing further configuration. public ExportConventionBuilder AddMetadata(string name, object value) { - if (name is null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); if (name.Length == 0) { @@ -116,14 +104,8 @@ public ExportConventionBuilder AddMetadata(string name, object value) /// An export builder allowing further configuration. public ExportConventionBuilder AddMetadata(string name, Func getValueFromPartType) { - if (name is null) - { - throw new ArgumentNullException(nameof(name)); - } - if (getValueFromPartType is null) - { - throw new ArgumentNullException(nameof(getValueFromPartType)); - } + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(getValueFromPartType); if (name.Length == 0) { diff --git a/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ImportConventionBuilder.cs b/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ImportConventionBuilder.cs index 3b9143b8f3dc95..3a2d16799f84e2 100644 --- a/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ImportConventionBuilder.cs +++ b/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ImportConventionBuilder.cs @@ -30,10 +30,7 @@ internal ImportConventionBuilder() { } /// An import builder allowing further configuration. public ImportConventionBuilder AsContractName(string contractName) { - if (contractName is null) - { - throw new ArgumentNullException(nameof(contractName)); - } + ArgumentNullException.ThrowIfNull(contractName); if (contractName.Length == 0) { @@ -50,10 +47,7 @@ public ImportConventionBuilder AsContractName(string contractName) /// An export builder allowing further configuration. public ImportConventionBuilder AsContractName(Func getContractNameFromPartType) { - if (getContractNameFromPartType is null) - { - throw new ArgumentNullException(nameof(getContractNameFromPartType)); - } + ArgumentNullException.ThrowIfNull(getContractNameFromPartType); _getContractNameFromPartType = getContractNameFromPartType; return this; @@ -98,10 +92,7 @@ public ImportConventionBuilder AllowDefault() /// An import builder allowing further configuration. public ImportConventionBuilder AddMetadataConstraint(string name, object value) { - if (name is null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); if (name.Length == 0) { @@ -121,14 +112,8 @@ public ImportConventionBuilder AddMetadataConstraint(string name, object value) /// An export builder allowing further configuration. public ImportConventionBuilder AddMetadataConstraint(string name, Func getConstraintValueFromPartType) { - if (name is null) - { - throw new ArgumentNullException(nameof(name)); - } - if (getConstraintValueFromPartType is null) - { - throw new ArgumentNullException(nameof(getConstraintValueFromPartType)); - } + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(getConstraintValueFromPartType); if (name.Length == 0) { diff --git a/src/libraries/System.Composition.Convention/src/System/Composition/Convention/PartConventionBuilder.cs b/src/libraries/System.Composition.Convention/src/System/Composition/Convention/PartConventionBuilder.cs index 76b0efd4898ecd..8592a46311dc5a 100644 --- a/src/libraries/System.Composition.Convention/src/System/Composition/Convention/PartConventionBuilder.cs +++ b/src/libraries/System.Composition.Convention/src/System/Composition/Convention/PartConventionBuilder.cs @@ -65,10 +65,7 @@ public PartConventionBuilder Export() /// A part builder allowing further configuration of the part. public PartConventionBuilder Export(Action exportConfiguration) { - if (exportConfiguration is null) - { - throw new ArgumentNullException(nameof(exportConfiguration)); - } + ArgumentNullException.ThrowIfNull(exportConfiguration); var exportBuilder = new ExportConventionBuilder(); exportConfiguration(exportBuilder); @@ -94,10 +91,7 @@ public PartConventionBuilder Export() /// A part builder allowing further configuration of the part. public PartConventionBuilder Export(Action exportConfiguration) { - if (exportConfiguration is null) - { - throw new ArgumentNullException(nameof(exportConfiguration)); - } + ArgumentNullException.ThrowIfNull(exportConfiguration); ExportConventionBuilder exportBuilder = new ExportConventionBuilder().AsContractType(); exportConfiguration(exportBuilder); @@ -112,10 +106,7 @@ public PartConventionBuilder Export(Action exportCon /// A part builder allowing further configuration of the part. public PartConventionBuilder SelectConstructor(Func, ConstructorInfo> constructorSelector) { - if (constructorSelector is null) - { - throw new ArgumentNullException(nameof(constructorSelector)); - } + ArgumentNullException.ThrowIfNull(constructorSelector); _constructorFilter = constructorSelector; return this; @@ -130,10 +121,7 @@ public PartConventionBuilder SelectConstructor(Func public PartConventionBuilder SelectConstructor(Func, ConstructorInfo> constructorSelector, Action importConfiguration) { - if (importConfiguration is null) - { - throw new ArgumentNullException(nameof(importConfiguration)); - } + ArgumentNullException.ThrowIfNull(importConfiguration); _configureConstructorImports = importConfiguration; SelectConstructor(constructorSelector); @@ -147,10 +135,7 @@ public PartConventionBuilder SelectConstructor(Func /// A part builder allowing further configuration of the part. public PartConventionBuilder ExportInterfaces(Predicate interfaceFilter) { - if (interfaceFilter is null) - { - throw new ArgumentNullException(nameof(interfaceFilter)); - } + ArgumentNullException.ThrowIfNull(interfaceFilter); return ExportInterfacesImpl(interfaceFilter, null); } @@ -173,14 +158,8 @@ public PartConventionBuilder ExportInterfaces() public PartConventionBuilder ExportInterfaces(Predicate interfaceFilter, Action exportConfiguration) { - if (interfaceFilter is null) - { - throw new ArgumentNullException(nameof(interfaceFilter)); - } - if (exportConfiguration is null) - { - throw new ArgumentNullException(nameof(exportConfiguration)); - } + ArgumentNullException.ThrowIfNull(interfaceFilter); + ArgumentNullException.ThrowIfNull(exportConfiguration); return ExportInterfacesImpl(interfaceFilter, exportConfiguration); } @@ -199,10 +178,7 @@ private PartConventionBuilder ExportInterfacesImpl(Predicate interfaceFilt /// A part builder allowing further configuration of the part. public PartConventionBuilder ExportProperties(Predicate propertyFilter) { - if (propertyFilter is null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } + ArgumentNullException.ThrowIfNull(propertyFilter); return ExportPropertiesImpl(propertyFilter, null); } @@ -216,14 +192,8 @@ public PartConventionBuilder ExportProperties(Predicate propertyFi public PartConventionBuilder ExportProperties(Predicate propertyFilter, Action exportConfiguration) { - if (propertyFilter is null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } - if (exportConfiguration is null) - { - throw new ArgumentNullException(nameof(exportConfiguration)); - } + ArgumentNullException.ThrowIfNull(propertyFilter); + ArgumentNullException.ThrowIfNull(exportConfiguration); return ExportPropertiesImpl(propertyFilter, exportConfiguration); } @@ -243,10 +213,7 @@ private PartConventionBuilder ExportPropertiesImpl(Predicate prope /// A part builder allowing further configuration of the part. public PartConventionBuilder ExportProperties(Predicate propertyFilter) { - if (propertyFilter is null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } + ArgumentNullException.ThrowIfNull(propertyFilter); return ExportPropertiesImpl(propertyFilter, null); } @@ -261,14 +228,8 @@ public PartConventionBuilder ExportProperties(Predicate propert public PartConventionBuilder ExportProperties(Predicate propertyFilter, Action exportConfiguration) { - if (propertyFilter is null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } - if (exportConfiguration is null) - { - throw new ArgumentNullException(nameof(exportConfiguration)); - } + ArgumentNullException.ThrowIfNull(propertyFilter); + ArgumentNullException.ThrowIfNull(exportConfiguration); return ExportPropertiesImpl(propertyFilter, exportConfiguration); } @@ -287,10 +248,7 @@ private PartConventionBuilder ExportPropertiesImpl(Predicate pr /// A part builder allowing further configuration of the part. public PartConventionBuilder ImportProperties(Predicate propertyFilter) { - if (propertyFilter is null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } + ArgumentNullException.ThrowIfNull(propertyFilter); return ImportPropertiesImpl(propertyFilter, null); } @@ -304,14 +262,8 @@ public PartConventionBuilder ImportProperties(Predicate propertyFi public PartConventionBuilder ImportProperties(Predicate propertyFilter, Action importConfiguration) { - if (propertyFilter is null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } - if (importConfiguration is null) - { - throw new ArgumentNullException(nameof(importConfiguration)); - } + ArgumentNullException.ThrowIfNull(propertyFilter); + ArgumentNullException.ThrowIfNull(importConfiguration); return ImportPropertiesImpl(propertyFilter, importConfiguration); } @@ -331,10 +283,7 @@ private PartConventionBuilder ImportPropertiesImpl(Predicate prope /// A part builder allowing further configuration of the part. public PartConventionBuilder ImportProperties(Predicate propertyFilter) { - if (propertyFilter is null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } + ArgumentNullException.ThrowIfNull(propertyFilter); return ImportPropertiesImpl(propertyFilter, null); } @@ -349,14 +298,8 @@ public PartConventionBuilder ImportProperties(Predicate propert public PartConventionBuilder ImportProperties(Predicate propertyFilter, Action importConfiguration) { - if (propertyFilter is null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } - if (importConfiguration is null) - { - throw new ArgumentNullException(nameof(importConfiguration)); - } + ArgumentNullException.ThrowIfNull(propertyFilter); + ArgumentNullException.ThrowIfNull(importConfiguration); return ImportPropertiesImpl(propertyFilter, importConfiguration); } @@ -395,10 +338,7 @@ public PartConventionBuilder Shared() /// A part builder allowing further configuration of the part. public PartConventionBuilder Shared(string sharingBoundary) { - if (sharingBoundary is null) - { - throw new ArgumentNullException(nameof(sharingBoundary)); - } + ArgumentNullException.ThrowIfNull(sharingBoundary); if (sharingBoundary.Length == 0) { @@ -423,10 +363,7 @@ private PartConventionBuilder SharedImpl(string sharingBoundary) /// A part builder allowing further configuration of the part. public PartConventionBuilder AddPartMetadata(string name, object value) { - if (name is null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); if (name.Length == 0) { @@ -446,14 +383,8 @@ public PartConventionBuilder AddPartMetadata(string name, object value) /// A part builder allowing further configuration of the part. public PartConventionBuilder AddPartMetadata(string name, Func getValueFromPartType) { - if (name is null) - { - throw new ArgumentNullException(nameof(name)); - } - if (getValueFromPartType is null) - { - throw new ArgumentNullException(nameof(getValueFromPartType)); - } + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(getValueFromPartType); if (name.Length == 0) { diff --git a/src/libraries/System.Composition.Convention/src/System/Composition/Convention/PartConventionBuilderOfT.cs b/src/libraries/System.Composition.Convention/src/System/Composition/Convention/PartConventionBuilderOfT.cs index 66a4713a8cc2b8..bdde26ed1876ff 100644 --- a/src/libraries/System.Composition.Convention/src/System/Composition/Convention/PartConventionBuilderOfT.cs +++ b/src/libraries/System.Composition.Convention/src/System/Composition/Convention/PartConventionBuilderOfT.cs @@ -29,10 +29,7 @@ public bool VerifyMethodInfo(MethodInfo mi) private static MethodInfo SelectMethods(Expression> methodSelector) { - if (methodSelector is null) - { - throw new ArgumentNullException(nameof(methodSelector)); - } + ArgumentNullException.ThrowIfNull(methodSelector); Expression expr = Reduce(methodSelector).Body; if (expr.NodeType == ExpressionType.Call) @@ -100,10 +97,7 @@ public void ConfigureExport(PropertyInfo _, ExportConventionBuilder exportBuilde private static PropertyInfo SelectProperties(Expression> propertySelector) { - if (propertySelector is null) - { - throw new ArgumentNullException(nameof(propertySelector)); - } + ArgumentNullException.ThrowIfNull(propertySelector); Expression expr = Reduce(propertySelector).Body; if (expr.NodeType == ExpressionType.MemberAccess) @@ -159,10 +153,7 @@ public void ConfigureConstructorImports(ParameterInfo parameterInfo, ImportConve private void ParseSelectConstructor(Expression> constructorSelector) { - if (constructorSelector is null) - { - throw new ArgumentNullException(nameof(constructorSelector)); - } + ArgumentNullException.ThrowIfNull(constructorSelector); Expression expr = Reduce(constructorSelector).Body; if (expr.NodeType != ExpressionType.New) @@ -217,10 +208,7 @@ internal PartConventionBuilder(Predicate selectType) : base(selectType) /// A part builder allowing further configuration of the part. public PartConventionBuilder SelectConstructor(Expression> constructorSelector) { - if (constructorSelector is null) - { - throw new ArgumentNullException(nameof(constructorSelector)); - } + ArgumentNullException.ThrowIfNull(constructorSelector); var adapter = new ConstructorExpressionAdapter(constructorSelector); base.SelectConstructor(adapter.SelectConstructor, adapter.ConfigureConstructorImports); @@ -247,10 +235,7 @@ public PartConventionBuilder ExportProperty( Expression> propertySelector, Action exportConfiguration) { - if (propertySelector is null) - { - throw new ArgumentNullException(nameof(propertySelector)); - } + ArgumentNullException.ThrowIfNull(propertySelector); var adapter = new PropertyExpressionAdapter(propertySelector, null, exportConfiguration); base.ExportProperties(adapter.VerifyPropertyInfo, adapter.ConfigureExport); @@ -280,10 +265,7 @@ public PartConventionBuilder ExportProperty( Expression> propertySelector, Action exportConfiguration) { - if (propertySelector is null) - { - throw new ArgumentNullException(nameof(propertySelector)); - } + ArgumentNullException.ThrowIfNull(propertySelector); var adapter = new PropertyExpressionAdapter(propertySelector, null, exportConfiguration); base.ExportProperties(adapter.VerifyPropertyInfo, adapter.ConfigureExport); @@ -310,10 +292,7 @@ public PartConventionBuilder ImportProperty( Expression> propertySelector, Action importConfiguration) { - if (propertySelector is null) - { - throw new ArgumentNullException(nameof(propertySelector)); - } + ArgumentNullException.ThrowIfNull(propertySelector); var adapter = new PropertyExpressionAdapter(propertySelector, importConfiguration, null); base.ImportProperties(adapter.VerifyPropertyInfo, adapter.ConfigureImport); @@ -342,10 +321,7 @@ public PartConventionBuilder ImportProperty( Expression> propertySelector, Action importConfiguration) { - if (propertySelector is null) - { - throw new ArgumentNullException(nameof(propertySelector)); - } + ArgumentNullException.ThrowIfNull(propertySelector); var adapter = new PropertyExpressionAdapter(propertySelector, importConfiguration, null); base.ImportProperties(adapter.VerifyPropertyInfo, adapter.ConfigureImport); @@ -358,10 +334,7 @@ public PartConventionBuilder ImportProperty( /// A part builder allowing further configuration of the part. public PartConventionBuilder NotifyImportsSatisfied(Expression> methodSelector) { - if (methodSelector is null) - { - throw new ArgumentNullException(nameof(methodSelector)); - } + ArgumentNullException.ThrowIfNull(methodSelector); var adapter = new MethodExpressionAdapter(methodSelector); base.NotifyImportsSatisfied(adapter.VerifyMethodInfo); diff --git a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/CompositionHost.cs b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/CompositionHost.cs index a40a23f119d920..3c328d7308af50 100644 --- a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/CompositionHost.cs +++ b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/CompositionHost.cs @@ -43,10 +43,7 @@ public static CompositionHost CreateCompositionHost(params ExportDescriptorProvi /// The container as an . public static CompositionHost CreateCompositionHost(IEnumerable providers) { - if (providers is null) - { - throw new ArgumentNullException(nameof(providers)); - } + ArgumentNullException.ThrowIfNull(providers); var allProviders = new ExportDescriptorProvider[] { new LazyExportDescriptorProvider(), diff --git a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/CompositionDependency.cs b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/CompositionDependency.cs index 1d1d0a38e34e75..877d5d9fa24b02 100644 --- a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/CompositionDependency.cs +++ b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/CompositionDependency.cs @@ -39,18 +39,9 @@ public class CompositionDependency /// The contract required by the dependency. public static CompositionDependency Satisfied(CompositionContract contract, ExportDescriptorPromise target, bool isPrerequisite, object site) { - if (contract is null) - { - throw new ArgumentNullException(nameof(contract)); - } - if (target is null) - { - throw new ArgumentNullException(nameof(target)); - } - if (site is null) - { - throw new ArgumentNullException(nameof(site)); - } + ArgumentNullException.ThrowIfNull(contract); + ArgumentNullException.ThrowIfNull(target); + ArgumentNullException.ThrowIfNull(site); return new CompositionDependency(contract, target, isPrerequisite, site); } @@ -64,14 +55,8 @@ public static CompositionDependency Satisfied(CompositionContract contract, Expo /// The contract required by the dependency. public static CompositionDependency Missing(CompositionContract contract, object site) { - if (contract is null) - { - throw new ArgumentNullException(nameof(contract)); - } - if (site is null) - { - throw new ArgumentNullException(nameof(site)); - } + ArgumentNullException.ThrowIfNull(contract); + ArgumentNullException.ThrowIfNull(site); return new CompositionDependency(contract, site); } @@ -86,18 +71,9 @@ public static CompositionDependency Missing(CompositionContract contract, object /// The contract required by the dependency. public static CompositionDependency Oversupplied(CompositionContract contract, IEnumerable targets, object site) { - if (contract is null) - { - throw new ArgumentNullException(nameof(contract)); - } - if (targets is null) - { - throw new ArgumentNullException(nameof(targets)); - } - if (site is null) - { - throw new ArgumentNullException(nameof(site)); - } + ArgumentNullException.ThrowIfNull(contract); + ArgumentNullException.ThrowIfNull(targets); + ArgumentNullException.ThrowIfNull(site); return new CompositionDependency(contract, targets, site); } diff --git a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/CompositionOperation.cs b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/CompositionOperation.cs index 5e446b3350ace0..05b78f62dc1570 100644 --- a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/CompositionOperation.cs +++ b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/CompositionOperation.cs @@ -30,14 +30,8 @@ private CompositionOperation() { } /// The composed object graph. public static object Run(LifetimeContext outermostLifetimeContext, CompositeActivator compositionRootActivator) { - if (outermostLifetimeContext is null) - { - throw new ArgumentNullException(nameof(outermostLifetimeContext)); - } - if (compositionRootActivator is null) - { - throw new ArgumentNullException(nameof(compositionRootActivator)); - } + ArgumentNullException.ThrowIfNull(outermostLifetimeContext); + ArgumentNullException.ThrowIfNull(compositionRootActivator); using (var operation = new CompositionOperation()) { @@ -54,10 +48,7 @@ public static object Run(LifetimeContext outermostLifetimeContext, CompositeActi /// Action to run. public void AddNonPrerequisiteAction(Action action) { - if (action is null) - { - throw new ArgumentNullException(nameof(action)); - } + ArgumentNullException.ThrowIfNull(action); _nonPrerequisiteActions ??= new List(); @@ -71,10 +62,7 @@ public void AddNonPrerequisiteAction(Action action) /// Action to run. public void AddPostCompositionAction(Action action) { - if (action is null) - { - throw new ArgumentNullException(nameof(action)); - } + ArgumentNullException.ThrowIfNull(action); _postCompositionActions ??= new List(); diff --git a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/DirectExportDescriptor.cs b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/DirectExportDescriptor.cs index 4741349d399237..8de674a0009786 100644 --- a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/DirectExportDescriptor.cs +++ b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/DirectExportDescriptor.cs @@ -12,14 +12,8 @@ internal sealed class DirectExportDescriptor : ExportDescriptor public DirectExportDescriptor(CompositeActivator activator, IDictionary metadata) { - if (activator is null) - { - throw new ArgumentNullException(nameof(activator)); - } - if (metadata is null) - { - throw new ArgumentNullException(nameof(metadata)); - } + ArgumentNullException.ThrowIfNull(activator); + ArgumentNullException.ThrowIfNull(metadata); _activator = activator; _metadata = metadata; diff --git a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Util/Formatters.cs b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Util/Formatters.cs index c7e0af32f4ba79..ad67307ac73875 100644 --- a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Util/Formatters.cs +++ b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Util/Formatters.cs @@ -10,10 +10,7 @@ internal static class Formatters { public static string ReadableList(IEnumerable items) { - if (items is null) - { - throw new ArgumentNullException(nameof(items)); - } + ArgumentNullException.ThrowIfNull(items); string reply = string.Join(SR.Formatter_ListSeparatorWithSpace, items.OrderBy(t => t)); return !string.IsNullOrEmpty(reply) ? reply : SR.Formatter_None; @@ -21,10 +18,7 @@ public static string ReadableList(IEnumerable items) public static string Format(Type type) { - if (type is null) - { - throw new ArgumentNullException(nameof(type)); - } + ArgumentNullException.ThrowIfNull(type); if (type.IsConstructedGenericType) { @@ -35,10 +29,7 @@ public static string Format(Type type) private static string FormatClosedGeneric(Type closedGenericType) { - if (closedGenericType is null) - { - throw new ArgumentNullException(nameof(closedGenericType)); - } + ArgumentNullException.ThrowIfNull(closedGenericType); if (!closedGenericType.IsConstructedGenericType) { diff --git a/src/libraries/System.Composition.Runtime/src/System/Composition/Hosting/Core/CompositionContract.cs b/src/libraries/System.Composition.Runtime/src/System/Composition/Hosting/Core/CompositionContract.cs index 641dde6524a5ea..9dd45fdd66aef9 100644 --- a/src/libraries/System.Composition.Runtime/src/System/Composition/Hosting/Core/CompositionContract.cs +++ b/src/libraries/System.Composition.Runtime/src/System/Composition/Hosting/Core/CompositionContract.cs @@ -140,10 +140,7 @@ public CompositionContract ChangeType(Type newContractType) /// True if the constraint is present and of the correct type, otherwise false. public bool TryUnwrapMetadataConstraint(string constraintName, out T constraintValue, out CompositionContract remainingContract) { - if (constraintName is null) - { - throw new ArgumentNullException(nameof(constraintName)); - } + ArgumentNullException.ThrowIfNull(constraintName); constraintValue = default(T); remainingContract = null; diff --git a/src/libraries/System.Composition.TypedParts/src/System/Composition/CompositionContextExtensions.cs b/src/libraries/System.Composition.TypedParts/src/System/Composition/CompositionContextExtensions.cs index 624acc2027efa8..a67a589ff75dcf 100644 --- a/src/libraries/System.Composition.TypedParts/src/System/Composition/CompositionContextExtensions.cs +++ b/src/libraries/System.Composition.TypedParts/src/System/Composition/CompositionContextExtensions.cs @@ -44,18 +44,9 @@ public static void SatisfyImports(this CompositionContext compositionContext, ob private static void SatisfyImportsInternal(this CompositionContext exportProvider, object objectWithLooseImports, AttributedModelProvider conventions) { - if (exportProvider is null) - { - throw new ArgumentNullException(nameof(exportProvider)); - } - if (objectWithLooseImports is null) - { - throw new ArgumentNullException(nameof(objectWithLooseImports)); - } - if (conventions is null) - { - throw new ArgumentNullException(nameof(conventions)); - } + ArgumentNullException.ThrowIfNull(exportProvider); + ArgumentNullException.ThrowIfNull(objectWithLooseImports); + ArgumentNullException.ThrowIfNull(conventions); var objType = objectWithLooseImports.GetType(); diff --git a/src/libraries/System.Composition.TypedParts/src/System/Composition/Hosting/ContainerConfiguration.cs b/src/libraries/System.Composition.TypedParts/src/System/Composition/Hosting/ContainerConfiguration.cs index ea9c1d5d0e439c..c0fe85ccf824ef 100644 --- a/src/libraries/System.Composition.TypedParts/src/System/Composition/Hosting/ContainerConfiguration.cs +++ b/src/libraries/System.Composition.TypedParts/src/System/Composition/Hosting/ContainerConfiguration.cs @@ -49,10 +49,7 @@ public CompositionHost CreateContainer() /// A configuration object allowing configuration to continue. public ContainerConfiguration WithProvider(ExportDescriptorProvider exportDescriptorProvider) { - if (exportDescriptorProvider is null) - { - throw new ArgumentNullException(nameof(exportDescriptorProvider)); - } + ArgumentNullException.ThrowIfNull(exportDescriptorProvider); _addedSources.Add(exportDescriptorProvider); return this; @@ -67,10 +64,7 @@ public ContainerConfiguration WithProvider(ExportDescriptorProvider exportDescri /// A configuration object allowing configuration to continue. public ContainerConfiguration WithDefaultConventions(AttributedModelProvider conventions) { - if (conventions is null) - { - throw new ArgumentNullException(nameof(conventions)); - } + ArgumentNullException.ThrowIfNull(conventions); if (_defaultAttributeContext != null) throw new InvalidOperationException(SR.ContainerConfiguration_DefaultConventionSet); @@ -157,10 +151,7 @@ public ContainerConfiguration WithParts(IEnumerable partTypes) /// A configuration object allowing configuration to continue. public ContainerConfiguration WithParts(IEnumerable partTypes, AttributedModelProvider conventions) { - if (partTypes is null) - { - throw new ArgumentNullException(nameof(partTypes)); - } + ArgumentNullException.ThrowIfNull(partTypes); _types.Add(Tuple.Create(partTypes, conventions)); return this; @@ -209,10 +200,7 @@ public ContainerConfiguration WithAssemblies(IEnumerable assemblies) /// A configuration object allowing configuration to continue. public ContainerConfiguration WithAssemblies(IEnumerable assemblies, AttributedModelProvider conventions) { - if (assemblies is null) - { - throw new ArgumentNullException(nameof(assemblies)); - } + ArgumentNullException.ThrowIfNull(assemblies); return WithParts(assemblies.SelectMany(a => a.DefinedTypes.Select(dt => dt.AsType())), conventions); } @@ -225,10 +213,7 @@ public ContainerConfiguration WithAssemblies(IEnumerable assemblies, A /// A configuration object allowing configuration to continue. public ContainerConfiguration WithExport(TExport exportedInstance) { - if (exportedInstance is null) - { - throw new ArgumentNullException(nameof(exportedInstance)); - } + ArgumentNullException.ThrowIfNull(exportedInstance); return WithExport(exportedInstance, null, null); } @@ -243,10 +228,7 @@ public ContainerConfiguration WithExport(TExport exportedInstance) /// A configuration object allowing configuration to continue. public ContainerConfiguration WithExport(TExport exportedInstance, string contractName = null, IDictionary metadata = null) { - if (exportedInstance is null) - { - throw new ArgumentNullException(nameof(exportedInstance)); - } + ArgumentNullException.ThrowIfNull(exportedInstance); return WithExport(typeof(TExport), exportedInstance, contractName, metadata); } @@ -259,14 +241,8 @@ public ContainerConfiguration WithExport(TExport exportedInstance, stri /// A configuration object allowing configuration to continue. public ContainerConfiguration WithExport(Type contractType, object exportedInstance) { - if (contractType is null) - { - throw new ArgumentNullException(nameof(contractType)); - } - if (exportedInstance is null) - { - throw new ArgumentNullException(nameof(exportedInstance)); - } + ArgumentNullException.ThrowIfNull(contractType); + ArgumentNullException.ThrowIfNull(exportedInstance); return WithExport(contractType, exportedInstance, null, null); } @@ -281,14 +257,8 @@ public ContainerConfiguration WithExport(Type contractType, object exportedInsta /// A configuration object allowing configuration to continue. public ContainerConfiguration WithExport(Type contractType, object exportedInstance, string contractName = null, IDictionary metadata = null) { - if (contractType is null) - { - throw new ArgumentNullException(nameof(contractType)); - } - if (exportedInstance is null) - { - throw new ArgumentNullException(nameof(exportedInstance)); - } + ArgumentNullException.ThrowIfNull(contractType); + ArgumentNullException.ThrowIfNull(exportedInstance); return WithProvider(new InstanceExportDescriptorProvider(exportedInstance, contractType, contractName, metadata)); } diff --git a/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/ActivationFeatures/OnImportsSatisfiedFeature.cs b/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/ActivationFeatures/OnImportsSatisfiedFeature.cs index 25fe02e0ea94e2..9b0e7f096b8d2b 100644 --- a/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/ActivationFeatures/OnImportsSatisfiedFeature.cs +++ b/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/ActivationFeatures/OnImportsSatisfiedFeature.cs @@ -21,10 +21,7 @@ internal sealed class OnImportsSatisfiedFeature : ActivationFeature public OnImportsSatisfiedFeature(AttributedModelProvider attributeContext) { - if (attributeContext is null) - { - throw new ArgumentNullException(nameof(attributeContext)); - } + ArgumentNullException.ThrowIfNull(attributeContext); _attributeContext = attributeContext; } diff --git a/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Util/DirectAttributeContext.cs b/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Util/DirectAttributeContext.cs index 053d5d20d28575..8dd0b5cdc379b0 100644 --- a/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Util/DirectAttributeContext.cs +++ b/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Util/DirectAttributeContext.cs @@ -22,10 +22,7 @@ public override IEnumerable GetCustomAttributes(Type reflectedType, R public override IEnumerable GetCustomAttributes(Type reflectedType, Reflection.ParameterInfo parameter) { - if (parameter is null) - { - throw new ArgumentNullException(nameof(parameter)); - } + ArgumentNullException.ThrowIfNull(parameter); if (reflectedType == null) throw new ArgumentNullException(nameof(reflectedType)); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/AppSettingsReader.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/AppSettingsReader.cs index 3123b43dc12380..2e4fbe3211bde1 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/AppSettingsReader.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/AppSettingsReader.cs @@ -30,14 +30,8 @@ public AppSettingsReader() /// public object GetValue(string key, Type type) { - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } - if (type is null) - { - throw new ArgumentNullException(nameof(type)); - } + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(type); string val = _map[key]; diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ApplicationSettingsBase.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ApplicationSettingsBase.cs index 112527d7bdddc4..8956757a223ba1 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ApplicationSettingsBase.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ApplicationSettingsBase.cs @@ -56,10 +56,7 @@ protected ApplicationSettingsBase(string settingsKey) /// protected ApplicationSettingsBase(IComponent owner, string settingsKey) : this(settingsKey) { - if (owner is null) - { - throw new ArgumentNullException(nameof(owner)); - } + ArgumentNullException.ThrowIfNull(owner); _owner = owner; diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/CallbackValidator.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/CallbackValidator.cs index d7ddeac8e3b84d..22f8650a8fe868 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/CallbackValidator.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/CallbackValidator.cs @@ -17,10 +17,7 @@ public CallbackValidator(Type type, ValidatorCallback callback) : this(callback) // Do not check for null type here to handle the callback attribute case internal CallbackValidator(ValidatorCallback callback) { - if (callback is null) - { - throw new ArgumentNullException(nameof(callback)); - } + ArgumentNullException.ThrowIfNull(callback); _type = null; _callback = callback; diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElementCollection.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElementCollection.cs index 20c95d501eb9f3..36fddb0cf249e3 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElementCollection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElementCollection.cs @@ -31,10 +31,7 @@ protected ConfigurationElementCollection() { } protected ConfigurationElementCollection(IComparer comparer) { - if (comparer is null) - { - throw new ArgumentNullException(nameof(comparer)); - } + ArgumentNullException.ThrowIfNull(comparer); _comparer = comparer; } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElementProperty.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElementProperty.cs index 51cf83f32819c4..e0b7e1b4d5761f 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElementProperty.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElementProperty.cs @@ -11,10 +11,7 @@ public sealed class ConfigurationElementProperty { public ConfigurationElementProperty(ConfigurationValidatorBase validator) { - if (validator is null) - { - throw new ArgumentNullException(nameof(validator)); - } + ArgumentNullException.ThrowIfNull(validator); Validator = validator; } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationSectionCollection.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationSectionCollection.cs index ef54b46ac03182..8429365e9a73fc 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationSectionCollection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationSectionCollection.cs @@ -63,10 +63,7 @@ public void Clear() public void CopyTo(ConfigurationSection[] array, int index) { - if (array is null) - { - throw new ArgumentNullException(nameof(array)); - } + ArgumentNullException.ThrowIfNull(array); int c = Count; if (array.Length < c + index) throw new ArgumentOutOfRangeException(nameof(index)); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationSectionGroupCollection.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationSectionGroupCollection.cs index 81210e851119e6..6d91085612b203 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationSectionGroupCollection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationSectionGroupCollection.cs @@ -67,10 +67,7 @@ public void Clear() public void CopyTo(ConfigurationSectionGroup[] array, int index) { - if (array is null) - { - throw new ArgumentNullException(nameof(array)); - } + ArgumentNullException.ThrowIfNull(array); int c = Count; if (array.Length < c + index) throw new ArgumentOutOfRangeException(nameof(index)); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PositiveTimeSpanValidator.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PositiveTimeSpanValidator.cs index 3af31a63f0e72d..6e840cc6bf94f5 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PositiveTimeSpanValidator.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PositiveTimeSpanValidator.cs @@ -12,10 +12,7 @@ public override bool CanValidate(Type type) public override void Validate(object value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); if ((TimeSpan)value <= TimeSpan.Zero) throw new ArgumentException(SR.Validator_timespan_value_must_be_positive); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PropertyInformationCollection.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PropertyInformationCollection.cs index b6bfc4bc0829a0..73f8e615e6d6bd 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PropertyInformationCollection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PropertyInformationCollection.cs @@ -41,10 +41,7 @@ public PropertyInformation this[string propertyName] public void CopyTo(PropertyInformation[] array, int index) { - if (array is null) - { - throw new ArgumentNullException(nameof(array)); - } + ArgumentNullException.ThrowIfNull(array); if (array.Length < Count + index) throw new ArgumentOutOfRangeException(nameof(index)); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProtectedConfigurationProviderCollection.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProtectedConfigurationProviderCollection.cs index 3db1a0602624f2..757bae6c65b6db 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProtectedConfigurationProviderCollection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProtectedConfigurationProviderCollection.cs @@ -11,10 +11,7 @@ public class ProtectedConfigurationProviderCollection : ProviderCollection public override void Add(ProviderBase provider) { - if (provider is null) - { - throw new ArgumentNullException(nameof(provider)); - } + ArgumentNullException.ThrowIfNull(provider); if (!(provider is ProtectedConfigurationProvider)) { diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsProviderCollection.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsProviderCollection.cs index 9cdf0d00fce722..61548282e0490e 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsProviderCollection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsProviderCollection.cs @@ -9,10 +9,7 @@ public class SettingsProviderCollection : ProviderCollection { public override void Add(ProviderBase provider) { - if (provider is null) - { - throw new ArgumentNullException(nameof(provider)); - } + ArgumentNullException.ThrowIfNull(provider); if (!(provider is SettingsProvider)) { diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Activity.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Activity.cs index e33938066d9d24..65274673caf8c5 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Activity.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Activity.cs @@ -551,10 +551,7 @@ public Activity AddEvent(ActivityEvent e) /// public Activity AddException(Exception exception, in TagList tags = default, DateTimeOffset timestamp = default) { - if (exception == null) - { - throw new ArgumentNullException(nameof(exception)); - } + ArgumentNullException.ThrowIfNull(exception); TagList exceptionTags = tags; diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityContext.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityContext.cs index da5f21f39f0f41..a5d12142fbcfe3 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityContext.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityContext.cs @@ -96,10 +96,7 @@ public static bool TryParse(string? traceParent, string? traceState, bool isRemo /// public static ActivityContext Parse(string traceParent, string? traceState) { - if (traceParent is null) - { - throw new ArgumentNullException(nameof(traceParent)); - } + ArgumentNullException.ThrowIfNull(traceParent); if (!Activity.TryConvertIdToContext(traceParent, traceState, isRemote: false, out ActivityContext context)) { diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivitySource.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivitySource.cs index 8a207ae838ac4c..8d8389cc2dd207 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivitySource.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivitySource.cs @@ -346,10 +346,7 @@ public void Dispose() /// The object to use for listening to the events. public static void AddActivityListener(ActivityListener listener) { - if (listener is null) - { - throw new ArgumentNullException(nameof(listener)); - } + ArgumentNullException.ThrowIfNull(listener); if (s_allListeners.AddIfNotExist(listener)) { diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityTagsCollection.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityTagsCollection.cs index a634a91880e445..998a66ec7c225a 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityTagsCollection.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityTagsCollection.cs @@ -36,10 +36,7 @@ public ActivityTagsCollection() /// Initial list to store in the collection. public ActivityTagsCollection(IEnumerable> list) { - if (list is null) - { - throw new ArgumentNullException(nameof(list)); - } + ArgumentNullException.ThrowIfNull(list); foreach (KeyValuePair kvp in list) { @@ -68,10 +65,7 @@ public object? this[string key] set { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); int index = FindIndex(key); if (value == null) @@ -144,10 +138,7 @@ public ICollection Values /// The tag value. public void Add(string key, object? value) { - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); int index = FindIndex(key); if (index >= 0) @@ -221,10 +212,7 @@ public void Add(KeyValuePair item) /// True if the item existed and removed. False otherwise. public bool Remove(string key) { - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); int index = FindIndex(key); if (index >= 0) diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/InstrumentAdvice.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/InstrumentAdvice.cs index b06a5e4012a5bd..f39657545c9afa 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/InstrumentAdvice.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/InstrumentAdvice.cs @@ -38,10 +38,7 @@ public IReadOnlyList? HistogramBucketBoundaries get => _HistogramBucketBoundaries; init { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); List bucketBoundariesCopy = new List(value); diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/Meter.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/Meter.cs index 762d90f425ebfb..ccacb53e5f8460 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/Meter.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/Meter.cs @@ -32,10 +32,7 @@ private static bool InitializeIsSupported() => /// public Meter(MeterOptions options) { - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); Debug.Assert(options.Name is not null); diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/MeterFactoryExtensions.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/MeterFactoryExtensions.cs index a82015bfd5e5be..1aa97f5e522022 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/MeterFactoryExtensions.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/MeterFactoryExtensions.cs @@ -21,10 +21,7 @@ public static class MeterFactoryExtensions /// A with the specified , , and . public static Meter Create(this IMeterFactory meterFactory, string name, string? version = null, IEnumerable>? tags = null) { - if (meterFactory is null) - { - throw new ArgumentNullException(nameof(meterFactory)); - } + ArgumentNullException.ThrowIfNull(meterFactory); return meterFactory.Create(new MeterOptions(name) { diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/TagList.netfx.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/TagList.netfx.cs index 4714348bd82a65..d446fa0648aa92 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/TagList.netfx.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/TagList.netfx.cs @@ -260,10 +260,7 @@ public readonly void CopyTo(Span> tags) /// is less than 0 or greater that or equal the length. public readonly void CopyTo(KeyValuePair[] array, int arrayIndex) { - if (array is null) - { - throw new ArgumentNullException(nameof(array)); - } + ArgumentNullException.ThrowIfNull(array); if ((uint)arrayIndex >= array.Length) { diff --git a/src/libraries/System.Diagnostics.EventLog/src/Messages/System.Diagnostics.EventLog.Messages.csproj b/src/libraries/System.Diagnostics.EventLog/src/Messages/System.Diagnostics.EventLog.Messages.csproj index 9285c392347b97..b5ca42ec6522b9 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/Messages/System.Diagnostics.EventLog.Messages.csproj +++ b/src/libraries/System.Diagnostics.EventLog/src/Messages/System.Diagnostics.EventLog.Messages.csproj @@ -6,5 +6,7 @@ false + true + true \ No newline at end of file diff --git a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceData/CounterSetInstanceCounterDataSet.cs b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceData/CounterSetInstanceCounterDataSet.cs index 55d3351386c8b3..a820b2cf9c02b3 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceData/CounterSetInstanceCounterDataSet.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceData/CounterSetInstanceCounterDataSet.cs @@ -225,10 +225,7 @@ public CounterData this[string counterName] { get { - if (counterName is null) - { - throw new ArgumentNullException(nameof(counterName)); - } + ArgumentNullException.ThrowIfNull(counterName); if (counterName.Length == 0) { diff --git a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryAttribute.cs b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryAttribute.cs index e0000b99c104bb..7dea8df33f06c4 100644 --- a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryAttribute.cs +++ b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryAttribute.cs @@ -141,11 +141,8 @@ public object this[int index] } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - else if (!(value is string) && !(value is byte[]) && !(value is Uri)) + ArgumentNullException.ThrowIfNull(value); + if (!(value is string) && !(value is byte[]) && !(value is Uri)) { throw new ArgumentException(SR.ValidValueType, nameof(value)); } @@ -255,10 +252,7 @@ public DirectoryAttribute this[string attributeName] { get { - if (attributeName == null) - { - throw new ArgumentNullException(nameof(attributeName)); - } + ArgumentNullException.ThrowIfNull(attributeName); object objectName = attributeName.ToLowerInvariant(); return (DirectoryAttribute)InnerHashtable[objectName]; diff --git a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryControl.cs b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryControl.cs index 25d455cb0ae5d2..89796775337691 100644 --- a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryControl.cs +++ b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryControl.cs @@ -845,10 +845,7 @@ public SortKey[] SortKeys } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); for (int i = 0; i < value.Length; i++) { diff --git a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.cs b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.cs index facdfc6a484bb9..4ad3ebc7082bb6 100644 --- a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.cs +++ b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.cs @@ -200,10 +200,7 @@ public DirectoryResponse SendRequest(DirectoryRequest request, TimeSpan requestT throw new ObjectDisposedException(GetType().Name); } - if (request == null) - { - throw new ArgumentNullException(nameof(request)); - } + ArgumentNullException.ThrowIfNull(request); if (request is DsmlAuthRequest) { @@ -273,10 +270,7 @@ public IAsyncResult BeginSendRequest(DirectoryRequest request, TimeSpan requestT throw new ObjectDisposedException(GetType().Name); } - if (request == null) - { - throw new ArgumentNullException(nameof(request)); - } + ArgumentNullException.ThrowIfNull(request); if (partialMode < PartialResultProcessing.NoPartialResultSupport || partialMode > PartialResultProcessing.ReturnPartialResultsAndNotifyCallback) { @@ -393,10 +387,7 @@ public void Abort(IAsyncResult asyncResult) throw new ObjectDisposedException(GetType().Name); } - if (asyncResult == null) - { - throw new ArgumentNullException(nameof(asyncResult)); - } + ArgumentNullException.ThrowIfNull(asyncResult); if (!(asyncResult is LdapAsyncResult)) { @@ -441,10 +432,7 @@ public PartialResultsCollection GetPartialResults(IAsyncResult asyncResult) throw new ObjectDisposedException(GetType().Name); } - if (asyncResult == null) - { - throw new ArgumentNullException(nameof(asyncResult)); - } + ArgumentNullException.ThrowIfNull(asyncResult); if (!(asyncResult is LdapAsyncResult)) { @@ -466,10 +454,7 @@ public DirectoryResponse EndSendRequest(IAsyncResult asyncResult) throw new ObjectDisposedException(GetType().Name); } - if (asyncResult == null) - { - throw new ArgumentNullException(nameof(asyncResult)); - } + ArgumentNullException.ThrowIfNull(asyncResult); if (!(asyncResult is LdapAsyncResult)) { diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ADAMInstance.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ADAMInstance.cs index f7932b6517dc7e..9fd4254442c780 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ADAMInstance.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ADAMInstance.cs @@ -114,10 +114,7 @@ public static AdamInstance GetAdamInstance(DirectoryContext context) string? dnsHostName = null; // check that the context is not null - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); // contexttype should be DirectoryServer if (context.ContextType != DirectoryContextType.DirectoryServer) @@ -167,10 +164,7 @@ public static AdamInstance GetAdamInstance(DirectoryContext context) public static AdamInstance FindOne(DirectoryContext context, string partitionName) { // validate parameters (partitionName validated by the call to ConfigSet) - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); // contexttype should be ConfigurationSet if (context.ContextType != DirectoryContextType.ConfigurationSet) @@ -178,10 +172,7 @@ public static AdamInstance FindOne(DirectoryContext context, string partitionNam throw new ArgumentException(SR.TargetShouldBeConfigSet, nameof(context)); } - if (partitionName == null) - { - throw new ArgumentNullException(nameof(partitionName)); - } + ArgumentNullException.ThrowIfNull(partitionName); if (partitionName.Length == 0) { @@ -199,10 +190,7 @@ public static AdamInstanceCollection FindAll(DirectoryContext context, string pa AdamInstanceCollection? adamInstanceCollection = null; // validate parameters (partitionName validated by the call to ConfigSet) - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); // contexttype should be ConfigurationSet if (context.ContextType != DirectoryContextType.ConfigurationSet) @@ -210,10 +198,7 @@ public static AdamInstanceCollection FindAll(DirectoryContext context, string pa throw new ArgumentException(SR.TargetShouldBeConfigSet, nameof(context)); } - if (partitionName == null) - { - throw new ArgumentNullException(nameof(partitionName)); - } + ArgumentNullException.ThrowIfNull(partitionName); if (partitionName.Length == 0) { diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ADAMInstanceCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ADAMInstanceCollection.cs index df597ac28eaf69..e9b93ec8bb1723 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ADAMInstanceCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ADAMInstanceCollection.cs @@ -21,10 +21,7 @@ internal AdamInstanceCollection(ArrayList values) public bool Contains(AdamInstance adamInstance) { - if (adamInstance == null) - { - throw new ArgumentNullException(nameof(adamInstance)); - } + ArgumentNullException.ThrowIfNull(adamInstance); for (int i = 0; i < InnerList.Count; i++) { @@ -39,10 +36,7 @@ public bool Contains(AdamInstance adamInstance) public int IndexOf(AdamInstance adamInstance) { - if (adamInstance == null) - { - throw new ArgumentNullException(nameof(adamInstance)); - } + ArgumentNullException.ThrowIfNull(adamInstance); for (int i = 0; i < InnerList.Count; i++) { diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchema.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchema.cs index 91e64708f305ef..5e8ffe4989613d 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchema.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchema.cs @@ -218,10 +218,7 @@ public ActiveDirectorySchemaClass FindDefunctClass(string commonName) { CheckIfDisposed(); - if (commonName == null) - { - throw new ArgumentNullException(nameof(commonName)); - } + ArgumentNullException.ThrowIfNull(commonName); if (commonName.Length == 0) { @@ -294,10 +291,7 @@ public ActiveDirectorySchemaProperty FindDefunctProperty(string commonName) { CheckIfDisposed(); - if (commonName == null) - { - throw new ArgumentNullException(nameof(commonName)); - } + ArgumentNullException.ThrowIfNull(commonName); if (commonName.Length == 0) { diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClass.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClass.cs index baa3c301fa5c9b..e4fc2ba312cf9f 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClass.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClass.cs @@ -64,10 +64,7 @@ public ActiveDirectorySchemaClass(DirectoryContext context, string ldapDisplayNa } } - if (ldapDisplayName == null) - { - throw new ArgumentNullException(nameof(ldapDisplayName)); - } + ArgumentNullException.ThrowIfNull(ldapDisplayName); if (ldapDisplayName.Length == 0) { @@ -236,10 +233,7 @@ public static ActiveDirectorySchemaClass FindByName(DirectoryContext context, st } } - if (ldapDisplayName == null) - { - throw new ArgumentNullException(nameof(ldapDisplayName)); - } + ArgumentNullException.ThrowIfNull(ldapDisplayName); if (ldapDisplayName.Length == 0) { 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 6c0ad17ba9951c..92504917d598a4 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClassCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClassCollection.cs @@ -56,10 +56,7 @@ public ActiveDirectorySchemaClass this[int index] get => (ActiveDirectorySchemaClass)List[index]!; set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); if (!value.isBound) { diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ApplicationPartition.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ApplicationPartition.cs index 297fdf984f1875..1a2b8a49177efe 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ApplicationPartition.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ApplicationPartition.cs @@ -107,10 +107,7 @@ protected override void Dispose(bool disposing) public static ApplicationPartition GetApplicationPartition(DirectoryContext context) { // validate the context - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); // contexttype should be ApplicationPartiton if (context.ContextType != DirectoryContextType.ApplicationPartition) @@ -376,10 +373,7 @@ public DirectoryServer FindDirectoryServer(string siteName) CheckIfDisposed(); - if (siteName == null) - { - throw new ArgumentNullException(nameof(siteName)); - } + ArgumentNullException.ThrowIfNull(siteName); if (_appType == ApplicationPartitionType.ADApplicationPartition) { @@ -430,10 +424,7 @@ public DirectoryServer FindDirectoryServer(string siteName, bool forceRediscover CheckIfDisposed(); - if (siteName == null) - { - throw new ArgumentNullException(nameof(siteName)); - } + ArgumentNullException.ThrowIfNull(siteName); if (_appType == ApplicationPartitionType.ADApplicationPartition) { @@ -481,10 +472,7 @@ public ReadOnlyDirectoryServerCollection FindAllDirectoryServers(string siteName { CheckIfDisposed(); - if (siteName == null) - { - throw new ArgumentNullException(nameof(siteName)); - } + ArgumentNullException.ThrowIfNull(siteName); if (_appType == ApplicationPartitionType.ADApplicationPartition) { @@ -527,10 +515,7 @@ public ReadOnlyDirectoryServerCollection FindAllDiscoverableDirectoryServers(str { CheckIfDisposed(); - if (siteName == null) - { - throw new ArgumentNullException(nameof(siteName)); - } + ArgumentNullException.ThrowIfNull(siteName); if (_appType == ApplicationPartitionType.ADApplicationPartition) { @@ -864,10 +849,7 @@ public string? SecurityReferenceDomain private void ValidateApplicationPartitionParameters(DirectoryContext context, string distinguishedName, string? objectClass, bool objectClassSpecified) { // validate context - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); // contexttype should be DirectoryServer if ((context.Name == null) || (!context.isServer())) @@ -876,10 +858,7 @@ private void ValidateApplicationPartitionParameters(DirectoryContext context, st } // check that the distinguished name is not null or empty - if (distinguishedName == null) - { - throw new ArgumentNullException(nameof(distinguishedName)); - } + ArgumentNullException.ThrowIfNull(distinguishedName); if (distinguishedName.Length == 0) { @@ -914,10 +893,7 @@ private void ValidateApplicationPartitionParameters(DirectoryContext context, st { // ADAM case and objectClass is explicitly specified, so must be validated - if (objectClass == null) - { - throw new ArgumentNullException(nameof(objectClass)); - } + ArgumentNullException.ThrowIfNull(objectClass); if (objectClass.Length == 0) { diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ApplicationPartitionCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ApplicationPartitionCollection.cs index 9ce65000e71092..e5a9b23a1d9e95 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ApplicationPartitionCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ApplicationPartitionCollection.cs @@ -21,10 +21,7 @@ internal ApplicationPartitionCollection(ArrayList values) public bool Contains(ApplicationPartition applicationPartition) { - if (applicationPartition == null) - { - throw new ArgumentNullException(nameof(applicationPartition)); - } + ArgumentNullException.ThrowIfNull(applicationPartition); for (int i = 0; i < InnerList.Count; i++) { @@ -39,10 +36,7 @@ public bool Contains(ApplicationPartition applicationPartition) public int IndexOf(ApplicationPartition applicationPartition) { - if (applicationPartition == null) - { - throw new ArgumentNullException(nameof(applicationPartition)); - } + ArgumentNullException.ThrowIfNull(applicationPartition); for (int i = 0; i < InnerList.Count; i++) { diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ConfigSet.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ConfigSet.cs index 9bdde3e93afccf..e4a2c0de171a0c 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ConfigSet.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ConfigSet.cs @@ -161,10 +161,7 @@ public AdamInstance FindAdamInstance(string partitionName) { CheckIfDisposed(); - if (partitionName == null) - { - throw new ArgumentNullException(nameof(partitionName)); - } + ArgumentNullException.ThrowIfNull(partitionName); return FindOneAdamInstance(Name, _context, partitionName, null); } @@ -177,10 +174,7 @@ public AdamInstance FindAdamInstance(string? partitionName, string siteName) // null partitionName would signify that we don't care about the partition // - if (siteName == null) - { - throw new ArgumentNullException(nameof(siteName)); - } + ArgumentNullException.ThrowIfNull(siteName); return FindOneAdamInstance(Name, _context, partitionName, siteName); } @@ -196,10 +190,7 @@ public AdamInstanceCollection FindAllAdamInstances(string partitionName) { CheckIfDisposed(); - if (partitionName == null) - { - throw new ArgumentNullException(nameof(partitionName)); - } + ArgumentNullException.ThrowIfNull(partitionName); return FindAdamInstances(_context, partitionName, null); } @@ -212,10 +203,7 @@ public AdamInstanceCollection FindAllAdamInstances(string? partitionName, string // null partitionName would signify that we don't care about the partition // - if (siteName == null) - { - throw new ArgumentNullException(nameof(siteName)); - } + ArgumentNullException.ThrowIfNull(siteName); return FindAdamInstances(_context, partitionName, siteName); } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryContext.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryContext.cs index a435ab972655f0..2594613b528782 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryContext.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryContext.cs @@ -121,10 +121,7 @@ public DirectoryContext(DirectoryContextType contextType, string name) throw new InvalidEnumArgumentException(nameof(contextType), (int)contextType, typeof(DirectoryContextType)); } - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); if (name.Length == 0) { @@ -155,10 +152,7 @@ public DirectoryContext(DirectoryContextType contextType, string name, string? u throw new InvalidEnumArgumentException(nameof(contextType), (int)contextType, typeof(DirectoryContextType)); } - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); if (name.Length == 0) { diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServer.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServer.cs index 4d7862649788d8..6fcd05b49a38b4 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServer.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServer.cs @@ -78,10 +78,7 @@ public void MoveToAnotherSite(string siteName) CheckIfDisposed(); // validate siteName - if (siteName == null) - { - throw new ArgumentNullException(nameof(siteName)); - } + ArgumentNullException.ThrowIfNull(siteName); if (siteName.Length == 0) { diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Domain.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Domain.cs index a1361f735533ae..5c0b5a5a98f6af 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Domain.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Domain.cs @@ -418,10 +418,7 @@ public DomainController FindDomainController(string siteName) { CheckIfDisposed(); - if (siteName == null) - { - throw new ArgumentNullException(nameof(siteName)); - } + ArgumentNullException.ThrowIfNull(siteName); return DomainController.FindOneInternal(context, Name, siteName, 0); } @@ -437,10 +434,7 @@ public DomainController FindDomainController(string siteName, LocatorOptions fla { CheckIfDisposed(); - if (siteName == null) - { - throw new ArgumentNullException(nameof(siteName)); - } + ArgumentNullException.ThrowIfNull(siteName); return DomainController.FindOneInternal(context, Name, siteName, flag); } @@ -456,10 +450,7 @@ public DomainControllerCollection FindAllDomainControllers(string siteName) { CheckIfDisposed(); - if (siteName == null) - { - throw new ArgumentNullException(nameof(siteName)); - } + ArgumentNullException.ThrowIfNull(siteName); return DomainController.FindAllInternal(context, Name, true /*isDnsDomainName */, siteName); } @@ -478,10 +469,7 @@ public DomainControllerCollection FindAllDiscoverableDomainControllers(string si CheckIfDisposed(); - if (siteName == null) - { - throw new ArgumentNullException(nameof(siteName)); - } + ArgumentNullException.ThrowIfNull(siteName); if (siteName.Length == 0) { diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainController.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainController.cs index 9f6ce24172ef6f..dde7d780466fe2 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainController.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainController.cs @@ -173,10 +173,7 @@ public static DomainController GetDomainController(DirectoryContext context) public static DomainController FindOne(DirectoryContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (context.ContextType != DirectoryContextType.Domain) { @@ -188,30 +185,21 @@ public static DomainController FindOne(DirectoryContext context) public static DomainController FindOne(DirectoryContext context, string siteName) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (context.ContextType != DirectoryContextType.Domain) { throw new ArgumentException(SR.TargetShouldBeDomain, nameof(context)); } - if (siteName == null) - { - throw new ArgumentNullException(nameof(siteName)); - } + ArgumentNullException.ThrowIfNull(siteName); return FindOneWithCredentialValidation(context, siteName, 0); } public static DomainController FindOne(DirectoryContext context, LocatorOptions flag) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (context.ContextType != DirectoryContextType.Domain) { @@ -223,30 +211,21 @@ public static DomainController FindOne(DirectoryContext context, LocatorOptions public static DomainController FindOne(DirectoryContext context, string siteName, LocatorOptions flag) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (context.ContextType != DirectoryContextType.Domain) { throw new ArgumentException(SR.TargetShouldBeDomain, nameof(context)); } - if (siteName == null) - { - throw new ArgumentNullException(nameof(siteName)); - } + ArgumentNullException.ThrowIfNull(siteName); return FindOneWithCredentialValidation(context, siteName, flag); } public static DomainControllerCollection FindAll(DirectoryContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (context.ContextType != DirectoryContextType.Domain) { @@ -261,20 +240,14 @@ public static DomainControllerCollection FindAll(DirectoryContext context) public static DomainControllerCollection FindAll(DirectoryContext context, string siteName) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (context.ContextType != DirectoryContextType.Domain) { throw new ArgumentException(SR.TargetShouldBeDomain, nameof(context)); } - if (siteName == null) - { - throw new ArgumentNullException(nameof(siteName)); - } + ArgumentNullException.ThrowIfNull(siteName); // work with copy of the context context = new DirectoryContext(context); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Forest.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Forest.cs index 8f93b36ca960c7..645b9ca45a608c 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Forest.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Forest.cs @@ -239,10 +239,7 @@ public GlobalCatalog FindGlobalCatalog(string siteName) { CheckIfDisposed(); - if (siteName == null) - { - throw new ArgumentNullException(nameof(siteName)); - } + ArgumentNullException.ThrowIfNull(siteName); return GlobalCatalog.FindOneInternal(_context, Name, siteName, 0); } @@ -258,10 +255,7 @@ public GlobalCatalog FindGlobalCatalog(string siteName, LocatorOptions flag) { CheckIfDisposed(); - if (siteName == null) - { - throw new ArgumentNullException(nameof(siteName)); - } + ArgumentNullException.ThrowIfNull(siteName); return GlobalCatalog.FindOneInternal(_context, Name, siteName, flag); } @@ -277,10 +271,7 @@ public GlobalCatalogCollection FindAllGlobalCatalogs(string siteName) { CheckIfDisposed(); - if (siteName == null) - { - throw new ArgumentNullException(nameof(siteName)); - } + ArgumentNullException.ThrowIfNull(siteName); return GlobalCatalog.FindAllInternal(_context, siteName); } @@ -299,10 +290,7 @@ public GlobalCatalogCollection FindAllDiscoverableGlobalCatalogs(string siteName CheckIfDisposed(); - if (siteName == null) - { - throw new ArgumentNullException(nameof(siteName)); - } + ArgumentNullException.ThrowIfNull(siteName); if (siteName.Length == 0) { diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/GlobalCatalog.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/GlobalCatalog.cs index 65d196593b7999..6fd21363fc4b90 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/GlobalCatalog.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/GlobalCatalog.cs @@ -88,10 +88,7 @@ public static GlobalCatalog GetGlobalCatalog(DirectoryContext context) public static new GlobalCatalog FindOne(DirectoryContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (context.ContextType != DirectoryContextType.Forest) { @@ -103,30 +100,21 @@ public static GlobalCatalog GetGlobalCatalog(DirectoryContext context) public static new GlobalCatalog FindOne(DirectoryContext context, string siteName) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (context.ContextType != DirectoryContextType.Forest) { throw new ArgumentException(SR.TargetShouldBeForest, nameof(context)); } - if (siteName == null) - { - throw new ArgumentNullException(nameof(siteName)); - } + ArgumentNullException.ThrowIfNull(siteName); return FindOneWithCredentialValidation(context, siteName, 0); } public static new GlobalCatalog FindOne(DirectoryContext context, LocatorOptions flag) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (context.ContextType != DirectoryContextType.Forest) { @@ -138,30 +126,21 @@ public static GlobalCatalog GetGlobalCatalog(DirectoryContext context) public static new GlobalCatalog FindOne(DirectoryContext context, string siteName, LocatorOptions flag) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (context.ContextType != DirectoryContextType.Forest) { throw new ArgumentException(SR.TargetShouldBeForest, nameof(context)); } - if (siteName == null) - { - throw new ArgumentNullException(nameof(siteName)); - } + ArgumentNullException.ThrowIfNull(siteName); return FindOneWithCredentialValidation(context, siteName, flag); } public static new GlobalCatalogCollection FindAll(DirectoryContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (context.ContextType != DirectoryContextType.Forest) { @@ -176,20 +155,14 @@ public static GlobalCatalog GetGlobalCatalog(DirectoryContext context) public static new GlobalCatalogCollection FindAll(DirectoryContext context, string siteName) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (context.ContextType != DirectoryContextType.Forest) { throw new ArgumentException(SR.TargetShouldBeForest, nameof(context)); } - if (siteName == null) - { - throw new ArgumentNullException(nameof(siteName)); - } + ArgumentNullException.ThrowIfNull(siteName); // work with copy of the context context = new DirectoryContext(context); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyStringCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyStringCollection.cs index 01c3958808e916..afe54c0ed7ad5b 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyStringCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyStringCollection.cs @@ -28,10 +28,7 @@ public string this[int index] public bool Contains(string value) { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); for (int i = 0; i < InnerList.Count; i++) { @@ -46,10 +43,7 @@ public bool Contains(string value) public int IndexOf(string value) { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); for (int i = 0; i < InnerList.Count; i++) { diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs index c26c7b3af38b18..ac1263bc439592 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs @@ -1876,27 +1876,15 @@ internal static int Compare(string? s1, string? s2) internal static int Compare(string s1, int offset1, int length1, string s2, int offset2, int length2) { - if (s1 == null) - { - throw new ArgumentNullException(nameof(s1)); - } - if (s2 == null) - { - throw new ArgumentNullException(nameof(s2)); - } + ArgumentNullException.ThrowIfNull(s1); + ArgumentNullException.ThrowIfNull(s2); return Compare(s1.Substring(offset1, length1), s2.Substring(offset2, length2)); } internal static int Compare(string s1, int offset1, int length1, string s2, int offset2, int length2, uint compareFlags) { - if (s1 == null) - { - throw new ArgumentNullException(nameof(s1)); - } - if (s2 == null) - { - throw new ArgumentNullException(nameof(s2)); - } + ArgumentNullException.ThrowIfNull(s1); + ArgumentNullException.ThrowIfNull(s2); return Compare(s1.Substring(offset1, length1), s2.Substring(offset2, length2), compareFlags); } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntry.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntry.cs index 0da317c9d72ab2..fa6c179b083ffb 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntry.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntry.cs @@ -227,10 +227,7 @@ public ActiveDirectorySecurity ObjectSecurity } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _objectSecurity = value; _objectSecurityInitialized = true; diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/PropertyValueCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/PropertyValueCollection.cs index 6a23f61fb07bd2..99fd009c3c0637 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/PropertyValueCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/PropertyValueCollection.cs @@ -136,10 +136,7 @@ public object? Value /// public void AddRange(object?[] value) { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); for (int i = 0; ((i) < (value.Length)); i = ((i) + (1))) { this.Add(value[i]); @@ -151,10 +148,7 @@ public void AddRange(object?[] value) /// public void AddRange(PropertyValueCollection value) { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); int currentCount = value.Count; for (int i = 0; i < currentCount; i = ((i) + (1))) { diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/SchemaNameCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/SchemaNameCollection.cs index 7acb9bf62334e7..c541c8c0aeb98c 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/SchemaNameCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/SchemaNameCollection.cs @@ -68,10 +68,7 @@ public int Add(string? value) /// public void AddRange(string?[] value) { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); object?[] oldValues = GetValue(); object?[] newValues = new object[oldValues.Length + value.Length]; for (int i = 0; i < oldValues.Length; i++) @@ -83,10 +80,7 @@ public void AddRange(string?[] value) public void AddRange(SchemaNameCollection value) { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); object?[] oldValues = GetValue(); object?[] newValues = new object?[oldValues.Length + value.Count]; for (int i = 0; i < oldValues.Length; i++) diff --git a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.Enumerated.cs b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.Enumerated.cs index 230375dc544d23..a6b511e8d9d0dd 100644 --- a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.Enumerated.cs +++ b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.Enumerated.cs @@ -32,10 +32,7 @@ public sealed partial class AsnWriter /// public void WriteEnumeratedValue(Enum value, Asn1Tag? tag = null) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); WriteEnumeratedValue(tag?.AsPrimitive() ?? Asn1Tag.Enumerated, value.GetType(), value); } diff --git a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.NamedBitList.cs b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.NamedBitList.cs index 533e31a7e6939b..9dbe389f5d1df5 100644 --- a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.NamedBitList.cs +++ b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.NamedBitList.cs @@ -34,10 +34,7 @@ public sealed partial class AsnWriter /// public void WriteNamedBitList(Enum value, Asn1Tag? tag = null) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); CheckUniversalTag(tag, UniversalTagNumber.BitString); @@ -96,10 +93,7 @@ public void WriteNamedBitList(TEnum value, Asn1Tag? tag = null) where TEn /// public void WriteNamedBitList(BitArray value, Asn1Tag? tag = null) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); CheckUniversalTag(tag, UniversalTagNumber.BitString); diff --git a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.Oid.cs b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.Oid.cs index 04a063a11fdc31..f682fad19bff0a 100644 --- a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.Oid.cs +++ b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.Oid.cs @@ -31,10 +31,7 @@ public sealed partial class AsnWriter /// public void WriteObjectIdentifier(string oidValue, Asn1Tag? tag = null) { - if (oidValue is null) - { - throw new ArgumentNullException(nameof(oidValue)); - } + ArgumentNullException.ThrowIfNull(oidValue); WriteObjectIdentifier(oidValue.AsSpan(), tag); } diff --git a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.Text.cs b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.Text.cs index 1330e0c1c7fd52..950318d30c578d 100644 --- a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.Text.cs +++ b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.Text.cs @@ -38,10 +38,7 @@ public sealed partial class AsnWriter /// public void WriteCharacterString(UniversalTagNumber encodingType, string value, Asn1Tag? tag = null) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); WriteCharacterString(encodingType, value.AsSpan(), tag); } diff --git a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.cs b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.cs index bc163a324c46c2..0de9d49f4ff9b1 100644 --- a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.cs +++ b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.cs @@ -231,8 +231,7 @@ public byte[] Encode() /// public TReturn Encode(Func, TReturn> encodeCallback) { - if (encodeCallback is null) - throw new ArgumentNullException(nameof(encodeCallback)); + ArgumentNullException.ThrowIfNull(encodeCallback); _encodeDepth = checked(_encodeDepth + 1); @@ -275,8 +274,7 @@ public TReturn Encode(Func, TReturn> encodeCallback) public TReturn Encode(TState state, Func, TReturn> encodeCallback) where TState : allows ref struct { - if (encodeCallback is null) - throw new ArgumentNullException(nameof(encodeCallback)); + ArgumentNullException.ThrowIfNull(encodeCallback); _encodeDepth = checked(_encodeDepth + 1); @@ -313,8 +311,7 @@ public TReturn Encode(TState state, Func(TState state, Action> encodeCallback) where TState : allows ref struct { - if (encodeCallback is null) - throw new ArgumentNullException(nameof(encodeCallback)); + ArgumentNullException.ThrowIfNull(encodeCallback); _encodeDepth = checked(_encodeDepth + 1); @@ -381,10 +378,7 @@ public bool EncodedValueEquals(ReadOnlySpan other) /// public bool EncodedValueEquals(AsnWriter other) { - if (other is null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); return EncodeAsSpan().SequenceEqual(other.EncodeAsSpan()); } @@ -545,10 +539,7 @@ private static int GetEncodedLengthSubsequentByteCount(int length) /// public void CopyTo(AsnWriter destination) { - if (destination is null) - { - throw new ArgumentNullException(nameof(destination)); - } + ArgumentNullException.ThrowIfNull(destination); try { diff --git a/src/libraries/System.Formats.Cbor/src/System/Formats/Cbor/Writer/CborWriter.String.cs b/src/libraries/System.Formats.Cbor/src/System/Formats/Cbor/Writer/CborWriter.String.cs index 426bfa2a8802e6..880b6e1706090b 100644 --- a/src/libraries/System.Formats.Cbor/src/System/Formats/Cbor/Writer/CborWriter.String.cs +++ b/src/libraries/System.Formats.Cbor/src/System/Formats/Cbor/Writer/CborWriter.String.cs @@ -24,10 +24,7 @@ public partial class CborWriter /// The written data is not accepted under the current conformance mode. public void WriteByteString(byte[] value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); WriteByteString(value.AsSpan()); } @@ -108,10 +105,7 @@ public void WriteEndIndefiniteLengthByteString() /// The written data is not accepted under the current conformance mode. public void WriteTextString(string value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); WriteTextString(value.AsSpan()); } diff --git a/src/libraries/System.Formats.Nrbf/src/System/Formats/Nrbf/ArrayRecord.cs b/src/libraries/System.Formats.Nrbf/src/System/Formats/Nrbf/ArrayRecord.cs index 040378d33b4fc5..4fe6fb1e0942b4 100644 --- a/src/libraries/System.Formats.Nrbf/src/System/Formats/Nrbf/ArrayRecord.cs +++ b/src/libraries/System.Formats.Nrbf/src/System/Formats/Nrbf/ArrayRecord.cs @@ -71,14 +71,8 @@ internal bool IsJagged [RequiresDynamicCode("The code for an array of the specified type might not be available.")] public Array GetArray(Type expectedArrayType, bool allowNulls = true) { -#if NET ArgumentNullException.ThrowIfNull(expectedArrayType); -#else - if (expectedArrayType is null) - { - throw new ArgumentNullException(nameof(expectedArrayType)); - } -#endif + if (!TypeNameMatches(expectedArrayType)) { throw new InvalidOperationException(SR.Format(SR.Serialization_TypeMismatch, expectedArrayType.AssemblyQualifiedName, TypeName.AssemblyQualifiedName)); diff --git a/src/libraries/System.Formats.Nrbf/src/System/Formats/Nrbf/NrbfDecoder.cs b/src/libraries/System.Formats.Nrbf/src/System/Formats/Nrbf/NrbfDecoder.cs index d3fbe95aded07a..64e99b59f6920e 100644 --- a/src/libraries/System.Formats.Nrbf/src/System/Formats/Nrbf/NrbfDecoder.cs +++ b/src/libraries/System.Formats.Nrbf/src/System/Formats/Nrbf/NrbfDecoder.cs @@ -55,14 +55,8 @@ public static bool StartsWithPayloadHeader(ReadOnlySpan bytes) /// When this method returns, is restored to its original position. public static bool StartsWithPayloadHeader(Stream stream) { -#if NET ArgumentNullException.ThrowIfNull(stream); -#else - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } -#endif + if (!stream.CanSeek) { throw new ArgumentException(SR.Argument_NonSeekableStream, nameof(stream)); @@ -133,14 +127,7 @@ public static SerializationRecord Decode(Stream payload, PayloadOptions? options /// public static SerializationRecord Decode(Stream payload, out IReadOnlyDictionary recordMap, PayloadOptions? options = default, bool leaveOpen = false) { -#if NET ArgumentNullException.ThrowIfNull(payload); -#else - if (payload is null) - { - throw new ArgumentNullException(nameof(payload)); - } -#endif using BinaryReader reader = new(payload, ThrowOnInvalidUtf8Encoding, leaveOpen: leaveOpen); try diff --git a/src/libraries/System.Formats.Nrbf/src/System/Formats/Nrbf/SerializationRecord.cs b/src/libraries/System.Formats.Nrbf/src/System/Formats/Nrbf/SerializationRecord.cs index 30830cd84eab04..d0a6bfd7e65921 100644 --- a/src/libraries/System.Formats.Nrbf/src/System/Formats/Nrbf/SerializationRecord.cs +++ b/src/libraries/System.Formats.Nrbf/src/System/Formats/Nrbf/SerializationRecord.cs @@ -55,14 +55,7 @@ internal SerializationRecord() // others can't derive from this type /// is . public bool TypeNameMatches(Type type) { -#if NET ArgumentNullException.ThrowIfNull(type); -#else - if (type is null) - { - throw new ArgumentNullException(nameof(type)); - } -#endif return Matches(type, TypeName); } diff --git a/src/libraries/System.IO.Hashing/src/System/IO/Hashing/Crc32.cs b/src/libraries/System.IO.Hashing/src/System/IO/Hashing/Crc32.cs index 86cedbab894ece..95dda7501518a1 100644 --- a/src/libraries/System.IO.Hashing/src/System/IO/Hashing/Crc32.cs +++ b/src/libraries/System.IO.Hashing/src/System/IO/Hashing/Crc32.cs @@ -103,10 +103,7 @@ protected override void GetHashAndResetCore(Span destination) /// public static byte[] Hash(byte[] source) { - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } + ArgumentNullException.ThrowIfNull(source); return Hash(new ReadOnlySpan(source)); } diff --git a/src/libraries/System.IO.Hashing/src/System/IO/Hashing/Crc64.cs b/src/libraries/System.IO.Hashing/src/System/IO/Hashing/Crc64.cs index 690037ca05fb33..9de2a30a752b6e 100644 --- a/src/libraries/System.IO.Hashing/src/System/IO/Hashing/Crc64.cs +++ b/src/libraries/System.IO.Hashing/src/System/IO/Hashing/Crc64.cs @@ -101,10 +101,7 @@ protected override void GetHashAndResetCore(Span destination) /// public static byte[] Hash(byte[] source) { - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } + ArgumentNullException.ThrowIfNull(source); return Hash(new ReadOnlySpan(source)); } diff --git a/src/libraries/System.IO.Hashing/src/System/IO/Hashing/NonCryptographicHashAlgorithm.cs b/src/libraries/System.IO.Hashing/src/System/IO/Hashing/NonCryptographicHashAlgorithm.cs index 4448f67927ef83..c9b9b0a6ba864a 100644 --- a/src/libraries/System.IO.Hashing/src/System/IO/Hashing/NonCryptographicHashAlgorithm.cs +++ b/src/libraries/System.IO.Hashing/src/System/IO/Hashing/NonCryptographicHashAlgorithm.cs @@ -84,10 +84,7 @@ protected NonCryptographicHashAlgorithm(int hashLengthInBytes) /// public void Append(byte[] source) { - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } + ArgumentNullException.ThrowIfNull(source); Append(new ReadOnlySpan(source)); } @@ -103,10 +100,7 @@ public void Append(byte[] source) /// public void Append(Stream stream) { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } + ArgumentNullException.ThrowIfNull(stream); stream.CopyTo(new CopyToDestinationStream(this)); } @@ -129,10 +123,7 @@ public void Append(Stream stream) /// public Task AppendAsync(Stream stream, CancellationToken cancellationToken = default) { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } + ArgumentNullException.ThrowIfNull(stream); return stream.CopyToAsync( new CopyToDestinationStream(this), diff --git a/src/libraries/System.IO.Hashing/src/System/IO/Hashing/XxHash128.cs b/src/libraries/System.IO.Hashing/src/System/IO/Hashing/XxHash128.cs index 8cd30b57e7f51e..23ff9fce02a671 100644 --- a/src/libraries/System.IO.Hashing/src/System/IO/Hashing/XxHash128.cs +++ b/src/libraries/System.IO.Hashing/src/System/IO/Hashing/XxHash128.cs @@ -61,14 +61,7 @@ private XxHash128(State state) : base(HashLengthInBytes) /// is null. public static byte[] Hash(byte[] source, long seed) { -#if NET ArgumentNullException.ThrowIfNull(source); -#else - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } -#endif return Hash(new ReadOnlySpan(source), seed); } diff --git a/src/libraries/System.IO.Hashing/src/System/IO/Hashing/XxHash3.cs b/src/libraries/System.IO.Hashing/src/System/IO/Hashing/XxHash3.cs index ee2073a52c06b6..c7985efc0e66b7 100644 --- a/src/libraries/System.IO.Hashing/src/System/IO/Hashing/XxHash3.cs +++ b/src/libraries/System.IO.Hashing/src/System/IO/Hashing/XxHash3.cs @@ -60,14 +60,7 @@ private XxHash3(State state) : base(HashLengthInBytes) /// is null. public static byte[] Hash(byte[] source, long seed) { -#if NET ArgumentNullException.ThrowIfNull(source); -#else - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } -#endif return Hash(new ReadOnlySpan(source), seed); } diff --git a/src/libraries/System.IO.Hashing/src/System/IO/Hashing/XxHash32.cs b/src/libraries/System.IO.Hashing/src/System/IO/Hashing/XxHash32.cs index 6f93bc56a7e17c..ea941c69909a49 100644 --- a/src/libraries/System.IO.Hashing/src/System/IO/Hashing/XxHash32.cs +++ b/src/libraries/System.IO.Hashing/src/System/IO/Hashing/XxHash32.cs @@ -161,10 +161,7 @@ public uint GetCurrentHashAsUInt32() /// public static byte[] Hash(byte[] source) { - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } + ArgumentNullException.ThrowIfNull(source); return Hash(new ReadOnlySpan(source)); } @@ -180,10 +177,7 @@ public static byte[] Hash(byte[] source) /// public static byte[] Hash(byte[] source, int seed) { - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } + ArgumentNullException.ThrowIfNull(source); return Hash(new ReadOnlySpan(source), seed); } diff --git a/src/libraries/System.IO.Hashing/src/System/IO/Hashing/XxHash64.cs b/src/libraries/System.IO.Hashing/src/System/IO/Hashing/XxHash64.cs index fa88682ed34e82..dd933918f64fd4 100644 --- a/src/libraries/System.IO.Hashing/src/System/IO/Hashing/XxHash64.cs +++ b/src/libraries/System.IO.Hashing/src/System/IO/Hashing/XxHash64.cs @@ -161,10 +161,7 @@ public ulong GetCurrentHashAsUInt64() /// public static byte[] Hash(byte[] source) { - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } + ArgumentNullException.ThrowIfNull(source); return Hash(new ReadOnlySpan(source)); } @@ -180,10 +177,7 @@ public static byte[] Hash(byte[] source) /// public static byte[] Hash(byte[] source, long seed) { - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } + ArgumentNullException.ThrowIfNull(source); return Hash(new ReadOnlySpan(source), seed); } diff --git a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ContentType.cs b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ContentType.cs index 894fd4826aa80d..9e59813328e35a 100644 --- a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ContentType.cs +++ b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ContentType.cs @@ -72,10 +72,7 @@ internal sealed class ContentType /// If the contentType string invalid CR-LF characters internal ContentType(string contentType) { - if (contentType is null) - { - throw new ArgumentNullException(nameof(contentType)); - } + ArgumentNullException.ThrowIfNull(contentType); if (contentType.Length == 0) { diff --git a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/InternalRelationshipCollection.cs b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/InternalRelationshipCollection.cs index d76b0972d017ce..eb2ba0b482f5b3 100644 --- a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/InternalRelationshipCollection.cs +++ b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/InternalRelationshipCollection.cs @@ -389,14 +389,8 @@ private static void ProcessEndElementForRelationshipTag(XmlCompatibilityReader r /// from a relationship part, or we are adding a new relationship private PackageRelationship Add(Uri targetUri, TargetMode targetMode, string relationshipType, string? id, bool parsing) { - if (targetUri is null) - { - throw new ArgumentNullException(nameof(targetUri)); - } - if (relationshipType is null) - { - throw new ArgumentNullException(nameof(relationshipType)); - } + ArgumentNullException.ThrowIfNull(targetUri); + ArgumentNullException.ThrowIfNull(relationshipType); ThrowIfInvalidRelationshipType(relationshipType); diff --git a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackUriHelper.cs b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackUriHelper.cs index 0c0b3c33b43f98..2951cdeff40c4c 100644 --- a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackUriHelper.cs +++ b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackUriHelper.cs @@ -35,10 +35,7 @@ public static partial class PackUriHelper /// If partUri parameter has a fragment public static Uri CreatePartUri(Uri partUri) { - if (partUri is null) - { - throw new ArgumentNullException(nameof(partUri)); - } + ArgumentNullException.ThrowIfNull(partUri); ThrowIfAbsoluteUri(partUri); @@ -78,14 +75,8 @@ public static Uri CreatePartUri(Uri partUri) /// If sourcePartUri parameter does not conform to the valid partUri syntax public static Uri ResolvePartUri(Uri sourcePartUri, Uri targetUri) { - if (sourcePartUri is null) - { - throw new ArgumentNullException(nameof(sourcePartUri)); - } - if (targetUri is null) - { - throw new ArgumentNullException(nameof(targetUri)); - } + ArgumentNullException.ThrowIfNull(sourcePartUri); + ArgumentNullException.ThrowIfNull(targetUri); ThrowIfAbsoluteUri(sourcePartUri); ThrowIfAbsoluteUri(targetUri); @@ -110,14 +101,8 @@ public static Uri ResolvePartUri(Uri sourcePartUri, Uri targetUri) /// If either sourcePartUri or targetPartUri parameter does not conform to the valid partUri syntax public static Uri GetRelativeUri(Uri sourcePartUri, Uri targetPartUri) { - if (sourcePartUri is null) - { - throw new ArgumentNullException(nameof(sourcePartUri)); - } - if (targetPartUri is null) - { - throw new ArgumentNullException(nameof(targetPartUri)); - } + ArgumentNullException.ThrowIfNull(sourcePartUri); + ArgumentNullException.ThrowIfNull(targetPartUri); sourcePartUri = new Uri(s_defaultUri, ValidatePartUri(sourcePartUri)); targetPartUri = new Uri(s_defaultUri, ValidatePartUri(targetPartUri)); @@ -134,10 +119,7 @@ public static Uri GetRelativeUri(Uri sourcePartUri, Uri targetPartUri) /// If partUri parameter does not conform to the valid partUri syntax public static Uri GetNormalizedPartUri(Uri partUri) { - if (partUri is null) - { - throw new ArgumentNullException(nameof(partUri)); - } + ArgumentNullException.ThrowIfNull(partUri); ValidatedPartUri validatedUri = partUri as ValidatedPartUri ?? ValidatePartUri(partUri); @@ -182,10 +164,7 @@ public static int ComparePartUri(Uri? firstPartUri, Uri? secondPartUri) /// If partUri parameter does not conform to the valid partUri Syntax public static bool IsRelationshipPartUri(Uri partUri) { - if (partUri is null) - { - throw new ArgumentNullException(nameof(partUri)); - } + ArgumentNullException.ThrowIfNull(partUri); ValidatedPartUri validatedUri = partUri as ValidatedPartUri ?? ValidatePartUri(partUri); @@ -207,10 +186,7 @@ public static bool IsRelationshipPartUri(Uri partUri) /// If partUri parameter does not conform to the valid partUri Syntax public static Uri GetRelationshipPartUri(Uri partUri) { - if (partUri is null) - { - throw new ArgumentNullException(nameof(partUri)); - } + ArgumentNullException.ThrowIfNull(partUri); if (Uri.Compare(partUri, PackageRootUri, UriComponents.SerializationInfoString, UriFormat.UriEscaped, StringComparison.Ordinal) == 0) return PackageRelationship.ContainerRelationshipPartName; @@ -263,10 +239,7 @@ public static Uri GetRelationshipPartUri(Uri partUri) /// If the resultant Uri obtained is a relationship part Uri public static Uri GetSourcePartUriFromRelationshipPartUri(Uri relationshipPartUri) { - if (relationshipPartUri is null) - { - throw new ArgumentNullException(nameof(relationshipPartUri)); - } + ArgumentNullException.ThrowIfNull(relationshipPartUri); // Verify - // 1. Validates that this part Uri is a valid part Uri @@ -396,10 +369,7 @@ internal static string GetStringForPartUri(Uri partUri) #region Private Methods private static Exception? GetExceptionIfPartUriInvalid(Uri partUri, out string partUriString) { - if (partUri is null) - { - throw new ArgumentNullException(nameof(partUri)); - } + ArgumentNullException.ThrowIfNull(partUri); partUriString = string.Empty; diff --git a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/Package.cs b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/Package.cs index 23aea78342647f..2a6adbac5a4ab4 100644 --- a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/Package.cs +++ b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/Package.cs @@ -854,10 +854,7 @@ public static Package Open( FileAccess packageAccess, FileShare packageShare) { - if (path is null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullException.ThrowIfNull(path); ThrowIfFileModeInvalid(packageMode); ThrowIfFileAccessInvalid(packageAccess); @@ -918,10 +915,7 @@ public static Package Open( /// If package to be created should have readwrite/write access and underlying stream is read only public static Package Open(Stream stream, FileMode packageMode, FileAccess packageAccess) { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } + ArgumentNullException.ThrowIfNull(stream); Package? package = null; try diff --git a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackagePart.cs b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackagePart.cs index 8340ac629f1739..48882115a7473e 100644 --- a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackagePart.cs +++ b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackagePart.cs @@ -98,14 +98,8 @@ protected PackagePart(Package package, string? contentType, CompressionOption compressionOption) { - if (package is null) - { - throw new ArgumentNullException(nameof(package)); - } - if (partUri is null) - { - throw new ArgumentNullException(nameof(partUri)); - } + ArgumentNullException.ThrowIfNull(package); + ArgumentNullException.ThrowIfNull(partUri); Package.ThrowIfCompressionOptionInvalid(compressionOption); diff --git a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackageRelationship.cs b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackageRelationship.cs index 24091a03f9fd4d..ca4bc1f5e90645 100644 --- a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackageRelationship.cs +++ b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackageRelationship.cs @@ -112,22 +112,10 @@ public Package Package /// unique identifier internal PackageRelationship(Package package, PackagePart? sourcePart, Uri targetUri, TargetMode targetMode, string relationshipType, string id) { - if (package is null) - { - throw new ArgumentNullException(nameof(package)); - } - if (targetUri is null) - { - throw new ArgumentNullException(nameof(targetUri)); - } - if (relationshipType is null) - { - throw new ArgumentNullException(nameof(relationshipType)); - } - if (id is null) - { - throw new ArgumentNullException(nameof(id)); - } + ArgumentNullException.ThrowIfNull(package); + ArgumentNullException.ThrowIfNull(targetUri); + ArgumentNullException.ThrowIfNull(relationshipType); + ArgumentNullException.ThrowIfNull(id); //sourcePart can be null to represent that the relationships are at the package level diff --git a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackageRelationshipSelector.cs b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackageRelationshipSelector.cs index 678986d2af3b68..1f43c5a8b7d490 100644 --- a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackageRelationshipSelector.cs +++ b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackageRelationshipSelector.cs @@ -30,14 +30,8 @@ public sealed class PackageRelationshipSelector /// valid PartUri syntax public PackageRelationshipSelector(Uri sourceUri, PackageRelationshipSelectorType selectorType, string selectionCriteria) { - if (sourceUri is null) - { - throw new ArgumentNullException(nameof(sourceUri)); - } - if (selectionCriteria is null) - { - throw new ArgumentNullException(nameof(selectionCriteria)); - } + ArgumentNullException.ThrowIfNull(sourceUri); + ArgumentNullException.ThrowIfNull(selectionCriteria); //If the sourceUri is not equal to "/", it must be a valid part name. if (Uri.Compare(sourceUri, PackUriHelper.PackageRootUri, UriComponents.SerializationInfoString, UriFormat.UriEscaped, StringComparison.Ordinal) != 0) @@ -114,10 +108,7 @@ public string SelectionCriteria /// If package parameter is null public List Select(Package package) { - if (package is null) - { - throw new ArgumentNullException(nameof(package)); - } + ArgumentNullException.ThrowIfNull(package); List relationships = new List(0); diff --git a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ZipPackagePartPiece.cs b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ZipPackagePartPiece.cs index 67ec7b3e7dadd2..a3c3b62a599a60 100644 --- a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ZipPackagePartPiece.cs +++ b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ZipPackagePartPiece.cs @@ -24,12 +24,7 @@ internal sealed class ZipPackagePartPiece : IComparable /// internal static bool TryParse(ZipArchiveEntry zipArchiveEntry, [NotNullWhen(true)] out ZipPackagePartPiece? partPiece) { -#if NET ArgumentNullException.ThrowIfNull(zipArchiveEntry); -#else - if (zipArchiveEntry == null) - throw new ArgumentNullException(nameof(zipArchiveEntry)); -#endif partPiece = null; @@ -155,15 +150,11 @@ internal static ZipPackagePartPiece Create(ZipArchive zipArchive, PackUriHelper. internal ZipPackagePartPiece(ZipArchiveEntry zipArchiveEntry, PackUriHelper.ValidatedPartUri? partUri, string prefixName, int pieceNumber, bool isLastPiece) { -#if NET ArgumentNullException.ThrowIfNull(zipArchiveEntry); ArgumentNullException.ThrowIfNull(prefixName); +#if NET ArgumentOutOfRangeException.ThrowIfNegative(pieceNumber); #else - if (zipArchiveEntry == null) - throw new ArgumentNullException(nameof(zipArchiveEntry)); - if (prefixName == null) - throw new ArgumentNullException(nameof(prefixName)); if (pieceNumber < 0) throw new ArgumentOutOfRangeException(nameof(pieceNumber)); #endif diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System.Linq.AsyncEnumerable.csproj b/src/libraries/System.Linq.AsyncEnumerable/src/System.Linq.AsyncEnumerable.csproj index 6a3015dca506c9..0682eee5d2ef7d 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System.Linq.AsyncEnumerable.csproj +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System.Linq.AsyncEnumerable.csproj @@ -1,4 +1,4 @@ - + $(NetCoreAppCurrent);$(NetCoreAppPrevious);$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum) @@ -96,8 +96,6 @@ - - @@ -107,4 +105,4 @@ - \ No newline at end of file + diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/AggregateAsync.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/AggregateAsync.cs index 9efd8af992a1f2..b12d3bd8a2586d 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/AggregateAsync.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/AggregateAsync.cs @@ -24,8 +24,8 @@ public static ValueTask AggregateAsync( Func func, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(func); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(func); return Impl(source, func, cancellationToken); @@ -65,8 +65,8 @@ public static ValueTask AggregateAsync( Func> func, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(func); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(func); return Impl(source, func, cancellationToken); @@ -108,8 +108,8 @@ public static ValueTask AggregateAsync( Func func, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(func); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(func); return Impl(source.WithCancellation(cancellationToken), seed, func); @@ -144,8 +144,8 @@ public static ValueTask AggregateAsync( Func> func, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(func); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(func); return Impl(source, seed, func, cancellationToken); @@ -189,9 +189,9 @@ public static ValueTask AggregateAsync( Func resultSelector, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(func); - ThrowHelper.ThrowIfNull(resultSelector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(func); + ArgumentNullException.ThrowIfNull(resultSelector); return Impl(source.WithCancellation(cancellationToken), seed, func, resultSelector); @@ -236,9 +236,9 @@ public static ValueTask AggregateAsync( Func> resultSelector, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(func); - ThrowHelper.ThrowIfNull(resultSelector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(func); + ArgumentNullException.ThrowIfNull(resultSelector); return Impl(source, seed, func, resultSelector, cancellationToken); diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/AggregateBy.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/AggregateBy.cs index 63f488bb1cfca8..db3679e290b912 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/AggregateBy.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/AggregateBy.cs @@ -38,9 +38,9 @@ public static IAsyncEnumerable> AggregateBy? keyComparer = null) where TKey : notnull { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(keySelector); - ThrowHelper.ThrowIfNull(func); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(func); return source.IsKnownEmpty() ? Empty>() : @@ -109,9 +109,9 @@ public static IAsyncEnumerable> AggregateBy? keyComparer = null) where TKey : notnull { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(keySelector); - ThrowHelper.ThrowIfNull(func); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(func); return source.IsKnownEmpty() ? Empty>() : @@ -175,10 +175,10 @@ public static IAsyncEnumerable> AggregateBy func, IEqualityComparer? keyComparer = null) where TKey : notnull { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(keySelector); - ThrowHelper.ThrowIfNull(seedSelector); - ThrowHelper.ThrowIfNull(func); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(seedSelector); + ArgumentNullException.ThrowIfNull(func); return source.IsKnownEmpty() ? Empty>() : @@ -247,10 +247,10 @@ public static IAsyncEnumerable> AggregateBy> func, IEqualityComparer? keyComparer = null) where TKey : notnull { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(keySelector); - ThrowHelper.ThrowIfNull(seedSelector); - ThrowHelper.ThrowIfNull(func); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(seedSelector); + ArgumentNullException.ThrowIfNull(func); return source.IsKnownEmpty() ? Empty>() : diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/AllAsync.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/AllAsync.cs index 54756c26623dfa..be4b34fc958eeb 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/AllAsync.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/AllAsync.cs @@ -26,8 +26,8 @@ public static ValueTask AllAsync( Func predicate, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(predicate); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); return Impl(source.WithCancellation(cancellationToken), predicate); @@ -64,8 +64,8 @@ public static ValueTask AllAsync( ValueTask> predicate, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(predicate); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); return Impl(source, predicate, cancellationToken); diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/AnyAsync.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/AnyAsync.cs index b05df9797a7364..936f252cb9fc4c 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/AnyAsync.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/AnyAsync.cs @@ -20,7 +20,7 @@ public static ValueTask AnyAsync( this IAsyncEnumerable source, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return Impl(source, cancellationToken); @@ -50,8 +50,8 @@ public static ValueTask AnyAsync( Func predicate, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(predicate); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); return Impl(source.WithCancellation(cancellationToken), predicate); @@ -87,8 +87,8 @@ public static ValueTask AnyAsync( Func> predicate, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(predicate); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); return Impl(source, predicate, cancellationToken); diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Append.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Append.cs index 055defa8caea98..7bd0ec485d5eb5 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Append.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Append.cs @@ -20,7 +20,7 @@ public static IAsyncEnumerable Append( this IAsyncEnumerable source, TSource element) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return Impl(source, element, default); diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/AverageAsync.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/AverageAsync.cs index e10d5e1ed030f0..658543aa51eafc 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/AverageAsync.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/AverageAsync.cs @@ -21,7 +21,7 @@ public static ValueTask AverageAsync( this IAsyncEnumerable source, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return Impl(source.WithCancellation(cancellationToken)); @@ -56,7 +56,7 @@ public static ValueTask AverageAsync( this IAsyncEnumerable source, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return Impl(source.WithCancellation(cancellationToken)); @@ -89,7 +89,7 @@ static async ValueTask Impl( public static ValueTask AverageAsync( this IAsyncEnumerable source, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return Impl(source.WithCancellation(cancellationToken)); @@ -122,7 +122,7 @@ static async ValueTask Impl( public static ValueTask AverageAsync( this IAsyncEnumerable source, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return Impl(source.WithCancellation(cancellationToken)); @@ -155,7 +155,7 @@ static async ValueTask Impl( public static ValueTask AverageAsync( this IAsyncEnumerable source, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return Impl(source.WithCancellation(cancellationToken)); @@ -189,7 +189,7 @@ static async ValueTask Impl( public static ValueTask AverageAsync( this IAsyncEnumerable source, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return Impl(source.WithCancellation(cancellationToken)); @@ -221,7 +221,7 @@ static async ValueTask Impl( public static ValueTask AverageAsync( this IAsyncEnumerable source, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return Impl(source.WithCancellation(cancellationToken)); @@ -252,7 +252,7 @@ static async ValueTask Impl( public static ValueTask AverageAsync( this IAsyncEnumerable source, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return Impl(source.WithCancellation(cancellationToken)); @@ -283,7 +283,7 @@ static async ValueTask Impl( public static ValueTask AverageAsync( this IAsyncEnumerable source, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return Impl(source.WithCancellation(cancellationToken)); @@ -314,7 +314,7 @@ static async ValueTask Impl( public static ValueTask AverageAsync( this IAsyncEnumerable source, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return Impl(source.WithCancellation(cancellationToken)); diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Cast.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Cast.cs index f7d6d6a2f81c17..2316c3edcd3587 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Cast.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Cast.cs @@ -24,7 +24,7 @@ public static partial class AsyncEnumerable public static IAsyncEnumerable Cast( // satisfies the C# query-expression pattern this IAsyncEnumerable source) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return source.IsKnownEmpty() ? Empty() : diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Chunk.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Chunk.cs index 3510407611eeb1..e2a4d6a7ee0aeb 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Chunk.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Chunk.cs @@ -27,7 +27,7 @@ public static IAsyncEnumerable Chunk( this IAsyncEnumerable source, int size) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); ThrowHelper.ThrowIfNegativeOrZero(size); return diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Concat.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Concat.cs index 940cd87718eeb0..cc36182574cdfb 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Concat.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Concat.cs @@ -20,8 +20,8 @@ public static partial class AsyncEnumerable public static IAsyncEnumerable Concat( this IAsyncEnumerable first, IAsyncEnumerable second) { - ThrowHelper.ThrowIfNull(first); - ThrowHelper.ThrowIfNull(second); + ArgumentNullException.ThrowIfNull(first); + ArgumentNullException.ThrowIfNull(second); return first.IsKnownEmpty() ? second : diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ContainsAsync.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ContainsAsync.cs index 5e8100ef36edf3..bdff13f64db72a 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ContainsAsync.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ContainsAsync.cs @@ -24,7 +24,7 @@ public static ValueTask ContainsAsync( IEqualityComparer? comparer = null, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return Impl(source.WithCancellation(cancellationToken), value, comparer ?? EqualityComparer.Default); diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/CountAsync.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/CountAsync.cs index 5f2419774b2f92..1094e9196e5eaf 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/CountAsync.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/CountAsync.cs @@ -21,7 +21,7 @@ public static ValueTask CountAsync( this IAsyncEnumerable source, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return Impl(source, cancellationToken); @@ -54,8 +54,8 @@ public static ValueTask CountAsync( Func predicate, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(predicate); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); return Impl(source.WithCancellation(cancellationToken), predicate); @@ -89,8 +89,8 @@ public static ValueTask CountAsync( Func> predicate, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(predicate); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); return Impl(source, predicate, cancellationToken); @@ -122,7 +122,7 @@ public static ValueTask LongCountAsync( this IAsyncEnumerable source, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return Impl(source, cancellationToken); @@ -154,8 +154,8 @@ public static ValueTask LongCountAsync( Func predicate, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(predicate); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); return Impl(source.WithCancellation(cancellationToken), predicate); @@ -188,8 +188,8 @@ public static ValueTask LongCountAsync( Func> predicate, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(predicate); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); return Impl(source, predicate, cancellationToken); diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/CountBy.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/CountBy.cs index 117baae8d087c7..5fa7733b0503e8 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/CountBy.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/CountBy.cs @@ -25,8 +25,8 @@ public static IAsyncEnumerable> CountBy( Func keySelector, IEqualityComparer? keyComparer = null) where TKey : notnull { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); return source.IsKnownEmpty() ? Empty>() : @@ -76,8 +76,8 @@ public static IAsyncEnumerable> CountBy( Func> keySelector, IEqualityComparer? keyComparer = null) where TKey : notnull { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); return source.IsKnownEmpty() ? Empty>() : diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/DefaultIfEmpty.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/DefaultIfEmpty.cs index 7fb67371dd9562..5503b1878e1eb2 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/DefaultIfEmpty.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/DefaultIfEmpty.cs @@ -33,7 +33,7 @@ public static partial class AsyncEnumerable public static IAsyncEnumerable DefaultIfEmpty( this IAsyncEnumerable source, TSource defaultValue) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return Impl(source, defaultValue, default); diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Distinct.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Distinct.cs index 307ca29e0f50c3..0162e34d0355df 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Distinct.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Distinct.cs @@ -19,7 +19,7 @@ public static IAsyncEnumerable Distinct( this IAsyncEnumerable source, IEqualityComparer? comparer = null) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return source.IsKnownEmpty() ? Empty() : diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/DistinctBy.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/DistinctBy.cs index af83cb160f211c..663040e7bba757 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/DistinctBy.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/DistinctBy.cs @@ -29,8 +29,8 @@ public static IAsyncEnumerable DistinctBy( Func keySelector, IEqualityComparer? comparer = null) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); return source.IsKnownEmpty() ? Empty() : @@ -79,8 +79,8 @@ public static IAsyncEnumerable DistinctBy( Func> keySelector, IEqualityComparer? comparer = null) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); return source.IsKnownEmpty() ? Empty() : diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ElementAtAsync.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ElementAtAsync.cs index 9503396d9531eb..bc52553977bb16 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ElementAtAsync.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ElementAtAsync.cs @@ -22,7 +22,7 @@ public static ValueTask ElementAtAsync( int index, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return ElementAtOrDefaultAsync(source, index, throwIfNotFound: true, cancellationToken)!; } @@ -42,7 +42,7 @@ public static ValueTask ElementAtAsync( int index, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return ElementAtOrDefaultAsync(source, index, throwIfNotFound: false, cancellationToken); } @@ -71,7 +71,7 @@ public static ValueTask ElementAtAsync( return ElementAtAsync(source, index.Value, cancellationToken); } - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return ElementAtFromEndOrDefault(source, index.Value, throwIfNotFound: true, cancellationToken)!; } @@ -98,7 +98,7 @@ public static ValueTask ElementAtAsync( return ElementAtOrDefaultAsync(source, index.Value, cancellationToken); } - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return ElementAtFromEndOrDefault(source, index.Value, throwIfNotFound: false, cancellationToken); } diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Empty.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Empty.cs index 2c39758ce16c28..e995f5c281796e 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Empty.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Empty.cs @@ -35,13 +35,13 @@ private sealed class EmptyAsyncEnumerable : public IOrderedAsyncEnumerable CreateOrderedAsyncEnumerable(Func keySelector, IComparer? comparer, bool descending) { - ThrowHelper.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(keySelector); return this; } public IOrderedAsyncEnumerable CreateOrderedAsyncEnumerable(Func> keySelector, IComparer? comparer, bool descending) { - ThrowHelper.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(keySelector); return this; } } diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Except.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Except.cs index 7452e1efac19fd..edd774c7e58fd3 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Except.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Except.cs @@ -23,8 +23,8 @@ public static IAsyncEnumerable Except( IAsyncEnumerable second, IEqualityComparer? comparer = null) { - ThrowHelper.ThrowIfNull(first); - ThrowHelper.ThrowIfNull(second); + ArgumentNullException.ThrowIfNull(first); + ArgumentNullException.ThrowIfNull(second); return first.IsKnownEmpty() ? Empty() : diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ExceptBy.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ExceptBy.cs index 99d6c3fa734f64..b415c3923dbf9d 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ExceptBy.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ExceptBy.cs @@ -29,9 +29,9 @@ public static IAsyncEnumerable ExceptBy( Func keySelector, IEqualityComparer? comparer = null) { - ThrowHelper.ThrowIfNull(first); - ThrowHelper.ThrowIfNull(second); - ThrowHelper.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(first); + ArgumentNullException.ThrowIfNull(second); + ArgumentNullException.ThrowIfNull(keySelector); return first.IsKnownEmpty() ? Empty() : @@ -89,9 +89,9 @@ public static IAsyncEnumerable ExceptBy( Func> keySelector, IEqualityComparer? comparer = null) { - ThrowHelper.ThrowIfNull(first); - ThrowHelper.ThrowIfNull(second); - ThrowHelper.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(first); + ArgumentNullException.ThrowIfNull(second); + ArgumentNullException.ThrowIfNull(keySelector); return first.IsKnownEmpty() ? Empty() : diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/FirstAsync.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/FirstAsync.cs index 5abc91ded2f446..c85df6a379a4e1 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/FirstAsync.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/FirstAsync.cs @@ -21,7 +21,7 @@ public static ValueTask FirstAsync( this IAsyncEnumerable source, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return Impl(source, cancellationToken); @@ -57,8 +57,8 @@ public static ValueTask FirstAsync( Func predicate, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(predicate); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); return Impl(source.WithCancellation(cancellationToken), predicate); @@ -96,8 +96,8 @@ public static ValueTask FirstAsync( Func> predicate, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(predicate); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); return Impl(source, predicate, cancellationToken); @@ -142,7 +142,7 @@ public static ValueTask FirstOrDefaultAsync( TSource defaultValue, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return Impl(source, defaultValue, cancellationToken); @@ -206,8 +206,8 @@ public static ValueTask FirstOrDefaultAsync( TSource defaultValue, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(predicate); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); return Impl(source.WithCancellation(cancellationToken), predicate, defaultValue); @@ -243,8 +243,8 @@ public static ValueTask FirstOrDefaultAsync( TSource defaultValue, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(predicate); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); return Impl(source, predicate, defaultValue, cancellationToken); diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/GroupBy.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/GroupBy.cs index 768abe2a9f4435..f0ab6334e8391b 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/GroupBy.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/GroupBy.cs @@ -29,8 +29,8 @@ public static IAsyncEnumerable> GroupBy( Func keySelector, IEqualityComparer? comparer = null) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); return source.IsKnownEmpty() ? Empty>() : @@ -66,8 +66,8 @@ public static IAsyncEnumerable> GroupBy( Func> keySelector, IEqualityComparer? comparer = null) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); return source.IsKnownEmpty() ? Empty>() : @@ -111,9 +111,9 @@ public static IAsyncEnumerable> GroupBy elementSelector, IEqualityComparer? comparer = null) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(keySelector); - ThrowHelper.ThrowIfNull(elementSelector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(elementSelector); return source.IsKnownEmpty() ? Empty>() : @@ -158,9 +158,9 @@ public static IAsyncEnumerable> GroupBy> elementSelector, IEqualityComparer? comparer = null) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(keySelector); - ThrowHelper.ThrowIfNull(elementSelector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(elementSelector); return source.IsKnownEmpty() ? Empty>() : @@ -204,9 +204,9 @@ public static IAsyncEnumerable GroupBy( Func, TResult> resultSelector, IEqualityComparer? comparer = null) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(keySelector); - ThrowHelper.ThrowIfNull(resultSelector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(resultSelector); return source.IsKnownEmpty() ? Empty() : @@ -253,9 +253,9 @@ public static IAsyncEnumerable GroupBy( Func, CancellationToken, ValueTask> resultSelector, IEqualityComparer? comparer = null) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(keySelector); - ThrowHelper.ThrowIfNull(resultSelector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(resultSelector); return source.IsKnownEmpty() ? Empty() : @@ -305,10 +305,10 @@ public static IAsyncEnumerable GroupBy, TResult> resultSelector, IEqualityComparer? comparer = null) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(keySelector); - ThrowHelper.ThrowIfNull(elementSelector); - ThrowHelper.ThrowIfNull(resultSelector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(elementSelector); + ArgumentNullException.ThrowIfNull(resultSelector); return source.IsKnownEmpty() ? Empty() : @@ -359,10 +359,10 @@ public static IAsyncEnumerable GroupBy, CancellationToken, ValueTask> resultSelector, IEqualityComparer? comparer = null) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(keySelector); - ThrowHelper.ThrowIfNull(elementSelector); - ThrowHelper.ThrowIfNull(resultSelector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(elementSelector); + ArgumentNullException.ThrowIfNull(resultSelector); return source.IsKnownEmpty() ? Empty() : diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/GroupJoin.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/GroupJoin.cs index 1899404d15fd26..3673aa85956f52 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/GroupJoin.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/GroupJoin.cs @@ -41,11 +41,11 @@ public static IAsyncEnumerable GroupJoin Func, TResult> resultSelector, IEqualityComparer? comparer = null) { - ThrowHelper.ThrowIfNull(outer); - ThrowHelper.ThrowIfNull(inner); - ThrowHelper.ThrowIfNull(outerKeySelector); - ThrowHelper.ThrowIfNull(innerKeySelector); - ThrowHelper.ThrowIfNull(resultSelector); + ArgumentNullException.ThrowIfNull(outer); + ArgumentNullException.ThrowIfNull(inner); + ArgumentNullException.ThrowIfNull(outerKeySelector); + ArgumentNullException.ThrowIfNull(innerKeySelector); + ArgumentNullException.ThrowIfNull(resultSelector); return outer.IsKnownEmpty() ? Empty() : @@ -106,11 +106,11 @@ public static IAsyncEnumerable GroupJoin Func, CancellationToken, ValueTask> resultSelector, IEqualityComparer? comparer = null) { - ThrowHelper.ThrowIfNull(outer); - ThrowHelper.ThrowIfNull(inner); - ThrowHelper.ThrowIfNull(outerKeySelector); - ThrowHelper.ThrowIfNull(innerKeySelector); - ThrowHelper.ThrowIfNull(resultSelector); + ArgumentNullException.ThrowIfNull(outer); + ArgumentNullException.ThrowIfNull(inner); + ArgumentNullException.ThrowIfNull(outerKeySelector); + ArgumentNullException.ThrowIfNull(innerKeySelector); + ArgumentNullException.ThrowIfNull(resultSelector); return outer.IsKnownEmpty() ? Empty() : diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Index.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Index.cs index 75451a5d534bc6..17c08b5a06a932 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Index.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Index.cs @@ -18,7 +18,7 @@ public static partial class AsyncEnumerable public static IAsyncEnumerable<(int Index, TSource Item)> Index( this IAsyncEnumerable source) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return source.IsKnownEmpty() ? Empty<(int Index, TSource Item)>() : diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Intersect.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Intersect.cs index 076fa86c63b1e1..fbcb3e5b54d915 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Intersect.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Intersect.cs @@ -23,8 +23,8 @@ public static IAsyncEnumerable Intersect( IAsyncEnumerable second, IEqualityComparer? comparer = null) { - ThrowHelper.ThrowIfNull(first); - ThrowHelper.ThrowIfNull(second); + ArgumentNullException.ThrowIfNull(first); + ArgumentNullException.ThrowIfNull(second); return first.IsKnownEmpty() || second.IsKnownEmpty() ? Empty() : diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/IntersectBy.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/IntersectBy.cs index bd065263e7f67c..922cf5b6422e0e 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/IntersectBy.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/IntersectBy.cs @@ -34,9 +34,9 @@ public static IAsyncEnumerable IntersectBy( Func keySelector, IEqualityComparer? comparer = null) { - ThrowHelper.ThrowIfNull(first); - ThrowHelper.ThrowIfNull(second); - ThrowHelper.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(first); + ArgumentNullException.ThrowIfNull(second); + ArgumentNullException.ThrowIfNull(keySelector); return first.IsKnownEmpty() || second.IsKnownEmpty() ? Empty() : @@ -99,9 +99,9 @@ public static IAsyncEnumerable IntersectBy( Func> keySelector, IEqualityComparer? comparer = null) { - ThrowHelper.ThrowIfNull(first); - ThrowHelper.ThrowIfNull(second); - ThrowHelper.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(first); + ArgumentNullException.ThrowIfNull(second); + ArgumentNullException.ThrowIfNull(keySelector); return first.IsKnownEmpty() || second.IsKnownEmpty() ? Empty() : diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Join.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Join.cs index 68f2160e8769f2..eb086126386a30 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Join.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Join.cs @@ -38,11 +38,11 @@ public static IAsyncEnumerable Join( // Func resultSelector, IEqualityComparer? comparer = null) { - ThrowHelper.ThrowIfNull(outer); - ThrowHelper.ThrowIfNull(inner); - ThrowHelper.ThrowIfNull(outerKeySelector); - ThrowHelper.ThrowIfNull(innerKeySelector); - ThrowHelper.ThrowIfNull(resultSelector); + ArgumentNullException.ThrowIfNull(outer); + ArgumentNullException.ThrowIfNull(inner); + ArgumentNullException.ThrowIfNull(outerKeySelector); + ArgumentNullException.ThrowIfNull(innerKeySelector); + ArgumentNullException.ThrowIfNull(resultSelector); return outer.IsKnownEmpty() || inner.IsKnownEmpty() ? Empty() : @@ -111,11 +111,11 @@ public static IAsyncEnumerable Join( Func> resultSelector, IEqualityComparer? comparer = null) { - ThrowHelper.ThrowIfNull(outer); - ThrowHelper.ThrowIfNull(inner); - ThrowHelper.ThrowIfNull(outerKeySelector); - ThrowHelper.ThrowIfNull(innerKeySelector); - ThrowHelper.ThrowIfNull(resultSelector); + ArgumentNullException.ThrowIfNull(outer); + ArgumentNullException.ThrowIfNull(inner); + ArgumentNullException.ThrowIfNull(outerKeySelector); + ArgumentNullException.ThrowIfNull(innerKeySelector); + ArgumentNullException.ThrowIfNull(resultSelector); return outer.IsKnownEmpty() || inner.IsKnownEmpty() ? Empty() : diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/LastAsync.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/LastAsync.cs index 04e82e2bc9ab13..ef4065f537a41e 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/LastAsync.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/LastAsync.cs @@ -20,7 +20,7 @@ public static ValueTask LastAsync( this IAsyncEnumerable source, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return Impl(source, cancellationToken); @@ -63,8 +63,8 @@ public static ValueTask LastAsync( Func predicate, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(predicate); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); return Impl(source, predicate, cancellationToken); @@ -117,8 +117,8 @@ public static ValueTask LastAsync( Func> predicate, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(predicate); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); return Impl(source, predicate, cancellationToken); @@ -180,7 +180,7 @@ public static ValueTask LastOrDefaultAsync( TSource defaultValue, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return Impl(source, defaultValue, cancellationToken); @@ -246,8 +246,8 @@ public static ValueTask LastOrDefaultAsync( TSource defaultValue, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(predicate); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); return Impl(source, predicate, defaultValue, cancellationToken); @@ -299,8 +299,8 @@ public static ValueTask LastOrDefaultAsync( TSource defaultValue, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(predicate); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); return Impl(source, predicate, defaultValue, cancellationToken); diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/LeftJoin.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/LeftJoin.cs index ab158d697cb827..a86645ece88d69 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/LeftJoin.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/LeftJoin.cs @@ -35,11 +35,11 @@ public static IAsyncEnumerable LeftJoin( Func resultSelector, IEqualityComparer? comparer = null) { - ThrowHelper.ThrowIfNull(outer); - ThrowHelper.ThrowIfNull(inner); - ThrowHelper.ThrowIfNull(outerKeySelector); - ThrowHelper.ThrowIfNull(innerKeySelector); - ThrowHelper.ThrowIfNull(resultSelector); + ArgumentNullException.ThrowIfNull(outer); + ArgumentNullException.ThrowIfNull(inner); + ArgumentNullException.ThrowIfNull(outerKeySelector); + ArgumentNullException.ThrowIfNull(innerKeySelector); + ArgumentNullException.ThrowIfNull(resultSelector); return outer.IsKnownEmpty() ? Empty() : @@ -106,11 +106,11 @@ public static IAsyncEnumerable LeftJoin( Func> resultSelector, IEqualityComparer? comparer = null) { - ThrowHelper.ThrowIfNull(outer); - ThrowHelper.ThrowIfNull(inner); - ThrowHelper.ThrowIfNull(outerKeySelector); - ThrowHelper.ThrowIfNull(innerKeySelector); - ThrowHelper.ThrowIfNull(resultSelector); + ArgumentNullException.ThrowIfNull(outer); + ArgumentNullException.ThrowIfNull(inner); + ArgumentNullException.ThrowIfNull(outerKeySelector); + ArgumentNullException.ThrowIfNull(innerKeySelector); + ArgumentNullException.ThrowIfNull(resultSelector); return outer.IsKnownEmpty() ? Empty() : diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/MaxAsync.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/MaxAsync.cs index a1046e2ed1fcc5..1b585c1dbc3dd0 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/MaxAsync.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/MaxAsync.cs @@ -26,7 +26,7 @@ public static partial class AsyncEnumerable IComparer? comparer = null, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); comparer ??= Comparer.Default; diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/MaxByAsync.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/MaxByAsync.cs index 0d0112d8db1de5..0d5c935d8facfa 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/MaxByAsync.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/MaxByAsync.cs @@ -28,8 +28,8 @@ public static partial class AsyncEnumerable IComparer? comparer = null, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); return Impl(source, keySelector, comparer ?? Comparer.Default, cancellationToken); @@ -138,8 +138,8 @@ public static partial class AsyncEnumerable IComparer? comparer = null, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); return Impl(source, keySelector, comparer ?? Comparer.Default, cancellationToken); diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/MinAsync.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/MinAsync.cs index 9ddf16d55b4f95..25cf4753115c7d 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/MinAsync.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/MinAsync.cs @@ -26,7 +26,7 @@ public static partial class AsyncEnumerable IComparer? comparer = null, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); comparer ??= Comparer.Default; diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/MinByAsync.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/MinByAsync.cs index b029aebbecd6d7..1ec10b5a360690 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/MinByAsync.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/MinByAsync.cs @@ -28,8 +28,8 @@ public static partial class AsyncEnumerable IComparer? comparer = null, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); return Impl(source, keySelector, comparer ?? Comparer.Default, cancellationToken); @@ -138,8 +138,8 @@ public static partial class AsyncEnumerable IComparer? comparer = null, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); return Impl(source, keySelector, comparer ?? Comparer.Default, cancellationToken); diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/OfType.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/OfType.cs index 9610cfea8b1065..bba87d138417f8 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/OfType.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/OfType.cs @@ -24,7 +24,7 @@ public static partial class AsyncEnumerable public static IAsyncEnumerable OfType( this IAsyncEnumerable source) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return source.IsKnownEmpty() ? Empty() : diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/OrderBy.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/OrderBy.cs index fa83e476d47ea3..1c5623de99b307 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/OrderBy.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/OrderBy.cs @@ -35,8 +35,8 @@ public static IOrderedAsyncEnumerable OrderBy( // satisf Func keySelector, IComparer? comparer = null) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); return source.IsKnownEmpty() ? EmptyAsyncEnumerable.Instance : @@ -57,8 +57,8 @@ public static IOrderedAsyncEnumerable OrderBy( Func> keySelector, IComparer? comparer = null) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); return source.IsKnownEmpty() ? EmptyAsyncEnumerable.Instance : @@ -90,8 +90,8 @@ public static IOrderedAsyncEnumerable OrderByDescending( Func keySelector, IComparer? comparer = null) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); return source.IsKnownEmpty() ? EmptyAsyncEnumerable.Instance : @@ -112,8 +112,8 @@ public static IOrderedAsyncEnumerable OrderByDescending( Func> keySelector, IComparer? comparer = null) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); return source.IsKnownEmpty() ? EmptyAsyncEnumerable.Instance : @@ -134,7 +134,7 @@ public static IOrderedAsyncEnumerable ThenBy( // satisfi Func keySelector, IComparer? comparer = null) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return source.CreateOrderedAsyncEnumerable(keySelector, comparer, descending: false); } @@ -153,7 +153,7 @@ public static IOrderedAsyncEnumerable ThenBy( Func> keySelector, IComparer? comparer = null) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return source.CreateOrderedAsyncEnumerable(keySelector, comparer, descending: false); } @@ -172,7 +172,7 @@ public static IOrderedAsyncEnumerable ThenByDescending( Func keySelector, IComparer? comparer = null) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return source.CreateOrderedAsyncEnumerable(keySelector, comparer, descending: true); } @@ -191,7 +191,7 @@ public static IOrderedAsyncEnumerable ThenByDescending( Func> keySelector, IComparer? comparer = null) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return source.CreateOrderedAsyncEnumerable(keySelector, comparer, descending: true); } diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Prepend.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Prepend.cs index 139e21f89afc72..074695989201df 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Prepend.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Prepend.cs @@ -20,7 +20,7 @@ public static IAsyncEnumerable Prepend( this IAsyncEnumerable source, TSource element) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return Impl(source, element, default); diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Reverse.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Reverse.cs index 0472ac5f9a1833..0d828214a6796e 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Reverse.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Reverse.cs @@ -17,7 +17,7 @@ public static partial class AsyncEnumerable public static IAsyncEnumerable Reverse( this IAsyncEnumerable source) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return source.IsKnownEmpty() ? Empty() : diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/RightJoin.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/RightJoin.cs index 6bef86978d89eb..9328acb4597abc 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/RightJoin.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/RightJoin.cs @@ -35,11 +35,11 @@ public static IAsyncEnumerable RightJoin Func resultSelector, IEqualityComparer? comparer = null) { - ThrowHelper.ThrowIfNull(outer); - ThrowHelper.ThrowIfNull(inner); - ThrowHelper.ThrowIfNull(outerKeySelector); - ThrowHelper.ThrowIfNull(innerKeySelector); - ThrowHelper.ThrowIfNull(resultSelector); + ArgumentNullException.ThrowIfNull(outer); + ArgumentNullException.ThrowIfNull(inner); + ArgumentNullException.ThrowIfNull(outerKeySelector); + ArgumentNullException.ThrowIfNull(innerKeySelector); + ArgumentNullException.ThrowIfNull(resultSelector); return inner.IsKnownEmpty() ? Empty() : @@ -107,11 +107,11 @@ public static IAsyncEnumerable RightJoin Func> resultSelector, IEqualityComparer? comparer = null) { - ThrowHelper.ThrowIfNull(outer); - ThrowHelper.ThrowIfNull(inner); - ThrowHelper.ThrowIfNull(outerKeySelector); - ThrowHelper.ThrowIfNull(innerKeySelector); - ThrowHelper.ThrowIfNull(resultSelector); + ArgumentNullException.ThrowIfNull(outer); + ArgumentNullException.ThrowIfNull(inner); + ArgumentNullException.ThrowIfNull(outerKeySelector); + ArgumentNullException.ThrowIfNull(innerKeySelector); + ArgumentNullException.ThrowIfNull(resultSelector); return inner.IsKnownEmpty() ? Empty() : diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Select.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Select.cs index 6edcbaeb802c86..3af109b3844199 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Select.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Select.cs @@ -25,8 +25,8 @@ public static IAsyncEnumerable Select( // satisfies t this IAsyncEnumerable source, Func selector) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(selector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); return source.IsKnownEmpty() ? Empty() : @@ -59,8 +59,8 @@ public static IAsyncEnumerable Select( this IAsyncEnumerable source, Func> selector) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(selector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); return source.IsKnownEmpty() ? Empty() : @@ -96,8 +96,8 @@ public static IAsyncEnumerable Select( this IAsyncEnumerable source, Func selector) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(selector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); return source.IsKnownEmpty() ? Empty() : @@ -134,8 +134,8 @@ public static IAsyncEnumerable Select( this IAsyncEnumerable source, Func> selector) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(selector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); return source.IsKnownEmpty() ? Empty() : diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/SelectMany.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/SelectMany.cs index 0e70e9b26e1e1c..9b79e9828fd412 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/SelectMany.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/SelectMany.cs @@ -28,8 +28,8 @@ public static IAsyncEnumerable SelectMany( this IAsyncEnumerable source, Func> selector) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(selector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); return source.IsKnownEmpty() ? Empty() : @@ -68,8 +68,8 @@ public static IAsyncEnumerable SelectMany( this IAsyncEnumerable source, Func>> selector) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(selector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); return source.IsKnownEmpty() ? Empty() : @@ -108,8 +108,8 @@ public static IAsyncEnumerable SelectMany( this IAsyncEnumerable source, Func> selector) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(selector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); return source.IsKnownEmpty() ? Empty() : @@ -149,8 +149,8 @@ public static IAsyncEnumerable SelectMany( this IAsyncEnumerable source, Func> selector) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(selector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); return source.IsKnownEmpty() ? Empty() : @@ -191,8 +191,8 @@ public static IAsyncEnumerable SelectMany( this IAsyncEnumerable source, Func>> selector) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(selector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); return source.IsKnownEmpty() ? Empty() : @@ -233,8 +233,8 @@ public static IAsyncEnumerable SelectMany( this IAsyncEnumerable source, Func> selector) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(selector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); return source.IsKnownEmpty() ? Empty() : @@ -282,9 +282,9 @@ public static IAsyncEnumerable SelectMany> collectionSelector, Func resultSelector) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(collectionSelector); - ThrowHelper.ThrowIfNull(resultSelector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(collectionSelector); + ArgumentNullException.ThrowIfNull(resultSelector); return source.IsKnownEmpty() ? Empty() : @@ -332,9 +332,9 @@ public static IAsyncEnumerable SelectMany>> collectionSelector, Func> resultSelector) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(collectionSelector); - ThrowHelper.ThrowIfNull(resultSelector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(collectionSelector); + ArgumentNullException.ThrowIfNull(resultSelector); return source.IsKnownEmpty() ? Empty() : @@ -382,9 +382,9 @@ public static IAsyncEnumerable SelectMany> collectionSelector, Func resultSelector) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(collectionSelector); - ThrowHelper.ThrowIfNull(resultSelector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(collectionSelector); + ArgumentNullException.ThrowIfNull(resultSelector); return source.IsKnownEmpty() ? Empty() : @@ -432,9 +432,9 @@ public static IAsyncEnumerable SelectMany> collectionSelector, Func> resultSelector) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(collectionSelector); - ThrowHelper.ThrowIfNull(resultSelector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(collectionSelector); + ArgumentNullException.ThrowIfNull(resultSelector); return source.IsKnownEmpty() ? Empty() : @@ -481,9 +481,9 @@ public static IAsyncEnumerable SelectMany> collectionSelector, Func resultSelector) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(collectionSelector); - ThrowHelper.ThrowIfNull(resultSelector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(collectionSelector); + ArgumentNullException.ThrowIfNull(resultSelector); return source.IsKnownEmpty() ? Empty() : @@ -531,9 +531,9 @@ public static IAsyncEnumerable SelectMany>> collectionSelector, Func> resultSelector) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(collectionSelector); - ThrowHelper.ThrowIfNull(resultSelector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(collectionSelector); + ArgumentNullException.ThrowIfNull(resultSelector); return source.IsKnownEmpty() ? Empty() : @@ -581,9 +581,9 @@ public static IAsyncEnumerable SelectMany> collectionSelector, Func> resultSelector) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(collectionSelector); - ThrowHelper.ThrowIfNull(resultSelector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(collectionSelector); + ArgumentNullException.ThrowIfNull(resultSelector); return source.IsKnownEmpty() ? Empty() : diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/SequenceEqualAsync.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/SequenceEqualAsync.cs index 458ef18f96af14..51f8445fe8855e 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/SequenceEqualAsync.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/SequenceEqualAsync.cs @@ -25,8 +25,8 @@ public static ValueTask SequenceEqualAsync( IEqualityComparer? comparer = null, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(first); - ThrowHelper.ThrowIfNull(second); + ArgumentNullException.ThrowIfNull(first); + ArgumentNullException.ThrowIfNull(second); return Impl(first, second, comparer ?? EqualityComparer.Default, cancellationToken); diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Shuffle.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Shuffle.cs index dde415abea0267..c35fc66f0dd130 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Shuffle.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Shuffle.cs @@ -22,7 +22,7 @@ public static partial class AsyncEnumerable public static IAsyncEnumerable Shuffle( this IAsyncEnumerable source) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return source.IsKnownEmpty() ? Empty() : diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/SingleAsync.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/SingleAsync.cs index f0c1aed926cf82..fa5685c05b31be 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/SingleAsync.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/SingleAsync.cs @@ -24,7 +24,7 @@ public static ValueTask SingleAsync( this IAsyncEnumerable source, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return Impl(source, cancellationToken); @@ -67,8 +67,8 @@ public static ValueTask SingleAsync( Func predicate, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(predicate); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); return Impl(source, predicate, cancellationToken); @@ -120,8 +120,8 @@ public static ValueTask SingleAsync( Func> predicate, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(predicate); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); return Impl(source, predicate, cancellationToken); @@ -185,7 +185,7 @@ public static ValueTask SingleOrDefaultAsync( TSource defaultValue, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return Impl(source, defaultValue, cancellationToken); @@ -271,8 +271,8 @@ public static ValueTask SingleOrDefaultAsync( TSource defaultValue, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(predicate); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); return Impl(source, predicate, defaultValue, cancellationToken); @@ -321,8 +321,8 @@ public static ValueTask SingleOrDefaultAsync( TSource defaultValue, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(predicate); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); return Impl(source, predicate, defaultValue, cancellationToken); diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Skip.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Skip.cs index a5fdbc633e550d..4c3a6dc2f55ed5 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Skip.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Skip.cs @@ -19,7 +19,7 @@ public static IAsyncEnumerable Skip( this IAsyncEnumerable source, int count) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return source.IsKnownEmpty() ? Empty() : diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/SkipLast.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/SkipLast.cs index e6f6966e09f465..a6972a84ad6fd0 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/SkipLast.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/SkipLast.cs @@ -23,7 +23,7 @@ public static IAsyncEnumerable SkipLast( this IAsyncEnumerable source, int count) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return source.IsKnownEmpty() ? Empty() : diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/SkipWhile.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/SkipWhile.cs index a6d4f9be2d1fae..9d6b7f420ebfa2 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/SkipWhile.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/SkipWhile.cs @@ -28,8 +28,8 @@ public static IAsyncEnumerable SkipWhile( this IAsyncEnumerable source, Func predicate) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(predicate); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); return source.IsKnownEmpty() ? Empty() : @@ -77,8 +77,8 @@ public static IAsyncEnumerable SkipWhile( this IAsyncEnumerable source, Func> predicate) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(predicate); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); return source.IsKnownEmpty() ? Empty() : @@ -130,8 +130,8 @@ public static IAsyncEnumerable SkipWhile( this IAsyncEnumerable source, Func predicate) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(predicate); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); return source.IsKnownEmpty() ? Empty() : @@ -184,8 +184,8 @@ public static IAsyncEnumerable SkipWhile( this IAsyncEnumerable source, Func> predicate) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(predicate); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); return source.IsKnownEmpty() ? Empty() : diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/SumAsync.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/SumAsync.cs index 12880abd38ecbe..82f8658695583f 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/SumAsync.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/SumAsync.cs @@ -20,7 +20,7 @@ public static ValueTask SumAsync( this IAsyncEnumerable source, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return Impl(source.WithCancellation(cancellationToken)); @@ -46,7 +46,7 @@ public static ValueTask SumAsync( this IAsyncEnumerable source, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return Impl(source.WithCancellation(cancellationToken)); @@ -71,7 +71,7 @@ public static ValueTask SumAsync( this IAsyncEnumerable source, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return Impl(source.WithCancellation(cancellationToken)); @@ -96,7 +96,7 @@ public static ValueTask SumAsync( this IAsyncEnumerable source, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return Impl(source.WithCancellation(cancellationToken)); @@ -121,7 +121,7 @@ public static ValueTask SumAsync( this IAsyncEnumerable source, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return Impl(source.WithCancellation(cancellationToken)); @@ -147,7 +147,7 @@ static async ValueTask Impl( this IAsyncEnumerable source, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return Impl(source.WithCancellation(cancellationToken)); @@ -176,7 +176,7 @@ static async ValueTask Impl( this IAsyncEnumerable source, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return Impl(source.WithCancellation(cancellationToken)); @@ -204,7 +204,7 @@ static async ValueTask Impl( this IAsyncEnumerable source, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return Impl(source.WithCancellation(cancellationToken)); @@ -232,7 +232,7 @@ static async ValueTask Impl( this IAsyncEnumerable source, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return Impl(source.WithCancellation(cancellationToken)); @@ -260,7 +260,7 @@ static async ValueTask Impl( this IAsyncEnumerable source, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return Impl(source.WithCancellation(cancellationToken)); diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Take.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Take.cs index 90b654e906d3c1..e6c628d77cc20d 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Take.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Take.cs @@ -24,7 +24,7 @@ public static IAsyncEnumerable Take( this IAsyncEnumerable source, int count) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return source.IsKnownEmpty() || count <= 0 ? Empty() : @@ -61,7 +61,7 @@ public static IAsyncEnumerable Take( this IAsyncEnumerable source, Range range) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); if (source.IsKnownEmpty()) { diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/TakeLast.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/TakeLast.cs index dff268880d09a4..f813d76dd06f4a 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/TakeLast.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/TakeLast.cs @@ -16,7 +16,7 @@ public static IAsyncEnumerable TakeLast( this IAsyncEnumerable source, int count) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return source.IsKnownEmpty() || count <= 0 ? Empty() : diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/TakeWhile.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/TakeWhile.cs index beac813dd6c4d0..ce4e84e5a00789 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/TakeWhile.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/TakeWhile.cs @@ -24,8 +24,8 @@ public static IAsyncEnumerable TakeWhile( this IAsyncEnumerable source, Func predicate) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(predicate); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); return source.IsKnownEmpty() ? Empty() : @@ -61,8 +61,8 @@ public static IAsyncEnumerable TakeWhile( this IAsyncEnumerable source, Func> predicate) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(predicate); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); return source.IsKnownEmpty() ? Empty() : @@ -102,8 +102,8 @@ public static IAsyncEnumerable TakeWhile( this IAsyncEnumerable source, Func predicate) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(predicate); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); return source.IsKnownEmpty() ? Empty() : @@ -144,8 +144,8 @@ public static IAsyncEnumerable TakeWhile( this IAsyncEnumerable source, Func> predicate) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(predicate); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); return source.IsKnownEmpty() ? Empty() : diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ThrowHelper.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ThrowHelper.cs index 4937dcb51d4ef9..0043e80b88d1da 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ThrowHelper.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ThrowHelper.cs @@ -8,17 +8,6 @@ namespace System.Linq { internal static class ThrowHelper { - internal static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression(nameof(argument))] string? paramName = null) - { - if (argument is null) - { - ThrowArgumentNullException(paramName); - } - - [DoesNotReturn] - static void ThrowArgumentNullException(string? paramName) => throw new ArgumentNullException(paramName); - } - internal static void ThrowIfNegative(int value, [CallerArgumentExpression(nameof(value))] string? paramName = null) { if (value < 0) diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ToArrayAsync.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ToArrayAsync.cs index ff23ecdafe300e..f3c41db342943f 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ToArrayAsync.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ToArrayAsync.cs @@ -20,7 +20,7 @@ public static ValueTask ToArrayAsync( this IAsyncEnumerable source, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return Impl(source.WithCancellation(cancellationToken)); diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ToAsyncEnumerable.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ToAsyncEnumerable.cs index ff8b8c880a0f09..97816d9cf8e432 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ToAsyncEnumerable.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ToAsyncEnumerable.cs @@ -18,7 +18,7 @@ public static partial class AsyncEnumerable public static IAsyncEnumerable ToAsyncEnumerable( this IEnumerable source) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return source switch { diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ToDictionaryAsync.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ToDictionaryAsync.cs index 2dd0d27616f33a..669903440cf32f 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ToDictionaryAsync.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ToDictionaryAsync.cs @@ -26,7 +26,7 @@ public static ValueTask> ToDictionaryAsync? comparer = null, CancellationToken cancellationToken = default) where TKey : notnull { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return Impl(source.WithCancellation(cancellationToken), comparer); @@ -79,8 +79,8 @@ public static ValueTask> ToDictionaryAsync? comparer = null, CancellationToken cancellationToken = default) where TKey : notnull { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); return Impl(source.WithCancellation(cancellationToken), keySelector, comparer); @@ -118,8 +118,8 @@ public static ValueTask> ToDictionaryAsync? comparer = null, CancellationToken cancellationToken = default) where TKey : notnull { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); return Impl(source, keySelector, comparer, cancellationToken); @@ -162,9 +162,9 @@ public static ValueTask> ToDictionaryAsync? comparer = null, CancellationToken cancellationToken = default) where TKey : notnull { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(keySelector); - ThrowHelper.ThrowIfNull(elementSelector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(elementSelector); return Impl(source.WithCancellation(cancellationToken), keySelector, elementSelector, comparer); @@ -208,9 +208,9 @@ public static ValueTask> ToDictionaryAsync? comparer = null, CancellationToken cancellationToken = default) where TKey : notnull { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(keySelector); - ThrowHelper.ThrowIfNull(elementSelector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(elementSelector); return Impl(source, keySelector, elementSelector, comparer, cancellationToken); diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ToHashSetAsync.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ToHashSetAsync.cs index d9d0578cb78839..6a62a47c8c598e 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ToHashSetAsync.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ToHashSetAsync.cs @@ -22,7 +22,7 @@ public static ValueTask> ToHashSetAsync( IEqualityComparer? comparer = null, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return Impl(source.WithCancellation(cancellationToken), comparer); diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ToListAsync.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ToListAsync.cs index 0d95b3a5d95e78..2133f82a1ea77f 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ToListAsync.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ToListAsync.cs @@ -20,7 +20,7 @@ public static ValueTask> ToListAsync( this IAsyncEnumerable source, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(source); return Impl(source.WithCancellation(cancellationToken)); diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ToLookupAsync.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ToLookupAsync.cs index d1f63abaac9c70..491fd3a76dbf1c 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ToLookupAsync.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/ToLookupAsync.cs @@ -31,8 +31,8 @@ public static ValueTask> ToLookupAsync( IEqualityComparer? comparer = null, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); return Impl(source.WithCancellation(cancellationToken), keySelector, comparer); @@ -79,8 +79,8 @@ public static ValueTask> ToLookupAsync( IEqualityComparer? comparer = null, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); return Impl(source, keySelector, comparer, cancellationToken); @@ -131,9 +131,9 @@ public static ValueTask> ToLookupAsync? comparer = null, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(keySelector); - ThrowHelper.ThrowIfNull(elementSelector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(elementSelector); return Impl(source.WithCancellation(cancellationToken), keySelector, elementSelector, comparer); @@ -184,9 +184,9 @@ public static ValueTask> ToLookupAsync? comparer = null, CancellationToken cancellationToken = default) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(keySelector); - ThrowHelper.ThrowIfNull(elementSelector); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(elementSelector); return Impl(source, keySelector, elementSelector, comparer, cancellationToken); @@ -237,7 +237,7 @@ private sealed class EmptyLookup : ILookup, ILis public void CopyTo(IGrouping[] array, int arrayIndex) { - ThrowHelper.ThrowIfNull(array); + ArgumentNullException.ThrowIfNull(array); if ((uint)arrayIndex > (uint)array.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(nameof(arrayIndex)); diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Union.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Union.cs index 963e58aa9c9948..984b6f5e7510a4 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Union.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Union.cs @@ -23,8 +23,8 @@ public static IAsyncEnumerable Union( IAsyncEnumerable second, IEqualityComparer? comparer = null) { - ThrowHelper.ThrowIfNull(first); - ThrowHelper.ThrowIfNull(second); + ArgumentNullException.ThrowIfNull(first); + ArgumentNullException.ThrowIfNull(second); return first.IsKnownEmpty() && second.IsKnownEmpty() ? Empty() : diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/UnionBy.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/UnionBy.cs index 82aab495c5b185..e1eaadf1e56e2d 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/UnionBy.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/UnionBy.cs @@ -26,9 +26,9 @@ public static IAsyncEnumerable UnionBy( Func keySelector, IEqualityComparer? comparer = null) { - ThrowHelper.ThrowIfNull(first); - ThrowHelper.ThrowIfNull(second); - ThrowHelper.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(first); + ArgumentNullException.ThrowIfNull(second); + ArgumentNullException.ThrowIfNull(keySelector); return first.IsKnownEmpty() && second.IsKnownEmpty() ? Empty() : @@ -77,9 +77,9 @@ public static IAsyncEnumerable UnionBy( Func> keySelector, IEqualityComparer? comparer = null) { - ThrowHelper.ThrowIfNull(first); - ThrowHelper.ThrowIfNull(second); - ThrowHelper.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(first); + ArgumentNullException.ThrowIfNull(second); + ArgumentNullException.ThrowIfNull(keySelector); return first.IsKnownEmpty() && second.IsKnownEmpty() ? Empty() : diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Where.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Where.cs index e3f05f51ff1efe..240ba1c010a8a3 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Where.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Where.cs @@ -21,8 +21,8 @@ public static IAsyncEnumerable Where( // satisfies the C# quer this IAsyncEnumerable source, Func predicate) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(predicate); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); return source.IsKnownEmpty() ? Empty() : @@ -54,8 +54,8 @@ public static IAsyncEnumerable Where( this IAsyncEnumerable source, Func> predicate) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(predicate); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); return source.IsKnownEmpty() ? Empty() : @@ -93,8 +93,8 @@ public static IAsyncEnumerable Where( this IAsyncEnumerable source, Func predicate) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(predicate); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); return source.IsKnownEmpty() ? Empty() : @@ -133,8 +133,8 @@ public static IAsyncEnumerable Where( this IAsyncEnumerable source, Func> predicate) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(predicate); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); return source.IsKnownEmpty() ? Empty() : diff --git a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Zip.cs b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Zip.cs index aa04fc44607398..5fa6b5c4083628 100644 --- a/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Zip.cs +++ b/src/libraries/System.Linq.AsyncEnumerable/src/System/Linq/Zip.cs @@ -29,9 +29,9 @@ public static IAsyncEnumerable Zip( IAsyncEnumerable second, Func resultSelector) { - ThrowHelper.ThrowIfNull(first); - ThrowHelper.ThrowIfNull(second); - ThrowHelper.ThrowIfNull(resultSelector); + ArgumentNullException.ThrowIfNull(first); + ArgumentNullException.ThrowIfNull(second); + ArgumentNullException.ThrowIfNull(resultSelector); return first.IsKnownEmpty() || second.IsKnownEmpty() ? Empty() : @@ -73,9 +73,9 @@ public static IAsyncEnumerable Zip( IAsyncEnumerable second, Func> resultSelector) { - ThrowHelper.ThrowIfNull(first); - ThrowHelper.ThrowIfNull(second); - ThrowHelper.ThrowIfNull(resultSelector); + ArgumentNullException.ThrowIfNull(first); + ArgumentNullException.ThrowIfNull(second); + ArgumentNullException.ThrowIfNull(resultSelector); return first.IsKnownEmpty() || second.IsKnownEmpty() ? Empty() : @@ -110,8 +110,8 @@ await e2.MoveNextAsync()) this IAsyncEnumerable first, IAsyncEnumerable second) { - ThrowHelper.ThrowIfNull(first); - ThrowHelper.ThrowIfNull(second); + ArgumentNullException.ThrowIfNull(first); + ArgumentNullException.ThrowIfNull(second); return first.IsKnownEmpty() || second.IsKnownEmpty() ? Empty<(TFirst, TSecond)>() : @@ -149,9 +149,9 @@ await e2.MoveNextAsync()) IAsyncEnumerable second, IAsyncEnumerable third) { - ThrowHelper.ThrowIfNull(first); - ThrowHelper.ThrowIfNull(second); - ThrowHelper.ThrowIfNull(third); + ArgumentNullException.ThrowIfNull(first); + ArgumentNullException.ThrowIfNull(second); + ArgumentNullException.ThrowIfNull(third); return first.IsKnownEmpty() || second.IsKnownEmpty() || third.IsKnownEmpty() ? Empty<(TFirst, TSecond, TThird)>() : diff --git a/src/libraries/System.Linq.Expressions/tests/ILReader/ILReader.cs b/src/libraries/System.Linq.Expressions/tests/ILReader/ILReader.cs index f2131ce7740143..18c5ee944711af 100644 --- a/src/libraries/System.Linq.Expressions/tests/ILReader/ILReader.cs +++ b/src/libraries/System.Linq.Expressions/tests/ILReader/ILReader.cs @@ -181,8 +181,7 @@ private ILInstruction Next() public void Accept(ILInstructionVisitor visitor) { - if (visitor == null) - throw new ArgumentNullException("argument 'visitor' can not be null"); + ArgumentNullException.ThrowIfNull(visitor); foreach (ILInstruction instruction in this) { diff --git a/src/libraries/System.Management/src/System/Management/ManagementPath.cs b/src/libraries/System.Management/src/System/Management/ManagementPath.cs index 87907913c4e775..4a28f5e67d1187 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementPath.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementPath.cs @@ -1105,10 +1105,7 @@ public override bool CanConvertTo(ITypeDescriptorContext context, Type destinati public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) - { - throw new ArgumentNullException(nameof(destinationType)); - } + ArgumentNullException.ThrowIfNull(destinationType); if (value is ManagementPath && destinationType == typeof(InstanceDescriptor)) { diff --git a/src/libraries/System.Management/src/System/Management/ManagementQuery.cs b/src/libraries/System.Management/src/System/Management/ManagementQuery.cs index 4cc54855c7044e..b033e76d8c50b6 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementQuery.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementQuery.cs @@ -3218,10 +3218,7 @@ public override bool CanConvertTo(ITypeDescriptorContext context, Type destinati public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) - { - throw new ArgumentNullException(nameof(destinationType)); - } + ArgumentNullException.ThrowIfNull(destinationType); if (value is EventQuery && destinationType == typeof(InstanceDescriptor)) { diff --git a/src/libraries/System.Management/src/System/Management/ManagementScope.cs b/src/libraries/System.Management/src/System/Management/ManagementScope.cs index 84f3491f414ff3..b0944fac8a9c53 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementScope.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementScope.cs @@ -1513,10 +1513,7 @@ public override bool CanConvertTo(ITypeDescriptorContext context, Type destinati public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) - { - throw new ArgumentNullException(nameof(destinationType)); - } + ArgumentNullException.ThrowIfNull(destinationType); if (value is ManagementScope && destinationType == typeof(InstanceDescriptor)) { diff --git a/src/libraries/System.Memory.Data/src/System/BinaryData.cs b/src/libraries/System.Memory.Data/src/System/BinaryData.cs index dbe55a353bac83..b1fe9b2b0a8880 100644 --- a/src/libraries/System.Memory.Data/src/System/BinaryData.cs +++ b/src/libraries/System.Memory.Data/src/System/BinaryData.cs @@ -139,10 +139,7 @@ public BinaryData(ReadOnlyMemory data, string? mediaType) : this(data) /// The string data. public BinaryData(string data) { - if (data is null) - { - throw new ArgumentNullException(nameof(data)); - } + ArgumentNullException.ThrowIfNull(data); _bytes = Encoding.UTF8.GetBytes(data); } @@ -238,10 +235,7 @@ public static BinaryData FromString(string data, string? mediaType) /// public static BinaryData FromStream(Stream stream, string? mediaType) { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } + ArgumentNullException.ThrowIfNull(stream); return FromStreamAsync(stream, useAsync: false, mediaType).GetAwaiter().GetResult(); } @@ -269,10 +263,7 @@ public static Task FromStreamAsync(Stream stream, CancellationToken public static Task FromStreamAsync(Stream stream, string? mediaType, CancellationToken cancellationToken = default) { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } + ArgumentNullException.ThrowIfNull(stream); return FromStreamAsync(stream, useAsync: true, mediaType, cancellationToken); } @@ -332,10 +323,7 @@ private static async Task FromStreamAsync(Stream stream, bool useAsy /// public static BinaryData FromFile(string path, string? mediaType) { - if (path is null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullException.ThrowIfNull(path); return new BinaryData(File.ReadAllBytes(path), mediaType); } @@ -361,10 +349,7 @@ public static Task FromFileAsync(string path, CancellationToken canc public static Task FromFileAsync(string path, string? mediaType, CancellationToken cancellationToken = default) { - if (path is null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullException.ThrowIfNull(path); return Core(); diff --git a/src/libraries/System.Net.Http.Json/src/System.Net.Http.Json.csproj b/src/libraries/System.Net.Http.Json/src/System.Net.Http.Json.csproj index b8908f4fde1c7d..5c5bdb02fc1966 100644 --- a/src/libraries/System.Net.Http.Json/src/System.Net.Http.Json.csproj +++ b/src/libraries/System.Net.Http.Json/src/System.Net.Http.Json.csproj @@ -13,8 +13,6 @@ System.Net.Http.Json.JsonContent - diff --git a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Get.AsyncEnumerable.cs b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Get.AsyncEnumerable.cs index 95f67291c131b7..bb0df6dd250e32 100644 --- a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Get.AsyncEnumerable.cs +++ b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Get.AsyncEnumerable.cs @@ -146,10 +146,7 @@ public static partial class HttpClientJsonExtensions JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken) { - if (client is null) - { - throw new ArgumentNullException(nameof(client)); - } + ArgumentNullException.ThrowIfNull(client); return Core(client, requestUri, jsonTypeInfo, cancellationToken); diff --git a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Patch.cs b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Patch.cs index 4ed1ed590f3b46..b3ba32a70af6dd 100644 --- a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Patch.cs +++ b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Patch.cs @@ -26,10 +26,7 @@ public static partial class HttpClientJsonExtensions [RequiresDynamicCode(HttpContentJsonExtensions.SerializationDynamicCodeMessage)] public static Task PatchAsJsonAsync(this HttpClient client, [StringSyntax(StringSyntaxAttribute.Uri)] string? requestUri, TValue value, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { - if (client is null) - { - throw new ArgumentNullException(nameof(client)); - } + ArgumentNullException.ThrowIfNull(client); JsonContent content = JsonContent.Create(value, mediaType: null, options); return client.PatchAsync(requestUri, content, cancellationToken); @@ -50,10 +47,7 @@ public static Task PatchAsJsonAsync(this HttpClient [RequiresDynamicCode(HttpContentJsonExtensions.SerializationDynamicCodeMessage)] public static Task PatchAsJsonAsync(this HttpClient client, Uri? requestUri, TValue value, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { - if (client is null) - { - throw new ArgumentNullException(nameof(client)); - } + ArgumentNullException.ThrowIfNull(client); JsonContent content = JsonContent.Create(value, mediaType: null, options); return client.PatchAsync(requestUri, content, cancellationToken); @@ -102,10 +96,7 @@ public static Task PatchAsJsonAsync(this HttpClient /// The is null. public static Task PatchAsJsonAsync(this HttpClient client, [StringSyntax(StringSyntaxAttribute.Uri)] string? requestUri, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) { - if (client is null) - { - throw new ArgumentNullException(nameof(client)); - } + ArgumentNullException.ThrowIfNull(client); JsonContent content = JsonContent.Create(value, jsonTypeInfo); return client.PatchAsync(requestUri, content, cancellationToken); @@ -124,10 +115,7 @@ public static Task PatchAsJsonAsync(this HttpClient /// The is null. public static Task PatchAsJsonAsync(this HttpClient client, Uri? requestUri, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) { - if (client is null) - { - throw new ArgumentNullException(nameof(client)); - } + ArgumentNullException.ThrowIfNull(client); JsonContent content = JsonContent.Create(value, jsonTypeInfo); return client.PatchAsync(requestUri, content, cancellationToken); diff --git a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Post.cs b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Post.cs index ec559ef34ae95d..c2eececcc2b700 100644 --- a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Post.cs +++ b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Post.cs @@ -15,10 +15,7 @@ public static partial class HttpClientJsonExtensions [RequiresDynamicCode(HttpContentJsonExtensions.SerializationDynamicCodeMessage)] public static Task PostAsJsonAsync(this HttpClient client, [StringSyntax(StringSyntaxAttribute.Uri)] string? requestUri, TValue value, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { - if (client is null) - { - throw new ArgumentNullException(nameof(client)); - } + ArgumentNullException.ThrowIfNull(client); JsonContent content = JsonContent.Create(value, mediaType: null, options); return client.PostAsync(requestUri, content, cancellationToken); @@ -28,10 +25,7 @@ public static Task PostAsJsonAsync(this HttpClient [RequiresDynamicCode(HttpContentJsonExtensions.SerializationDynamicCodeMessage)] public static Task PostAsJsonAsync(this HttpClient client, Uri? requestUri, TValue value, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { - if (client is null) - { - throw new ArgumentNullException(nameof(client)); - } + ArgumentNullException.ThrowIfNull(client); JsonContent content = JsonContent.Create(value, mediaType: null, options); return client.PostAsync(requestUri, content, cancellationToken); @@ -49,10 +43,7 @@ public static Task PostAsJsonAsync(this HttpClient public static Task PostAsJsonAsync(this HttpClient client, [StringSyntax(StringSyntaxAttribute.Uri)] string? requestUri, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) { - if (client is null) - { - throw new ArgumentNullException(nameof(client)); - } + ArgumentNullException.ThrowIfNull(client); JsonContent content = JsonContent.Create(value, jsonTypeInfo); return client.PostAsync(requestUri, content, cancellationToken); @@ -60,10 +51,7 @@ public static Task PostAsJsonAsync(this HttpClient public static Task PostAsJsonAsync(this HttpClient client, Uri? requestUri, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) { - if (client is null) - { - throw new ArgumentNullException(nameof(client)); - } + ArgumentNullException.ThrowIfNull(client); JsonContent content = JsonContent.Create(value, jsonTypeInfo); return client.PostAsync(requestUri, content, cancellationToken); diff --git a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Put.cs b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Put.cs index 5a6dab9f00dca5..803e8ed0635b65 100644 --- a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Put.cs +++ b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Put.cs @@ -15,10 +15,7 @@ public static partial class HttpClientJsonExtensions [RequiresDynamicCode(HttpContentJsonExtensions.SerializationDynamicCodeMessage)] public static Task PutAsJsonAsync(this HttpClient client, [StringSyntax(StringSyntaxAttribute.Uri)] string? requestUri, TValue value, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { - if (client is null) - { - throw new ArgumentNullException(nameof(client)); - } + ArgumentNullException.ThrowIfNull(client); JsonContent content = JsonContent.Create(value, mediaType: null, options); return client.PutAsync(requestUri, content, cancellationToken); @@ -28,10 +25,7 @@ public static Task PutAsJsonAsync(this HttpClient c [RequiresDynamicCode(HttpContentJsonExtensions.SerializationDynamicCodeMessage)] public static Task PutAsJsonAsync(this HttpClient client, Uri? requestUri, TValue value, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { - if (client is null) - { - throw new ArgumentNullException(nameof(client)); - } + ArgumentNullException.ThrowIfNull(client); JsonContent content = JsonContent.Create(value, mediaType: null, options); return client.PutAsync(requestUri, content, cancellationToken); @@ -49,10 +43,7 @@ public static Task PutAsJsonAsync(this HttpClient c public static Task PutAsJsonAsync(this HttpClient client, [StringSyntax(StringSyntaxAttribute.Uri)] string? requestUri, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) { - if (client is null) - { - throw new ArgumentNullException(nameof(client)); - } + ArgumentNullException.ThrowIfNull(client); JsonContent content = JsonContent.Create(value, jsonTypeInfo); return client.PutAsync(requestUri, content, cancellationToken); @@ -60,10 +51,7 @@ public static Task PutAsJsonAsync(this HttpClient c public static Task PutAsJsonAsync(this HttpClient client, Uri? requestUri, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) { - if (client is null) - { - throw new ArgumentNullException(nameof(client)); - } + ArgumentNullException.ThrowIfNull(client); JsonContent content = JsonContent.Create(value, jsonTypeInfo); return client.PutAsync(requestUri, content, cancellationToken); diff --git a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.cs b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.cs index 4223cf3e064109..2c83e0f437e7d7 100644 --- a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.cs +++ b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.cs @@ -38,10 +38,7 @@ public static partial class HttpClientJsonExtensions TJsonOptions jsonOptions, CancellationToken cancellationToken) { - if (client is null) - { - throw new ArgumentNullException(nameof(client)); - } + ArgumentNullException.ThrowIfNull(client); TimeSpan timeout = client.Timeout; diff --git a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpContentJsonExtensions.AsyncEnumerable.cs b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpContentJsonExtensions.AsyncEnumerable.cs index ffe778352b9cb5..ca3b0cf0780c19 100644 --- a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpContentJsonExtensions.AsyncEnumerable.cs +++ b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpContentJsonExtensions.AsyncEnumerable.cs @@ -52,10 +52,7 @@ public static partial class HttpContentJsonExtensions JsonSerializerOptions? options, CancellationToken cancellationToken = default) { - if (content is null) - { - throw new ArgumentNullException(nameof(content)); - } + ArgumentNullException.ThrowIfNull(content); return ReadFromJsonAsAsyncEnumerableCore(content, options, cancellationToken); } @@ -77,10 +74,7 @@ public static partial class HttpContentJsonExtensions JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) { - if (content is null) - { - throw new ArgumentNullException(nameof(content)); - } + ArgumentNullException.ThrowIfNull(content); return ReadFromJsonAsAsyncEnumerableCore(content, jsonTypeInfo, cancellationToken); } diff --git a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpContentJsonExtensions.cs b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpContentJsonExtensions.cs index decdc125b7f750..e50715859e6fe3 100644 --- a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpContentJsonExtensions.cs +++ b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpContentJsonExtensions.cs @@ -29,10 +29,7 @@ public static partial class HttpContentJsonExtensions [RequiresDynamicCode(SerializationDynamicCodeMessage)] public static Task ReadFromJsonAsync(this HttpContent content, Type type, JsonSerializerOptions? options, CancellationToken cancellationToken = default) { - if (content is null) - { - throw new ArgumentNullException(nameof(content)); - } + ArgumentNullException.ThrowIfNull(content); return ReadFromJsonAsyncCore(content, type, options, cancellationToken); } @@ -63,10 +60,7 @@ public static partial class HttpContentJsonExtensions [RequiresDynamicCode(SerializationDynamicCodeMessage)] public static Task ReadFromJsonAsync(this HttpContent content, JsonSerializerOptions? options, CancellationToken cancellationToken = default) { - if (content is null) - { - throw new ArgumentNullException(nameof(content)); - } + ArgumentNullException.ThrowIfNull(content); return ReadFromJsonAsyncCore(content, options, cancellationToken); } @@ -107,20 +101,14 @@ public static partial class HttpContentJsonExtensions public static Task ReadFromJsonAsync(this HttpContent content, Type type, JsonSerializerContext context, CancellationToken cancellationToken = default) { - if (content is null) - { - throw new ArgumentNullException(nameof(content)); - } + ArgumentNullException.ThrowIfNull(content); return ReadFromJsonAsyncCore(content, type, context, cancellationToken); } public static Task ReadFromJsonAsync(this HttpContent content, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) { - if (content is null) - { - throw new ArgumentNullException(nameof(content)); - } + ArgumentNullException.ThrowIfNull(content); return ReadFromJsonAsyncCore(content, jsonTypeInfo, cancellationToken); } diff --git a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/JsonContent.cs b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/JsonContent.cs index f568ef2f684ac0..b9c53b672fffc8 100644 --- a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/JsonContent.cs +++ b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/JsonContent.cs @@ -65,7 +65,7 @@ public static JsonContent Create(T inputValue, MediaTypeHeaderValue? mediaTyp [RequiresDynamicCode(HttpContentJsonExtensions.SerializationDynamicCodeMessage)] public static JsonContent Create(object? inputValue, Type inputType, MediaTypeHeaderValue? mediaType = null, JsonSerializerOptions? options = null) { - ThrowHelper.ThrowIfNull(inputType); + ArgumentNullException.ThrowIfNull(inputType); EnsureTypeCompatibility(inputValue, inputType); return new JsonContent(inputValue, JsonHelpers.GetJsonTypeInfo(inputType, options), mediaType); @@ -81,7 +81,7 @@ public static JsonContent Create(object? inputValue, Type inputType, MediaTypeHe /// A instance. public static JsonContent Create(T? inputValue, JsonTypeInfo jsonTypeInfo, MediaTypeHeaderValue? mediaType = null) { - ThrowHelper.ThrowIfNull(jsonTypeInfo); + ArgumentNullException.ThrowIfNull(jsonTypeInfo); return new JsonContent(inputValue, jsonTypeInfo, mediaType); } @@ -95,7 +95,7 @@ public static JsonContent Create(T? inputValue, JsonTypeInfo jsonTypeInfo, /// A instance. public static JsonContent Create(object? inputValue, JsonTypeInfo jsonTypeInfo, MediaTypeHeaderValue? mediaType = null) { - ThrowHelper.ThrowIfNull(jsonTypeInfo); + ArgumentNullException.ThrowIfNull(jsonTypeInfo); EnsureTypeCompatibility(inputValue, jsonTypeInfo.Type); return new JsonContent(inputValue, jsonTypeInfo, mediaType); diff --git a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpHandler.cs b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpHandler.cs index 88869ac7b98cb9..a3bf24e9c4f150 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpHandler.cs +++ b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpHandler.cs @@ -594,10 +594,7 @@ protected override Task SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { - if (request is null) - { - throw new ArgumentNullException(nameof(request)); - } + ArgumentNullException.ThrowIfNull(request); Uri? requestUri = request.RequestUri; if (requestUri is null || !requestUri.IsAbsoluteUri) diff --git a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestStream.cs b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestStream.cs index 64288c537fa674..6c97ed0b102602 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestStream.cs +++ b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestStream.cs @@ -97,10 +97,7 @@ public override Task FlushAsync(CancellationToken cancellationToken) public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken token) { - if (buffer is null) - { - throw new ArgumentNullException(nameof(buffer)); - } + ArgumentNullException.ThrowIfNull(buffer); if (offset < 0) { diff --git a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpResponseStream.cs b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpResponseStream.cs index 97b7ec64ec0408..418f65128eb081 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpResponseStream.cs +++ b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpResponseStream.cs @@ -171,10 +171,7 @@ private async Task CopyToAsyncCore(Stream destination, byte[] buffer, Cancellati public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken token) { - if (buffer is null) - { - throw new ArgumentNullException(nameof(buffer)); - } + ArgumentNullException.ThrowIfNull(buffer); if (offset < 0) { diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/BrowserHttpHandler/BrowserHttpHandler.cs b/src/libraries/System.Net.Http/src/System/Net/Http/BrowserHttpHandler/BrowserHttpHandler.cs index b2e73bc1cef364..8cea5b3fe2d182 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/BrowserHttpHandler/BrowserHttpHandler.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/BrowserHttpHandler/BrowserHttpHandler.cs @@ -487,7 +487,7 @@ protected override Task SerializeToStreamAsync(Stream stream, TransportContext? protected override async Task SerializeToStreamAsync(Stream stream, TransportContext? context, CancellationToken cancellationToken) { - ArgumentNullException.ThrowIfNull(stream, nameof(stream)); + ArgumentNullException.ThrowIfNull(stream); byte[] data = await GetResponseData(cancellationToken).ConfigureAwait(false); await stream.WriteAsync(data, cancellationToken).ConfigureAwait(false); diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Tasks.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Tasks.cs index 4c0ab4799504a9..ba8aa0aff49648 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Tasks.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Tasks.cs @@ -434,7 +434,7 @@ public ValueTask ReceiveFromAsync(Memory buffer, public ValueTask ReceiveFromAsync(Memory buffer, SocketFlags socketFlags, SocketAddress receivedAddress, CancellationToken cancellationToken = default) { ThrowIfDisposed(); - ArgumentNullException.ThrowIfNull(receivedAddress, nameof(receivedAddress)); + ArgumentNullException.ThrowIfNull(receivedAddress); if (receivedAddress.Size < SocketAddress.GetMaximumAddressSize(AddressFamily)) { 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 f6918bbcf46653..bd7ba1a90b770e 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 @@ -2015,7 +2015,7 @@ public int ReceiveFrom(Span buffer, SocketFlags socketFlags, SocketAddress if (!Socket.OSSupportsThreads) throw new PlatformNotSupportedException(); // TODO remove with https://github.com/dotnet/runtime/pull/107185 ThrowIfDisposed(); - ArgumentNullException.ThrowIfNull(receivedAddress, nameof(receivedAddress)); + ArgumentNullException.ThrowIfNull(receivedAddress); if (receivedAddress.Size < SocketAddress.GetMaximumAddressSize(AddressFamily)) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/ICollectionDebugView.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/ICollectionDebugView.cs index 5be0acf724fff8..4e58fc58b20265 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/ICollectionDebugView.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/ICollectionDebugView.cs @@ -11,14 +11,7 @@ internal sealed class ICollectionDebugView public ICollectionDebugView(ICollection collection) { -#if NET ArgumentNullException.ThrowIfNull(collection); -#else - if (collection is null) - { - throw new ArgumentNullException(nameof(collection)); - } -#endif _collection = collection; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/ObjectModel/CollectionHelpers.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/ObjectModel/CollectionHelpers.cs index 3896ea5543561a..d3b9f1f19f5275 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/ObjectModel/CollectionHelpers.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/ObjectModel/CollectionHelpers.cs @@ -12,10 +12,7 @@ internal static void ValidateCopyToArguments(int sourceCount, Array array, int i #if NET8_0_OR_GREATER ArgumentNullException.ThrowIfNull(array); #else - if (array is null) - { - throw new ArgumentNullException(nameof(array)); - } + ArgumentNullException.ThrowIfNull(array); #endif if (array.Rank != 1) diff --git a/src/libraries/System.Private.CoreLib/src/System/Numerics/TotalOrderIeee754Comparer.cs b/src/libraries/System.Private.CoreLib/src/System/Numerics/TotalOrderIeee754Comparer.cs index dca39f67536041..1fb20bb983da5d 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Numerics/TotalOrderIeee754Comparer.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Numerics/TotalOrderIeee754Comparer.cs @@ -220,7 +220,7 @@ static int CompareSignificand(T x, T y) /// A hash code for the specified number. public int GetHashCode([DisallowNull] T obj) { - ArgumentNullException.ThrowIfNull(obj, nameof(obj)); + ArgumentNullException.ThrowIfNull(obj); return obj.GetHashCode(); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/ConstructorInvoker.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/ConstructorInvoker.cs index 47766e9428f44b..ab5f4132c23a0e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/ConstructorInvoker.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/ConstructorInvoker.cs @@ -48,7 +48,7 @@ public sealed partial class ConstructorInvoker /// public static ConstructorInvoker Create(ConstructorInfo constructor) { - ArgumentNullException.ThrowIfNull(constructor, nameof(constructor)); + ArgumentNullException.ThrowIfNull(constructor); if (constructor is not RuntimeConstructorInfo runtimeConstructor) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/MethodInvoker.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/MethodInvoker.cs index d7d8ff6e01d98b..09eddfa31f5112 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/MethodInvoker.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/MethodInvoker.cs @@ -50,7 +50,7 @@ public sealed partial class MethodInvoker /// public static MethodInvoker Create(MethodBase method) { - ArgumentNullException.ThrowIfNull(method, nameof(method)); + ArgumentNullException.ThrowIfNull(method); if (method is RuntimeMethodInfo rmi) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/NullabilityInfoContext.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/NullabilityInfoContext.cs index fd279a70fbbb6c..ecd60f5dece554 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/NullabilityInfoContext.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/NullabilityInfoContext.cs @@ -67,11 +67,8 @@ private enum NotAnnotatedStatus /// public NullabilityInfo Create(ParameterInfo parameterInfo) { -#if NET ArgumentNullException.ThrowIfNull(parameterInfo); -#else - NetstandardHelpers.ThrowIfNull(parameterInfo, nameof(parameterInfo)); -#endif + IList attributes = parameterInfo.GetCustomAttributesData(); NullableAttributeStateParser parser = parameterInfo.Member is MethodBase method && IsPrivateOrInternalMethodAndAnnotationDisabled(method) ? NullableAttributeStateParser.Unknown @@ -193,11 +190,8 @@ private static void CheckNullabilityAttributes(NullabilityInfo nullability, ILis /// public NullabilityInfo Create(PropertyInfo propertyInfo) { -#if NET ArgumentNullException.ThrowIfNull(propertyInfo); -#else - NetstandardHelpers.ThrowIfNull(propertyInfo, nameof(propertyInfo)); -#endif + MethodInfo? getter = propertyInfo.GetGetMethod(true); MethodInfo? setter = propertyInfo.GetSetMethod(true); bool annotationsDisabled = (getter == null || IsPrivateOrInternalMethodAndAnnotationDisabled(getter)) @@ -249,11 +243,8 @@ private bool IsPrivateOrInternalMethodAndAnnotationDisabled(MethodBase method) /// public NullabilityInfo Create(EventInfo eventInfo) { -#if NET ArgumentNullException.ThrowIfNull(eventInfo); -#else - NetstandardHelpers.ThrowIfNull(eventInfo, nameof(eventInfo)); -#endif + return GetNullabilityInfo(eventInfo, eventInfo.EventHandlerType!, CreateParser(eventInfo.GetCustomAttributesData())); } @@ -267,11 +258,8 @@ public NullabilityInfo Create(EventInfo eventInfo) /// public NullabilityInfo Create(FieldInfo fieldInfo) { -#if NET ArgumentNullException.ThrowIfNull(fieldInfo); -#else - NetstandardHelpers.ThrowIfNull(fieldInfo, nameof(fieldInfo)); -#endif + IList attributes = fieldInfo.GetCustomAttributesData(); NullableAttributeStateParser parser = IsPrivateOrInternalFieldAndAnnotationDisabled(fieldInfo) ? NullableAttributeStateParser.Unknown : CreateParser(attributes); NullabilityInfo nullability = GetNullabilityInfo(fieldInfo, fieldInfo.FieldType, parser); @@ -679,21 +667,12 @@ public bool ParseNullableState(int index, ref NullabilityState state) #if !NET internal static class NetstandardHelpers { - public static void ThrowIfNull(object? argument, string paramName) - { - if (argument is null) - { - Throw(paramName); - static void Throw(string paramName) => throw new ArgumentNullException(paramName); - } - } - [Diagnostics.CodeAnalysis.UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:UnrecognizedReflectionPattern", Justification = "This is finding the MemberInfo with the same MetadataToken as specified MemberInfo. If the specified MemberInfo " + "exists and wasn't trimmed, then the current Type's MemberInfo couldn't have been trimmed.")] public static MemberInfo GetMemberWithSameMetadataDefinitionAs(this Type type, MemberInfo member) { - ThrowIfNull(member, nameof(member)); + ArgumentNullException.ThrowIfNull(member); const BindingFlags all = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance; foreach (MemberInfo myMemberInfo in type.GetMembers(all)) diff --git a/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceReader.cs b/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceReader.cs index af37166b8cb2ac..0be356e870a453 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceReader.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceReader.cs @@ -119,10 +119,7 @@ public sealed partial class #endif { #if RESOURCES_EXTENSIONS - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } + ArgumentNullException.ThrowIfNull(stream); #else ArgumentNullException.ThrowIfNull(stream); #endif diff --git a/src/libraries/System.Private.CoreLib/src/System/Resources/RuntimeResourceSet.cs b/src/libraries/System.Private.CoreLib/src/System/Resources/RuntimeResourceSet.cs index 809fbe55a8fd47..ae7ed13658751c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Resources/RuntimeResourceSet.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Resources/RuntimeResourceSet.cs @@ -192,10 +192,7 @@ internal RuntimeResourceSet(IResourceReader reader) : // the purpose of RuntimeResourceSet is to lazily load and cache. base() { - if (reader is null) - { - throw new ArgumentNullException(nameof(reader)); - } + ArgumentNullException.ThrowIfNull(reader); _defaultReader = reader as DeserializingResourceReader ?? throw new ArgumentException(SR.Format(SR.NotSupported_WrongResourceReader_Type, reader.GetType()), nameof(reader)); @@ -266,10 +263,7 @@ private IDictionaryEnumerator GetEnumeratorHelper() private object? GetObject(string key, bool ignoreCase, bool isString) { #if RESOURCES_EXTENSIONS - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); #else ArgumentNullException.ThrowIfNull(key); #endif diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/CustomReflectionContext.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/CustomReflectionContext.cs index 8c94051b44be83..eee744a706b38f 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/CustomReflectionContext.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/CustomReflectionContext.cs @@ -22,10 +22,7 @@ protected CustomReflectionContext() : this(new IdentityReflectionContext()) { } protected CustomReflectionContext(ReflectionContext source) { - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } + ArgumentNullException.ThrowIfNull(source); SourceContext = source; _projector = new ReflectionContextProjector(this); @@ -33,20 +30,14 @@ protected CustomReflectionContext(ReflectionContext source) public override Assembly MapAssembly(Assembly assembly) { - if (assembly is null) - { - throw new ArgumentNullException(nameof(assembly)); - } + ArgumentNullException.ThrowIfNull(assembly); return _projector.ProjectAssemblyIfNeeded(assembly); } public override TypeInfo MapType(TypeInfo type) { - if (type is null) - { - throw new ArgumentNullException(nameof(type)); - } + ArgumentNullException.ThrowIfNull(type); return _projector.ProjectTypeIfNeeded(type); } diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualParameter.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualParameter.cs index a719de60a3f789..27a2940478f061 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualParameter.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualParameter.cs @@ -10,14 +10,8 @@ internal class VirtualParameter : ParameterInfo { public VirtualParameter(MemberInfo member, Type parameterType, string? name, int position) { - if (member is null) - { - throw new ArgumentNullException(nameof(member)); - } - if (parameterType is null) - { - throw new ArgumentNullException(nameof(parameterType)); - } + ArgumentNullException.ThrowIfNull(member); + ArgumentNullException.ThrowIfNull(parameterType); Debug.Assert(position >= -1); diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualPropertyBase.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualPropertyBase.cs index 772f2d102a5da2..7720bf06884a25 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualPropertyBase.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualPropertyBase.cs @@ -17,8 +17,7 @@ internal abstract partial class VirtualPropertyBase : PropertyInfo protected VirtualPropertyBase(Type propertyType, string name, CustomReflectionContext context) { - if (name is null) - throw new ArgumentNullException(nameof(name)); + ArgumentNullException.ThrowIfNull(name); if (name.Length == 0) throw new ArgumentException("", nameof(name)); diff --git a/src/libraries/System.Reflection.Emit/src/System/Reflection/Emit/MethodBuilderImpl.cs b/src/libraries/System.Reflection.Emit/src/System/Reflection/Emit/MethodBuilderImpl.cs index 5881f753eb8fe5..4e189b30c9abcf 100644 --- a/src/libraries/System.Reflection.Emit/src/System/Reflection/Emit/MethodBuilderImpl.cs +++ b/src/libraries/System.Reflection.Emit/src/System/Reflection/Emit/MethodBuilderImpl.cs @@ -121,7 +121,7 @@ protected override GenericTypeParameterBuilder[] DefineGenericParametersCore(par for (int i = 0; i < names.Length; i++) { string name = names[i]; - ArgumentNullException.ThrowIfNull(names, nameof(names)); + ArgumentNullException.ThrowIfNull(names); typeParameters[i] = new GenericTypeParameterBuilderImpl(name, i, this, _declaringType); } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/InstructionEncoder.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/InstructionEncoder.cs index 18ff0fd9d1947d..c6491a6dec9573 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/InstructionEncoder.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/InstructionEncoder.cs @@ -34,10 +34,7 @@ public readonly struct InstructionEncoder /// public InstructionEncoder(BlobBuilder codeBuilder, ControlFlowBuilder? controlFlowBuilder = null) { - if (codeBuilder == null) - { - Throw.BuilderArgumentNull(); - } + ArgumentNullException.ThrowIfNull(codeBuilder); CodeBuilder = codeBuilder; ControlFlowBuilder = controlFlowBuilder; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/MethodBodyStreamEncoder.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/MethodBodyStreamEncoder.cs index 9ec51718c76190..f12fb2ed96d4bb 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/MethodBodyStreamEncoder.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/MethodBodyStreamEncoder.cs @@ -12,10 +12,7 @@ public readonly struct MethodBodyStreamEncoder public MethodBodyStreamEncoder(BlobBuilder builder) { - if (builder == null) - { - Throw.BuilderArgumentNull(); - } + ArgumentNullException.ThrowIfNull(builder); // Fat methods are 4-byte aligned. We calculate the alignment relative to the start of the ILStream. // diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataStringComparer.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataStringComparer.cs index 97c68fff88a7b2..20f929259a63d5 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataStringComparer.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataStringComparer.cs @@ -62,10 +62,7 @@ public bool Equals(StringHandle handle, string value) public bool Equals(StringHandle handle, string value, bool ignoreCase) { - if (value == null) - { - Throw.ValueArgumentNull(); - } + ArgumentNullException.ThrowIfNull(value); return _reader.StringHeap.Equals(handle, value, _reader.UTF8Decoder, ignoreCase); } @@ -77,10 +74,7 @@ public bool Equals(NamespaceDefinitionHandle handle, string value) public bool Equals(NamespaceDefinitionHandle handle, string value, bool ignoreCase) { - if (value == null) - { - Throw.ValueArgumentNull(); - } + ArgumentNullException.ThrowIfNull(value); if (handle.HasFullName) { @@ -97,10 +91,7 @@ public bool Equals(DocumentNameBlobHandle handle, string value) public bool Equals(DocumentNameBlobHandle handle, string value, bool ignoreCase) { - if (value == null) - { - Throw.ValueArgumentNull(); - } + ArgumentNullException.ThrowIfNull(value); return _reader.BlobHeap.DocumentNameEquals(handle, value, ignoreCase); } @@ -112,10 +103,7 @@ public bool StartsWith(StringHandle handle, string value) public bool StartsWith(StringHandle handle, string value, bool ignoreCase) { - if (value == null) - { - Throw.ValueArgumentNull(); - } + ArgumentNullException.ThrowIfNull(value); return _reader.StringHeap.StartsWith(handle, value, _reader.UTF8Decoder, ignoreCase); } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Throw.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Throw.cs index ff98271852d0cb..19a9a9cacd0ad9 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Throw.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Throw.cs @@ -113,18 +113,6 @@ internal static void ArgumentEmptyArray(string parameterName) throw new ArgumentException(SR.ExpectedNonEmptyArray, parameterName); } - [DoesNotReturn] - internal static void ValueArgumentNull() - { - throw new ArgumentNullException("value"); - } - - [DoesNotReturn] - internal static void BuilderArgumentNull() - { - throw new ArgumentNullException("builder"); - } - [DoesNotReturn] internal static void ArgumentOutOfRange(string parameterName) { diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/DefaultBinder.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/DefaultBinder.cs index 10501e11c4a4ac..c45b91feb699ee 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/DefaultBinder.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/DefaultBinder.cs @@ -273,10 +273,7 @@ public sealed override MethodBase BindToMethod( // Binder and is used by RuntimeType.) public static MethodBase? ExactBinding(MethodBase[] match, Type[] types) { - if (match is null) - { - throw new ArgumentNullException(nameof(match)); - } + ArgumentNullException.ThrowIfNull(match); MethodBase[] aExactMatches = new MethodBase[match.Length]; int cExactMatches = 0; @@ -318,10 +315,7 @@ public sealed override MethodBase BindToMethod( // Binder and is used by RuntimeType.) public static PropertyInfo? ExactPropertyBinding(PropertyInfo[] match, Type? returnType, Type[]? types) { - if (match is null) - { - throw new ArgumentNullException(nameof(match)); - } + ArgumentNullException.ThrowIfNull(match); PropertyInfo? bestMatch = null; int typesLength = (types != null) ? types.Length : 0; diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/MetadataLoadContext.Apis.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/MetadataLoadContext.Apis.cs index ad402f70be35dd..425be1dc7d0b34 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/MetadataLoadContext.Apis.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/MetadataLoadContext.Apis.cs @@ -105,8 +105,7 @@ public sealed partial class MetadataLoadContext : IDisposable /// public MetadataLoadContext(MetadataAssemblyResolver resolver, string? coreAssemblyName = null) { - if (resolver is null) - throw new ArgumentNullException(nameof(resolver)); + ArgumentNullException.ThrowIfNull(resolver); this.resolver = resolver; @@ -127,8 +126,7 @@ public MetadataLoadContext(MetadataAssemblyResolver resolver, string? coreAssemb /// public Assembly LoadFromAssemblyPath(string assemblyPath) { - if (assemblyPath is null) - throw new ArgumentNullException(nameof(assemblyPath)); + ArgumentNullException.ThrowIfNull(assemblyPath); if (IsDisposed) throw new ObjectDisposedException(nameof(MetadataLoadContext)); @@ -142,8 +140,7 @@ public Assembly LoadFromAssemblyPath(string assemblyPath) /// public Assembly LoadFromByteArray(byte[] assembly) { - if (assembly is null) - throw new ArgumentNullException(nameof(assembly)); + ArgumentNullException.ThrowIfNull(assembly); if (IsDisposed) throw new ObjectDisposedException(nameof(MetadataLoadContext)); @@ -160,8 +157,7 @@ public Assembly LoadFromByteArray(byte[] assembly) /// public Assembly LoadFromStream(Stream assembly) { - if (assembly is null) - throw new ArgumentNullException(nameof(assembly)); + ArgumentNullException.ThrowIfNull(assembly); if (IsDisposed) throw new ObjectDisposedException(nameof(MetadataLoadContext)); @@ -178,8 +174,7 @@ public Assembly LoadFromStream(Stream assembly) /// public Assembly LoadFromAssemblyName(string assemblyName) { - if (assemblyName is null) - throw new ArgumentNullException(nameof(assemblyName)); + ArgumentNullException.ThrowIfNull(assemblyName); if (IsDisposed) throw new ObjectDisposedException(nameof(MetadataLoadContext)); @@ -197,8 +192,7 @@ public Assembly LoadFromAssemblyName(string assemblyName) /// public Assembly LoadFromAssemblyName(AssemblyName assemblyName) { - if (assemblyName is null) - throw new ArgumentNullException(nameof(assemblyName)); + ArgumentNullException.ThrowIfNull(assemblyName); if (IsDisposed) throw new ObjectDisposedException(nameof(MetadataLoadContext)); diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/PathAssemblyResolver.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/PathAssemblyResolver.cs index 095f5ad9586393..f9610a7115e155 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/PathAssemblyResolver.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/PathAssemblyResolver.cs @@ -31,8 +31,7 @@ public class PathAssemblyResolver : MetadataAssemblyResolver /// Thrown when a path is invalid. public PathAssemblyResolver(IEnumerable assemblyPaths) { - if (assemblyPaths is null) - throw new ArgumentNullException(nameof(assemblyPaths)); + ArgumentNullException.ThrowIfNull(assemblyPaths); foreach (string path in assemblyPaths) { diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Assemblies/Ecma/EcmaAssembly.ManifestResources.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Assemblies/Ecma/EcmaAssembly.ManifestResources.cs index 7d5c407a672eed..1b37c0cc454aae 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Assemblies/Ecma/EcmaAssembly.ManifestResources.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Assemblies/Ecma/EcmaAssembly.ManifestResources.cs @@ -14,8 +14,7 @@ internal sealed partial class EcmaAssembly { public sealed override ManifestResourceInfo? GetManifestResourceInfo(string resourceName) { - if (resourceName is null) - throw new ArgumentNullException(nameof(resourceName)); + ArgumentNullException.ThrowIfNull(resourceName); if (resourceName.Length == 0) throw new ArgumentException(null, nameof(resourceName)); @@ -61,8 +60,7 @@ public sealed override string[] GetManifestResourceNames() Justification = "ResourceLocation should never be ContainedInAnotherAssembly if embedded in a single-file")] public sealed override Stream? GetManifestResourceStream(string name) { - if (name is null) - throw new ArgumentNullException(nameof(name)); + ArgumentNullException.ThrowIfNull(name); if (name.Length == 0) throw new ArgumentException(null, nameof(name)); diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Assemblies/RoAssembly.Modules.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Assemblies/RoAssembly.Modules.cs index e5caf0e3a79f89..30660c22c45e3f 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Assemblies/RoAssembly.Modules.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Assemblies/RoAssembly.Modules.cs @@ -61,8 +61,7 @@ public sealed override Module[] GetLoadedModules(bool getResourceModules) internal RoModule? GetRoModule(string name) { - if (name is null) - throw new ArgumentNullException(nameof(name)); + ArgumentNullException.ThrowIfNull(name); if (!TryGetAssemblyFileInfo(name, includeManifestModule: true, out AssemblyFileInfo afi)) return null; @@ -100,10 +99,9 @@ internal RoModule[] ComputeRoModules(bool getResourceModules) public sealed override Module LoadModule(string moduleName, byte[]? rawModule, byte[]? rawSymbolStore) #pragma warning restore CS8995 { - if (moduleName is null) - throw new ArgumentNullException(nameof(moduleName)); - if (rawModule is null) - throw new ArgumentNullException(nameof(rawModule)); + ArgumentNullException.ThrowIfNull(moduleName); + ArgumentNullException.ThrowIfNull(rawModule); + if (!TryGetAssemblyFileInfo(moduleName, includeManifestModule: false, out AssemblyFileInfo afi)) throw new ArgumentException(SR.Format(SR.SpecifiedFileNameInvalid, moduleName)); // Name not in manifest. diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Assemblies/RoAssembly.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Assemblies/RoAssembly.cs index 8ba5c16560087e..8e85330e19d26f 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Assemblies/RoAssembly.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Assemblies/RoAssembly.cs @@ -99,10 +99,7 @@ public sealed override IEnumerable ExportedTypes // Api to retrieve types by name. Retrieves both types physically defined in this module and types this assembly forwards from another assembly. public sealed override Type? GetType(string name, bool throwOnError, bool ignoreCase) { - if (name is null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); // Known compat disagreement: This api is supposed to throw an ArgumentException if the name has an assembly qualification // (though the intended meaning seems clear.) This is difficult for us to implement as we don't have our own type name parser. diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/General/Helpers.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/General/Helpers.cs index c303886f9e7063..60263a0c6516f6 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/General/Helpers.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/General/Helpers.cs @@ -274,8 +274,7 @@ public static string ToString(this IRoMethodBase roMethodBase, MethodSig public static bool HasSameMetadataDefinitionAsCore(this M thisMember, MemberInfo other) where M : MemberInfo { - if (other is null) - throw new ArgumentNullException(nameof(other)); + ArgumentNullException.ThrowIfNull(other); // Ensure that "other" is one of our MemberInfo objects. Do this check before calling any methods on it! if (!(other is M)) diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Methods/RoDefinitionMethod.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Methods/RoDefinitionMethod.cs index 3a2a82883f52f9..4407518d3f34d2 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Methods/RoDefinitionMethod.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Methods/RoDefinitionMethod.cs @@ -100,8 +100,7 @@ public sealed override bool Equals([NotNullWhen(true)] object? obj) [RequiresUnreferencedCode("If some of the generic arguments are annotated (either with DynamicallyAccessedMembersAttribute, or generic constraints), trimming can't validate that the requirements of those annotations are met.")] public sealed override MethodInfo MakeGenericMethod(params Type[] typeArguments) { - if (typeArguments is null) - throw new ArgumentNullException(nameof(typeArguments)); + ArgumentNullException.ThrowIfNull(typeArguments); if (!IsGenericMethodDefinition) throw new InvalidOperationException(SR.Format(SR.Arg_NotGenericMethodDefinition, this)); diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/RuntimeTypeInfo.BindingFlags.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/RuntimeTypeInfo.BindingFlags.cs index ed9d80059b22b0..2bccecb7930715 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/RuntimeTypeInfo.BindingFlags.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/RuntimeTypeInfo.BindingFlags.cs @@ -169,10 +169,7 @@ private QueryResult Query(BindingFlags bindingAttr) where M : MemberInfo private QueryResult Query(string name, BindingFlags bindingAttr) where M : MemberInfo { - if (name is null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); return Query(name, bindingAttr, null); } diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/RuntimeTypeInfo.GetMember.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/RuntimeTypeInfo.GetMember.cs index 59e04482f90d51..f3f2e9f699b382 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/RuntimeTypeInfo.GetMember.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/RuntimeTypeInfo.GetMember.cs @@ -11,20 +11,14 @@ internal partial class RoType public sealed override MemberInfo[] GetMembers(BindingFlags bindingAttr) => GetMemberImpl(null, MemberTypes.All, bindingAttr); public sealed override MemberInfo[] GetMember(string name, BindingFlags bindingAttr) { - if (name is null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); return GetMemberImpl(name, MemberTypes.All, bindingAttr); } public sealed override MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr) { - if (name is null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); return GetMemberImpl(name, type, bindingAttr); } diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Types/RoDefinitionType.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Types/RoDefinitionType.cs index 3782428b2a34cd..f868de5f8584a3 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Types/RoDefinitionType.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Types/RoDefinitionType.cs @@ -89,8 +89,7 @@ public sealed override IEnumerable CustomAttributes [RequiresUnreferencedCode("If some of the generic arguments are annotated (either with DynamicallyAccessedMembersAttribute, or generic constraints), trimming can't validate that the requirements of those annotations are met.")] public sealed override Type MakeGenericType(params Type[] typeArguments) { - if (typeArguments is null) - throw new ArgumentNullException(nameof(typeArguments)); + ArgumentNullException.ThrowIfNull(typeArguments); if (!IsGenericTypeDefinition) throw new InvalidOperationException(SR.Format(SR.Arg_NotGenericTypeDefinition, this)); diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Types/RoType.GetInterface.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Types/RoType.GetInterface.cs index e9d9881cc52bc4..871644ae98d33d 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Types/RoType.GetInterface.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Types/RoType.GetInterface.cs @@ -10,10 +10,7 @@ internal partial class RoType { public sealed override Type? GetInterface(string name, bool ignoreCase) { - if (name is null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); name.SplitTypeName(out string ns, out string simpleName); diff --git a/src/libraries/System.Resources.Extensions/src/System/Resources/Extensions/PreserializedResourceWriter.cs b/src/libraries/System.Resources.Extensions/src/System/Resources/Extensions/PreserializedResourceWriter.cs index 2983a04b4acb22..8f32f0b0e312cf 100644 --- a/src/libraries/System.Resources.Extensions/src/System/Resources/Extensions/PreserializedResourceWriter.cs +++ b/src/libraries/System.Resources.Extensions/src/System/Resources/Extensions/PreserializedResourceWriter.cs @@ -70,18 +70,9 @@ public partial class PreserializedResourceWriter /// Assembly qualified type name of the resource public void AddResource(string name, string value, string typeName) { - if (name is null) - { - throw new ArgumentNullException(nameof(name)); - } - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } - if (typeName is null) - { - throw new ArgumentNullException(nameof(typeName)); - } + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(value); + ArgumentNullException.ThrowIfNull(typeName); // determine if the type is a primitive type if (s_primitiveTypes.TryGetValue(typeName, out Type? primitiveType)) @@ -127,18 +118,9 @@ public void AddResource(string name, string value, string typeName) /// Assembly qualified type name of the resource public void AddTypeConverterResource(string name, byte[] value, string typeName) { - if (name is null) - { - throw new ArgumentNullException(nameof(name)); - } - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } - if (typeName is null) - { - throw new ArgumentNullException(nameof(typeName)); - } + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(value); + ArgumentNullException.ThrowIfNull(typeName); AddResourceData(name, typeName, new ResourceDataRecord(SerializationFormat.TypeConverterByteArray, value)); @@ -155,14 +137,8 @@ public void AddTypeConverterResource(string name, byte[] value, string typeName) [Obsolete(Obsoletions.BinaryFormatterMessage, DiagnosticId = Obsoletions.BinaryFormatterDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] public void AddBinaryFormattedResource(string name, byte[] value, string? typeName = null) { - if (name is null) - { - throw new ArgumentNullException(nameof(name)); - } - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(value); // Some resx-files are missing type information for binary-formatted resources. // These would have previously been handled by deserializing once, capturing the type @@ -188,18 +164,9 @@ public void AddBinaryFormattedResource(string name, byte[] value, string? typeNa /// Indicates that the stream should be closed after resources have been written public void AddActivatorResource(string name, Stream value, string typeName, bool closeAfterWrite = false) { - if (name is null) - { - throw new ArgumentNullException(nameof(name)); - } - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } - if (typeName is null) - { - throw new ArgumentNullException(nameof(typeName)); - } + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(value); + ArgumentNullException.ThrowIfNull(typeName); if (!value.CanSeek) throw new ArgumentException(SR.NotSupported_UnseekableStream); diff --git a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheEntryRemovedArguments.cs b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheEntryRemovedArguments.cs index 8ae008b84ef9c7..e485706e1c9272 100644 --- a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheEntryRemovedArguments.cs +++ b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheEntryRemovedArguments.cs @@ -26,14 +26,8 @@ public ObjectCache Source public CacheEntryRemovedArguments(ObjectCache source, CacheEntryRemovedReason reason, CacheItem cacheItem) { - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } - if (cacheItem is null) - { - throw new ArgumentNullException(nameof(cacheItem)); - } + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(cacheItem); _source = source; _reason = reason; diff --git a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheEntryUpdateArguments.cs b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheEntryUpdateArguments.cs index 38b75f4e57ec21..478a3f758b2bec 100644 --- a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheEntryUpdateArguments.cs +++ b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheEntryUpdateArguments.cs @@ -48,14 +48,8 @@ public CacheItemPolicy UpdatedCacheItemPolicy public CacheEntryUpdateArguments(ObjectCache source, CacheEntryRemovedReason reason, string key, string regionName) { - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(key); _source = source; _reason = reason; diff --git a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/ChangeMonitor.cs b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/ChangeMonitor.cs index 28b3b38c0a9307..d6989874e07aba 100644 --- a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/ChangeMonitor.cs +++ b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/ChangeMonitor.cs @@ -221,10 +221,7 @@ public void Dispose() // be called immediately (on the same thread??). public void NotifyOnChanged(OnChangedCallback onChangedCallback) { - if (onChangedCallback is null) - { - throw new ArgumentNullException(nameof(onChangedCallback)); - } + ArgumentNullException.ThrowIfNull(onChangedCallback); if (Interlocked.CompareExchange(ref _onChangedCallback, onChangedCallback, null) != null) { diff --git a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/FileChangeNotificationSystem.cs b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/FileChangeNotificationSystem.cs index ee23f09a97e150..ca290776200788 100644 --- a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/FileChangeNotificationSystem.cs +++ b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/FileChangeNotificationSystem.cs @@ -95,14 +95,8 @@ internal FileChangeNotificationSystem() void IFileChangeNotificationSystem.StartMonitoring(string filePath, OnChangedCallback onChangedCallback, out object state, out DateTimeOffset lastWriteTime, out long fileSize) { - if (filePath is null) - { - throw new ArgumentNullException(nameof(filePath)); - } - if (onChangedCallback is null) - { - throw new ArgumentNullException(nameof(onChangedCallback)); - } + ArgumentNullException.ThrowIfNull(filePath); + ArgumentNullException.ThrowIfNull(onChangedCallback); FileInfo fileInfo = new FileInfo(filePath); string dir = Path.GetDirectoryName(filePath); @@ -146,14 +140,8 @@ void IFileChangeNotificationSystem.StartMonitoring(string filePath, OnChangedCal void IFileChangeNotificationSystem.StopMonitoring(string filePath, object state) { - if (filePath is null) - { - throw new ArgumentNullException(nameof(filePath)); - } - if (state is null) - { - throw new ArgumentNullException(nameof(state)); - } + ArgumentNullException.ThrowIfNull(filePath); + ArgumentNullException.ThrowIfNull(state); FileChangeEventTarget target = state as FileChangeEventTarget; if (target == null) diff --git a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/HostFileChangeMonitor.cs b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/HostFileChangeMonitor.cs index c14de7b5d2cad1..44bec8472b5314 100644 --- a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/HostFileChangeMonitor.cs +++ b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/HostFileChangeMonitor.cs @@ -159,10 +159,7 @@ protected override void Dispose(bool disposing) public HostFileChangeMonitor(IList filePaths) { - if (filePaths is null) - { - throw new ArgumentNullException(nameof(filePaths)); - } + ArgumentNullException.ThrowIfNull(filePaths); if (filePaths.Count == 0) { diff --git a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCache.cs b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCache.cs index 5ec63c2f65e07b..c9235e1e85b0d9 100644 --- a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCache.cs +++ b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCache.cs @@ -321,10 +321,7 @@ private MemoryCache() public MemoryCache(string name, NameValueCollection config = null) { - if (name is null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); if (name.Length == 0) { @@ -342,10 +339,7 @@ public MemoryCache(string name, NameValueCollection config = null) // due to the fact that the (ASP.NET) config system uses the cache, and the cache uses the config system. public MemoryCache(string name, NameValueCollection config, bool ignoreConfigSection) { - if (name is null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); if (name.Length == 0) { @@ -374,10 +368,7 @@ private void Init(NameValueCollection config) private object AddOrGetExistingInternal(string key, object value, CacheItemPolicy policy) { - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); DateTimeOffset absExp = ObjectCache.InfiniteAbsoluteExpiration; TimeSpan slidingExp = ObjectCache.NoSlidingExpiration; @@ -423,10 +414,7 @@ public override CacheEntryChangeMonitor CreateCacheEntryChangeMonitor(IEnumerabl { throw new NotSupportedException(SR.RegionName_not_supported); } - if (keys == null) - { - throw new ArgumentNullException(nameof(keys)); - } + ArgumentNullException.ThrowIfNull(keys); List keysClone = new List(keys); if (keysClone.Count == 0) { @@ -474,10 +462,7 @@ private object GetInternal(string key, string regionName) { throw new NotSupportedException(SR.RegionName_not_supported); } - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); MemoryCacheEntry entry = GetEntry(key); return entry?.Value; } @@ -584,10 +569,7 @@ public override object AddOrGetExisting(string key, object value, DateTimeOffset public override CacheItem AddOrGetExisting(CacheItem item, CacheItemPolicy policy) { - if (item is null) - { - throw new ArgumentNullException(nameof(item)); - } + ArgumentNullException.ThrowIfNull(item); return new CacheItem(item.Key, AddOrGetExistingInternal(item.Key, item.Value, policy)); } @@ -625,10 +607,7 @@ public override void Set(string key, object value, DateTimeOffset absoluteExpira public override void Set(CacheItem item, CacheItemPolicy policy) { - if (item is null) - { - throw new ArgumentNullException(nameof(item)); - } + ArgumentNullException.ThrowIfNull(item); Set(item.Key, item.Value, policy); } @@ -639,10 +618,7 @@ public override void Set(string key, object value, CacheItemPolicy policy, strin { throw new NotSupportedException(SR.RegionName_not_supported); } - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); DateTimeOffset absExp = ObjectCache.InfiniteAbsoluteExpiration; TimeSpan slidingExp = ObjectCache.NoSlidingExpiration; CacheItemPriority priority = CacheItemPriority.Default; @@ -688,10 +664,7 @@ internal void Set(string key, TimeSpan slidingExpiration, CacheEntryUpdateCallback onUpdateCallback) { - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); if (changeMonitors == null && absoluteExpiration == ObjectCache.InfiniteAbsoluteExpiration @@ -699,10 +672,7 @@ internal void Set(string key, { throw new ArgumentException(SR.Invalid_argument_combination); } - if (onUpdateCallback == null) - { - throw new ArgumentNullException(nameof(onUpdateCallback)); - } + ArgumentNullException.ThrowIfNull(onUpdateCallback); if (IsDisposed) { if (changeMonitors != null) @@ -762,10 +732,7 @@ public object Remove(string key, CacheEntryRemovedReason reason, string regionNa { throw new NotSupportedException(SR.RegionName_not_supported); } - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); if (IsDisposedOrThrow()) { return null; @@ -809,10 +776,7 @@ public override IDictionary GetValues(IEnumerable keys, { throw new NotSupportedException(SR.RegionName_not_supported); } - if (keys == null) - { - throw new ArgumentNullException(nameof(keys)); - } + ArgumentNullException.ThrowIfNull(keys); Dictionary values = null; @@ -840,10 +804,7 @@ public override IDictionary GetValues(IEnumerable keys, // config system. internal void UpdateConfig(NameValueCollection config) { - if (config is null) - { - throw new ArgumentNullException(nameof(config)); - } + ArgumentNullException.ThrowIfNull(config); if (!IsDisposed) { diff --git a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCacheEntry.cs b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCacheEntry.cs index c0d218b4b858f4..adbef06d414eb6 100644 --- a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCacheEntry.cs +++ b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCacheEntry.cs @@ -112,10 +112,7 @@ internal MemoryCacheEntry(string key, CacheEntryRemovedCallback removedCallback, MemoryCache cache) : base(key) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _utcCreated = DateTime.UtcNow; _value = value; diff --git a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/ObjectCache.cs b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/ObjectCache.cs index 39c077570dd008..cd287198799373 100644 --- a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/ObjectCache.cs +++ b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/ObjectCache.cs @@ -29,10 +29,7 @@ public static IServiceProvider Host set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); if (Interlocked.CompareExchange(ref s_host, value, null) != null) { throw new InvalidOperationException(SR.Property_already_set); diff --git a/src/libraries/System.Runtime.Serialization.Formatters/tests/BinaryFormatterTests.cs b/src/libraries/System.Runtime.Serialization.Formatters/tests/BinaryFormatterTests.cs index 6dfeaf8fa4e22e..4329b66501e58d 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/tests/BinaryFormatterTests.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/tests/BinaryFormatterTests.cs @@ -79,10 +79,7 @@ public void ValidateEqualityComparersAgainstBlobs(object obj, TypeSerializableVa private static void ValidateAndRoundtrip(object obj, TypeSerializableValue[] blobs, bool isEqualityComparer) { - if (obj == null) - { - throw new ArgumentNullException("The serializable object must not be null", nameof(obj)); - } + Assert.NotNull(obj); if (blobs == null || blobs.Length == 0) { diff --git a/src/libraries/System.Runtime/tests/System.Runtime.Tests/System.Runtime.Tests.csproj b/src/libraries/System.Runtime/tests/System.Runtime.Tests/System.Runtime.Tests.csproj index fcdd891cf4ac58..4fcdf9b3c77f39 100644 --- a/src/libraries/System.Runtime/tests/System.Runtime.Tests/System.Runtime.Tests.csproj +++ b/src/libraries/System.Runtime/tests/System.Runtime.Tests/System.Runtime.Tests.csproj @@ -328,7 +328,6 @@ - diff --git a/src/libraries/System.Runtime/tests/System.Threading.Tasks.Tests/CESchedulerPairTests.cs b/src/libraries/System.Runtime/tests/System.Threading.Tasks.Tests/CESchedulerPairTests.cs index 0dd20961e6e682..8a2ae855c95196 100644 --- a/src/libraries/System.Runtime/tests/System.Threading.Tasks.Tests/CESchedulerPairTests.cs +++ b/src/libraries/System.Runtime/tests/System.Threading.Tasks.Tests/CESchedulerPairTests.cs @@ -37,7 +37,8 @@ public TrackingTaskScheduler(int maxConLevel) protected override void QueueTask(Task task) { - if (task == null) throw new ArgumentNullException("When requesting to QueueTask, the input task can not be null"); + ArgumentNullException.ThrowIfNull(task); + Task.Factory.StartNew(() => { lock (_lockObj) //Locking so that if multiple threads in threadpool does not incorrectly increment the counter. diff --git a/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseHeaderLabel.cs b/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseHeaderLabel.cs index 6646c87c80e3b7..a476d58a67f7ef 100644 --- a/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseHeaderLabel.cs +++ b/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseHeaderLabel.cs @@ -59,10 +59,7 @@ public CoseHeaderLabel(int label) /// is . public CoseHeaderLabel(string label) { - if (label is null) - { - throw new ArgumentNullException(nameof(label)); - } + ArgumentNullException.ThrowIfNull(label); this = default; LabelAsString = label; diff --git a/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseHeaderValue.cs b/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseHeaderValue.cs index 4602f2295cfd0f..2f58b0045075c8 100644 --- a/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseHeaderValue.cs +++ b/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseHeaderValue.cs @@ -48,10 +48,7 @@ public static CoseHeaderValue FromEncodedValue(ReadOnlySpan encodedValue) /// is . public static CoseHeaderValue FromEncodedValue(byte[] encodedValue) { - if (encodedValue == null) - { - throw new ArgumentNullException(nameof(encodedValue)); - } + ArgumentNullException.ThrowIfNull(encodedValue); return FromEncodedValue(encodedValue.AsSpan()); } @@ -85,10 +82,7 @@ public static CoseHeaderValue FromInt32(int value) /// is . public static CoseHeaderValue FromString(string value) { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); var writer = new CborWriter(); writer.WriteTextString(value); @@ -119,10 +113,7 @@ public static CoseHeaderValue FromBytes(ReadOnlySpan value) /// public static CoseHeaderValue FromBytes(byte[] value) { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); return FromBytes(value.AsSpan()); } diff --git a/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseMessage.cs b/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseMessage.cs index 32ce27a508387a..f4a7b80aadc4bd 100644 --- a/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseMessage.cs +++ b/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseMessage.cs @@ -92,8 +92,7 @@ public ReadOnlyMemory? Content /// could not be decoded as a COSE_Sign1 message. public static CoseSign1Message DecodeSign1(byte[] cborPayload) { - if (cborPayload is null) - throw new ArgumentNullException(nameof(cborPayload)); + ArgumentNullException.ThrowIfNull(cborPayload); return DecodeCoseSign1Core(new CborReader(cborPayload)); } @@ -178,8 +177,7 @@ private static CoseSign1Message DecodeCoseSign1Core(CborReader reader) /// could not be decoded as a COSE_Sign message. public static CoseMultiSignMessage DecodeMultiSign(byte[] cborPayload) { - if (cborPayload is null) - throw new ArgumentNullException(nameof(cborPayload)); + ArgumentNullException.ThrowIfNull(cborPayload); return DecodeCoseMultiSignCore(new CborReader(cborPayload)); } diff --git a/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseMultiSignMessage.cs b/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseMultiSignMessage.cs index 351f987bd95300..5f04720ecd866a 100644 --- a/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseMultiSignMessage.cs +++ b/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseMultiSignMessage.cs @@ -66,8 +66,7 @@ internal CoseMultiSignMessage(CoseHeaderMap protectedHeader, CoseHeaderMap unpro /// public static byte[] SignDetached(byte[] detachedContent, CoseSigner signer, CoseHeaderMap? protectedHeaders = null, CoseHeaderMap? unprotectedHeaders = null, byte[]? associatedData = null) { - if (detachedContent is null) - throw new ArgumentNullException(nameof(detachedContent)); + ArgumentNullException.ThrowIfNull(detachedContent); return SignCore(detachedContent, null, signer, protectedHeaders, unprotectedHeaders, associatedData, isDetached: true); } @@ -97,8 +96,7 @@ public static byte[] SignDetached(byte[] detachedContent, CoseSigner signer, Cos /// public static byte[] SignEmbedded(byte[] embeddedContent, CoseSigner signer, CoseHeaderMap? protectedHeaders = null, CoseHeaderMap? unprotectedHeaders = null, byte[]? associatedData = null) { - if (embeddedContent is null) - throw new ArgumentNullException(nameof(embeddedContent)); + ArgumentNullException.ThrowIfNull(embeddedContent); return SignCore(embeddedContent, null, signer, protectedHeaders, unprotectedHeaders, associatedData, isDetached: false); } @@ -186,8 +184,7 @@ public static byte[] SignEmbedded(ReadOnlySpan embeddedContent, CoseSigner /// public static byte[] SignDetached(Stream detachedContent, CoseSigner signer, CoseHeaderMap? protectedHeaders = null, CoseHeaderMap? unprotectedHeaders = null, ReadOnlySpan associatedData = default) { - if (detachedContent is null) - throw new ArgumentNullException(nameof(detachedContent)); + ArgumentNullException.ThrowIfNull(detachedContent); if (!detachedContent.CanRead) throw new ArgumentException(SR.Sign1ArgumentStreamNotReadable, nameof(detachedContent)); @@ -207,8 +204,7 @@ private static byte[] SignCore( ReadOnlySpan associatedData, bool isDetached) { - if (signer is null) - throw new ArgumentNullException(nameof(signer)); + ArgumentNullException.ThrowIfNull(signer); ValidateBeforeSign(signer, protectedHeaders, unprotectedHeaders); @@ -257,11 +253,8 @@ public static Task SignDetachedAsync( ReadOnlyMemory associatedData = default, CancellationToken cancellationToken = default) { - if (detachedContent is null) - throw new ArgumentNullException(nameof(detachedContent)); - - if (signer is null) - throw new ArgumentNullException(nameof(signer)); + ArgumentNullException.ThrowIfNull(detachedContent); + ArgumentNullException.ThrowIfNull(signer); if (!detachedContent.CanRead) throw new ArgumentException(SR.Sign1ArgumentStreamNotReadable, nameof(detachedContent)); @@ -349,8 +342,7 @@ public static bool TrySignEmbedded(ReadOnlySpan embeddedContent, Span content, Span destination, CoseSigner signer, CoseHeaderMap? protectedHeaders, CoseHeaderMap? unprotectedHeaders, out int bytesWritten, ReadOnlySpan associatedData, bool isDetached) { - if (signer is null) - throw new ArgumentNullException(nameof(signer)); + ArgumentNullException.ThrowIfNull(signer); ValidateBeforeSign(signer, protectedHeaders, unprotectedHeaders); @@ -667,10 +659,7 @@ public void AddSignatureForEmbedded(CoseSigner signer, byte[]? associatedData = /// The content is detached from this message, use an overload that accepts a detached content. public void AddSignatureForEmbedded(CoseSigner signer, ReadOnlySpan associatedData) { - if (signer == null) - { - throw new ArgumentNullException(nameof(signer)); - } + ArgumentNullException.ThrowIfNull(signer); if (IsDetached) { @@ -699,10 +688,7 @@ public void AddSignatureForEmbedded(CoseSigner signer, ReadOnlySpan associ /// The content is embedded on this message, use an overload that uses embedded content. public void AddSignatureForDetached(byte[] detachedContent, CoseSigner signer, byte[]? associatedData = null) { - if (detachedContent == null) - { - throw new ArgumentNullException(nameof(detachedContent)); - } + ArgumentNullException.ThrowIfNull(detachedContent); AddSignatureForDetached(detachedContent.AsSpan(), signer, associatedData); } @@ -726,10 +712,7 @@ public void AddSignatureForDetached(byte[] detachedContent, CoseSigner signer, b /// The content is embedded on this message, use an overload that uses embedded content. public void AddSignatureForDetached(ReadOnlySpan detachedContent, CoseSigner signer, ReadOnlySpan associatedData = default) { - if (signer == null) - { - throw new ArgumentNullException(nameof(signer)); - } + ArgumentNullException.ThrowIfNull(signer); if (!IsDetached) { @@ -762,10 +745,7 @@ public void AddSignatureForDetached(ReadOnlySpan detachedContent, CoseSign /// The content is embedded on this message, use an overload that uses embedded content. public void AddSignatureForDetached(Stream detachedContent, CoseSigner signer, ReadOnlySpan associatedData = default) { - if (detachedContent == null) - { - throw new ArgumentNullException(nameof(detachedContent)); - } + ArgumentNullException.ThrowIfNull(detachedContent); if (!IsDetached) { @@ -838,10 +818,7 @@ private void AddSignatureCore(ReadOnlySpan contentBytes, Stream? contentSt /// The content is embedded on this message, use an overload that uses embedded content. public Task AddSignatureForDetachedAsync(Stream detachedContent, CoseSigner signer, ReadOnlyMemory associatedData = default, CancellationToken cancellationToken = default) { - if (detachedContent == null) - { - throw new ArgumentNullException(nameof(detachedContent)); - } + ArgumentNullException.ThrowIfNull(detachedContent); if (!IsDetached) { @@ -891,10 +868,7 @@ private async Task AddSignatureCoreAsync(Stream content, CoseSigner signer, Read /// public void RemoveSignature(CoseSignature signature) { - if (signature == null) - { - throw new ArgumentNullException(nameof(signature)); - } + ArgumentNullException.ThrowIfNull(signature); _signatures.Remove(signature); } diff --git a/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseSign1Message.cs b/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseSign1Message.cs index 4a4bdc5887b034..67b00b6c6ea906 100644 --- a/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseSign1Message.cs +++ b/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseSign1Message.cs @@ -50,11 +50,8 @@ internal CoseSign1Message(CoseHeaderMap protectedHeader, CoseHeaderMap unprotect /// public static byte[] SignDetached(byte[] detachedContent, CoseSigner signer, byte[]? associatedData = null) { - if (detachedContent is null) - throw new ArgumentNullException(nameof(detachedContent)); - - if (signer is null) - throw new ArgumentNullException(nameof(signer)); + ArgumentNullException.ThrowIfNull(detachedContent); + ArgumentNullException.ThrowIfNull(signer); return SignCore(detachedContent.AsSpan(), null, signer, associatedData, isDetached: true); } @@ -78,11 +75,8 @@ public static byte[] SignDetached(byte[] detachedContent, CoseSigner signer, byt /// public static byte[] SignEmbedded(byte[] embeddedContent, CoseSigner signer, byte[]? associatedData = null) { - if (embeddedContent is null) - throw new ArgumentNullException(nameof(embeddedContent)); - - if (signer is null) - throw new ArgumentNullException(nameof(signer)); + ArgumentNullException.ThrowIfNull(embeddedContent); + ArgumentNullException.ThrowIfNull(signer); return SignCore(embeddedContent.AsSpan(), null, signer, associatedData, isDetached: false); } @@ -106,8 +100,7 @@ public static byte[] SignEmbedded(byte[] embeddedContent, CoseSigner signer, byt /// public static byte[] SignDetached(ReadOnlySpan detachedContent, CoseSigner signer, ReadOnlySpan associatedData = default) { - if (signer is null) - throw new ArgumentNullException(nameof(signer)); + ArgumentNullException.ThrowIfNull(signer); return SignCore(detachedContent, null, signer, associatedData, isDetached: true); } @@ -131,8 +124,7 @@ public static byte[] SignDetached(ReadOnlySpan detachedContent, CoseSigner /// public static byte[] SignEmbedded(ReadOnlySpan embeddedContent, CoseSigner signer, ReadOnlySpan associatedData = default) { - if (signer is null) - throw new ArgumentNullException(nameof(signer)); + ArgumentNullException.ThrowIfNull(signer); return SignCore(embeddedContent, null, signer, associatedData, isDetached: false); } @@ -160,11 +152,8 @@ public static byte[] SignEmbedded(ReadOnlySpan embeddedContent, CoseSigner /// public static byte[] SignDetached(Stream detachedContent, CoseSigner signer, ReadOnlySpan associatedData = default) { - if (detachedContent is null) - throw new ArgumentNullException(nameof(detachedContent)); - - if (signer is null) - throw new ArgumentNullException(nameof(signer)); + ArgumentNullException.ThrowIfNull(detachedContent); + ArgumentNullException.ThrowIfNull(signer); if (!detachedContent.CanRead) throw new ArgumentException(SR.Sign1ArgumentStreamNotReadable, nameof(detachedContent)); @@ -214,11 +203,8 @@ internal static byte[] SignCore(ReadOnlySpan contentBytes, Stream? content /// public static Task SignDetachedAsync(Stream detachedContent, CoseSigner signer, ReadOnlyMemory associatedData = default, CancellationToken cancellationToken = default) { - if (detachedContent is null) - throw new ArgumentNullException(nameof(detachedContent)); - - if (signer is null) - throw new ArgumentNullException(nameof(signer)); + ArgumentNullException.ThrowIfNull(detachedContent); + ArgumentNullException.ThrowIfNull(signer); if (!detachedContent.CanRead) throw new ArgumentException(SR.Sign1ArgumentStreamNotReadable, nameof(detachedContent)); @@ -287,8 +273,7 @@ public static bool TrySignEmbedded(ReadOnlySpan embeddedContent, Span content, Span destination, CoseSigner signer, out int bytesWritten, ReadOnlySpan associatedData, bool isDetached) { - if (signer is null) - throw new ArgumentNullException(nameof(signer)); + ArgumentNullException.ThrowIfNull(signer); ValidateBeforeSign(signer); @@ -393,10 +378,7 @@ private static async Task CreateCoseSign1MessageAsync(Stream content, byte[ /// public bool VerifyEmbedded(AsymmetricAlgorithm key, byte[]? associatedData = null) { - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); if (IsDetached) { @@ -435,10 +417,7 @@ public bool VerifyEmbedded(AsymmetricAlgorithm key, byte[]? associatedData = nul /// public bool VerifyEmbedded(AsymmetricAlgorithm key, ReadOnlySpan associatedData) { - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); if (IsDetached) { @@ -479,14 +458,8 @@ public bool VerifyEmbedded(AsymmetricAlgorithm key, ReadOnlySpan associate /// public bool VerifyDetached(AsymmetricAlgorithm key, byte[] detachedContent, byte[]? associatedData = null) { - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } - if (detachedContent is null) - { - throw new ArgumentNullException(nameof(detachedContent)); - } + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(detachedContent); if (!IsDetached) { @@ -527,10 +500,7 @@ public bool VerifyDetached(AsymmetricAlgorithm key, byte[] detachedContent, byte /// public bool VerifyDetached(AsymmetricAlgorithm key, ReadOnlySpan detachedContent, ReadOnlySpan associatedData = default) { - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); if (!IsDetached) { @@ -579,14 +549,8 @@ public bool VerifyDetached(AsymmetricAlgorithm key, ReadOnlySpan detachedC /// public bool VerifyDetached(AsymmetricAlgorithm key, Stream detachedContent, ReadOnlySpan associatedData = default) { - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } - if (detachedContent is null) - { - throw new ArgumentNullException(nameof(detachedContent)); - } + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(detachedContent); if (!detachedContent.CanRead) { @@ -680,14 +644,8 @@ private bool VerifyCore(AsymmetricAlgorithm key, ReadOnlySpan contentBytes /// public Task VerifyDetachedAsync(AsymmetricAlgorithm key, Stream detachedContent, ReadOnlyMemory associatedData = default, CancellationToken cancellationToken = default) { - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } - if (detachedContent is null) - { - throw new ArgumentNullException(nameof(detachedContent)); - } + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(detachedContent); if (!detachedContent.CanRead) { diff --git a/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseSignature.cs b/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseSignature.cs index da0962a48b3bdf..85214a136ae727 100644 --- a/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseSignature.cs +++ b/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseSignature.cs @@ -99,10 +99,7 @@ internal CoseMultiSignMessage Message /// public bool VerifyEmbedded(AsymmetricAlgorithm key, ReadOnlySpan associatedData) { - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); if (Message.IsDetached) { @@ -142,10 +139,7 @@ public bool VerifyEmbedded(AsymmetricAlgorithm key, ReadOnlySpan associate /// public bool VerifyEmbedded(AsymmetricAlgorithm key, byte[]? associatedData = null) { - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); if (Message.IsDetached) { @@ -186,15 +180,9 @@ public bool VerifyEmbedded(AsymmetricAlgorithm key, byte[]? associatedData = nul /// public bool VerifyDetached(AsymmetricAlgorithm key, byte[] detachedContent, byte[]? associatedData = null) { - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); - if (detachedContent is null) - { - throw new ArgumentNullException(nameof(detachedContent)); - } + ArgumentNullException.ThrowIfNull(detachedContent); if (!Message.IsDetached) { @@ -235,10 +223,7 @@ public bool VerifyDetached(AsymmetricAlgorithm key, byte[] detachedContent, byte /// public bool VerifyDetached(AsymmetricAlgorithm key, ReadOnlySpan detachedContent, ReadOnlySpan associatedData = default) { - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); if (!Message.IsDetached) { @@ -287,15 +272,9 @@ public bool VerifyDetached(AsymmetricAlgorithm key, ReadOnlySpan detachedC /// public bool VerifyDetached(AsymmetricAlgorithm key, Stream detachedContent, ReadOnlySpan associatedData = default) { - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); - if (detachedContent is null) - { - throw new ArgumentNullException(nameof(detachedContent)); - } + ArgumentNullException.ThrowIfNull(detachedContent); if (!detachedContent.CanRead) { @@ -355,14 +334,8 @@ public bool VerifyDetached(AsymmetricAlgorithm key, Stream detachedContent, Read /// public Task VerifyDetachedAsync(AsymmetricAlgorithm key, Stream detachedContent, ReadOnlyMemory associatedData = default, CancellationToken cancellationToken = default) { - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } - if (detachedContent is null) - { - throw new ArgumentNullException(nameof(detachedContent)); - } + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(detachedContent); if (!detachedContent.CanRead) { diff --git a/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseSigner.cs b/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseSigner.cs index e7ae5d9ea01e2b..64a38a7765b5a1 100644 --- a/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseSigner.cs +++ b/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseSigner.cs @@ -64,8 +64,7 @@ public sealed class CoseSigner /// public CoseSigner(AsymmetricAlgorithm key, HashAlgorithmName hashAlgorithm, CoseHeaderMap? protectedHeaders = null, CoseHeaderMap? unprotectedHeaders = null) { - if (key is null) - throw new ArgumentNullException(nameof(key)); + ArgumentNullException.ThrowIfNull(key); if (key is RSA) throw new ArgumentException(SR.CoseSignerRSAKeyNeedsPadding, nameof(key)); @@ -103,11 +102,8 @@ public CoseSigner(AsymmetricAlgorithm key, HashAlgorithmName hashAlgorithm, Cose /// public CoseSigner(RSA key, RSASignaturePadding signaturePadding, HashAlgorithmName hashAlgorithm, CoseHeaderMap? protectedHeaders = null, CoseHeaderMap? unprotectedHeaders = null) { - if (key is null) - throw new ArgumentNullException(nameof(key)); - - if (signaturePadding is null) - throw new ArgumentNullException(nameof(signaturePadding)); + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(signaturePadding); Key = key; HashAlgorithm = hashAlgorithm; diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsRecipient.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsRecipient.cs index 034b1099d752aa..8169d5cce0a460 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsRecipient.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsRecipient.cs @@ -22,10 +22,7 @@ public CmsRecipient(X509Certificate2 certificate) CmsRecipient(X509Certificate2 certificate, RSAEncryptionPadding rsaEncryptionPadding) : this(certificate) { - if (rsaEncryptionPadding is null) - { - throw new ArgumentNullException(nameof(rsaEncryptionPadding)); - } + ArgumentNullException.ThrowIfNull(rsaEncryptionPadding); ValidateRSACertificate(certificate); RSAEncryptionPadding = rsaEncryptionPadding; @@ -39,10 +36,7 @@ public CmsRecipient(X509Certificate2 certificate) CmsRecipient(SubjectIdentifierType recipientIdentifierType, X509Certificate2 certificate, RSAEncryptionPadding rsaEncryptionPadding) : this(recipientIdentifierType, certificate) { - if (rsaEncryptionPadding is null) - { - throw new ArgumentNullException(nameof(rsaEncryptionPadding)); - } + ArgumentNullException.ThrowIfNull(rsaEncryptionPadding); ValidateRSACertificate(certificate); RSAEncryptionPadding = rsaEncryptionPadding; @@ -50,10 +44,7 @@ public CmsRecipient(X509Certificate2 certificate) public CmsRecipient(SubjectIdentifierType recipientIdentifierType, X509Certificate2 certificate) { - if (certificate is null) - { - throw new ArgumentNullException(nameof(certificate)); - } + ArgumentNullException.ThrowIfNull(certificate); switch (recipientIdentifierType) { diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsRecipientCollection.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsRecipientCollection.cs index f4745b8b35ec00..2e057fc390e1fb 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsRecipientCollection.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsRecipientCollection.cs @@ -55,10 +55,7 @@ public int Count public int Add(CmsRecipient recipient) { - if (recipient is null) - { - throw new ArgumentNullException(nameof(recipient)); - } + ArgumentNullException.ThrowIfNull(recipient); int indexOfNewItem = _recipients.Count; _recipients.Add(recipient); @@ -67,10 +64,7 @@ public int Add(CmsRecipient recipient) public void Remove(CmsRecipient recipient) { - if (recipient is null) - { - throw new ArgumentNullException(nameof(recipient)); - } + ArgumentNullException.ThrowIfNull(recipient); _recipients.Remove(recipient); } @@ -87,10 +81,7 @@ IEnumerator IEnumerable.GetEnumerator() public void CopyTo(Array array, int index) { - if (array is null) - { - throw new ArgumentNullException(nameof(array)); - } + ArgumentNullException.ThrowIfNull(array); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); @@ -108,10 +99,7 @@ public void CopyTo(Array array, int index) public void CopyTo(CmsRecipient[] array, int index) { - if (array is null) - { - throw new ArgumentNullException(nameof(array)); - } + ArgumentNullException.ThrowIfNull(array); if (index < 0 || index >= array.Length) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexMustBeLess); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/ContentInfo.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/ContentInfo.cs index 72fcbcbd817511..3df54d9503107b 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/ContentInfo.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/ContentInfo.cs @@ -21,14 +21,8 @@ public ContentInfo(byte[] content) public ContentInfo(Oid contentType, byte[] content) { - if (contentType is null) - { - throw new ArgumentNullException(nameof(contentType)); - } - if (content is null) - { - throw new ArgumentNullException(nameof(content)); - } + ArgumentNullException.ThrowIfNull(contentType); + ArgumentNullException.ThrowIfNull(content); ContentType = contentType; Content = content; @@ -40,10 +34,7 @@ public ContentInfo(Oid contentType, byte[] content) public static Oid GetContentType(byte[] encodedMessage) { - if (encodedMessage is null) - { - throw new ArgumentNullException(nameof(encodedMessage)); - } + ArgumentNullException.ThrowIfNull(encodedMessage); return PkcsPal.Instance.GetEncodedMessageType(encodedMessage); } diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/EnvelopedCms.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/EnvelopedCms.cs index 1f1d4b21ec6a91..25f2278c331631 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/EnvelopedCms.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/EnvelopedCms.cs @@ -27,14 +27,8 @@ public EnvelopedCms(ContentInfo contentInfo) public EnvelopedCms(ContentInfo contentInfo, AlgorithmIdentifier encryptionAlgorithm) { - if (contentInfo is null) - { - throw new ArgumentNullException(nameof(contentInfo)); - } - if (encryptionAlgorithm is null) - { - throw new ArgumentNullException(nameof(encryptionAlgorithm)); - } + ArgumentNullException.ThrowIfNull(contentInfo); + ArgumentNullException.ThrowIfNull(encryptionAlgorithm); Version = 0; // It makes little sense to ask for a version before you've decoded, but since the .NET Framework returns 0 in that case, we will too. ContentInfo = contentInfo; @@ -90,20 +84,14 @@ public RecipientInfoCollection RecipientInfos // public void Encrypt(CmsRecipient recipient) { - if (recipient is null) - { - throw new ArgumentNullException(nameof(recipient)); - } + ArgumentNullException.ThrowIfNull(recipient); Encrypt(new CmsRecipientCollection(recipient)); } public void Encrypt(CmsRecipientCollection recipients) { - if (recipients is null) - { - throw new ArgumentNullException(nameof(recipients)); - } + ArgumentNullException.ThrowIfNull(recipients); // .NET Framework compat note: Unlike the desktop, we don't provide a free UI to select the recipient. The app must give it to us programmatically. if (recipients.Count == 0) @@ -134,10 +122,7 @@ public byte[] Encode() // public void Decode(byte[] encodedMessage) { - if (encodedMessage is null) - { - throw new ArgumentNullException(nameof(encodedMessage)); - } + ArgumentNullException.ThrowIfNull(encodedMessage); Decode(new ReadOnlySpan(encodedMessage)); } @@ -192,34 +177,22 @@ public void Decrypt() public void Decrypt(RecipientInfo recipientInfo) { - if (recipientInfo is null) - { - throw new ArgumentNullException(nameof(recipientInfo)); - } + ArgumentNullException.ThrowIfNull(recipientInfo); DecryptContent(new RecipientInfoCollection(recipientInfo), null); } public void Decrypt(RecipientInfo recipientInfo, X509Certificate2Collection extraStore) { - if (recipientInfo is null) - { - throw new ArgumentNullException(nameof(recipientInfo)); - } - if (extraStore is null) - { - throw new ArgumentNullException(nameof(extraStore)); - } + ArgumentNullException.ThrowIfNull(recipientInfo); + ArgumentNullException.ThrowIfNull(extraStore); DecryptContent(new RecipientInfoCollection(recipientInfo), extraStore); } public void Decrypt(X509Certificate2Collection extraStore) { - if (extraStore is null) - { - throw new ArgumentNullException(nameof(extraStore)); - } + ArgumentNullException.ThrowIfNull(extraStore); DecryptContent(RecipientInfos, extraStore); } @@ -231,10 +204,7 @@ public void Decrypt(X509Certificate2Collection extraStore) #endif void Decrypt(RecipientInfo recipientInfo, AsymmetricAlgorithm? privateKey) { - if (recipientInfo is null) - { - throw new ArgumentNullException(nameof(recipientInfo)); - } + ArgumentNullException.ThrowIfNull(recipientInfo); CheckStateForDecryption(); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/RecipientInfoCollection.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/RecipientInfoCollection.cs index 7c6dc6248213c0..511620a78c15b1 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/RecipientInfoCollection.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/RecipientInfoCollection.cs @@ -56,10 +56,7 @@ IEnumerator IEnumerable.GetEnumerator() public void CopyTo(Array array, int index) { - if (array is null) - { - throw new ArgumentNullException(nameof(array)); - } + ArgumentNullException.ThrowIfNull(array); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); @@ -76,10 +73,7 @@ public void CopyTo(Array array, int index) public void CopyTo(RecipientInfo[] array, int index) { - if (array is null) - { - throw new ArgumentNullException(nameof(array)); - } + ArgumentNullException.ThrowIfNull(array); if (index < 0 || index >= array.Length) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexMustBeLess); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampRequest.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampRequest.cs index 8246fd82199448..38280144f56378 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampRequest.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampRequest.cs @@ -169,10 +169,7 @@ public static Rfc3161TimestampRequest CreateFromSignerInfo( bool requestSignerCertificates = false, X509ExtensionCollection? extensions = null) { - if (signerInfo is null) - { - throw new ArgumentNullException(nameof(signerInfo)); - } + ArgumentNullException.ThrowIfNull(signerInfo); // https://tools.ietf.org/html/rfc3161, Appendix A. // diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampToken.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampToken.cs index 60cae7ea570557..58321a15b127d8 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampToken.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampToken.cs @@ -124,10 +124,7 @@ public bool VerifySignatureForHash( [NotNullWhen(true)] out X509Certificate2? signerCertificate, X509Certificate2Collection? extraCandidates = null) { - if (hashAlgorithmId is null) - { - throw new ArgumentNullException(nameof(hashAlgorithmId)); - } + ArgumentNullException.ThrowIfNull(hashAlgorithmId); signerCertificate = null; @@ -156,10 +153,7 @@ public bool VerifySignatureForSignerInfo( [NotNullWhen(true)] out X509Certificate2? signerCertificate, X509Certificate2Collection? extraCandidates = null) { - if (signerInfo is null) - { - throw new ArgumentNullException(nameof(signerInfo)); - } + ArgumentNullException.ThrowIfNull(signerInfo); return VerifySignatureForData( signerInfo.GetSignatureMemory().Span, diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampTokenInfo.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampTokenInfo.cs index f40c32357f1ed9..93dd9e350469fd 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampTokenInfo.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampTokenInfo.cs @@ -323,14 +323,8 @@ private static byte[] Encode( ReadOnlyMemory? tsaName, X509ExtensionCollection? extensions) { - if (policyId is null) - { - throw new ArgumentNullException(nameof(policyId)); - } - if (hashAlgorithmId is null) - { - throw new ArgumentNullException(nameof(hashAlgorithmId)); - } + ArgumentNullException.ThrowIfNull(policyId); + ArgumentNullException.ThrowIfNull(hashAlgorithmId); var tstInfo = new Rfc3161TstInfo { 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 a3f140a2a30009..fedffc1b7aab58 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 @@ -43,10 +43,7 @@ public sealed partial class SignedCms public SignedCms(SubjectIdentifierType signerIdentifierType, ContentInfo contentInfo, bool detached) { - if (contentInfo is null) - { - throw new ArgumentNullException(nameof(contentInfo)); - } + ArgumentNullException.ThrowIfNull(contentInfo); if (contentInfo.Content == null) throw new ArgumentException(SR.Format(SR.Arg_EmptyOrNullString_Named, "contentInfo.Content"), nameof(contentInfo)); @@ -158,10 +155,7 @@ public byte[] Encode() public void Decode(byte[] encodedMessage) { - if (encodedMessage is null) - { - throw new ArgumentNullException(nameof(encodedMessage)); - } + ArgumentNullException.ThrowIfNull(encodedMessage); Decode(new ReadOnlySpan(encodedMessage)); } @@ -306,10 +300,7 @@ internal static ReadOnlyMemory GetContent( public void ComputeSignature(CmsSigner signer, bool silent) { - if (signer is null) - { - throw new ArgumentNullException(nameof(signer)); - } + ArgumentNullException.ThrowIfNull(signer); // While it shouldn't be possible to change the length of ContentInfo.Content // after it's built, use the property at this stage, then use the saved value @@ -415,10 +406,7 @@ public void RemoveSignature(int index) public void RemoveSignature(SignerInfo signerInfo) { - if (signerInfo is null) - { - throw new ArgumentNullException(nameof(signerInfo)); - } + ArgumentNullException.ThrowIfNull(signerInfo); int idx = SignerInfos.FindIndexForSigner(signerInfo); 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 ed258cd305601c..095ec400cf12de 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 @@ -425,10 +425,7 @@ public void RemoveCounterSignature(int index) public void RemoveCounterSignature(SignerInfo counterSignerInfo) { - if (counterSignerInfo is null) - { - throw new ArgumentNullException(nameof(counterSignerInfo)); - } + ArgumentNullException.ThrowIfNull(counterSignerInfo); SignerInfoCollection docSigners = _document.SignerInfos; int index = docSigners.FindIndexForSigner(this); @@ -454,10 +451,7 @@ public void CheckSignature(bool verifySignatureOnly) => public void CheckSignature(X509Certificate2Collection extraStore, bool verifySignatureOnly) { - if (extraStore is null) - { - throw new ArgumentNullException(nameof(extraStore)); - } + ArgumentNullException.ThrowIfNull(extraStore); X509Certificate2? certificate = Certificate; diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfoCollection.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfoCollection.cs index d019df3d3fc7c5..6df74adf8514f0 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfoCollection.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfoCollection.cs @@ -54,10 +54,7 @@ public SignerInfo this[int index] public void CopyTo(Array array, int index) { - if (array is null) - { - throw new ArgumentNullException(nameof(array)); - } + ArgumentNullException.ThrowIfNull(array); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); diff --git a/src/libraries/System.Security.Cryptography.ProtectedData/src/System/Security/Cryptography/ProtectedData.cs b/src/libraries/System.Security.Cryptography.ProtectedData/src/System/Security/Cryptography/ProtectedData.cs index eeb98bbf48de98..837c7865ca73a8 100644 --- a/src/libraries/System.Security.Cryptography.ProtectedData/src/System/Security/Cryptography/ProtectedData.cs +++ b/src/libraries/System.Security.Cryptography.ProtectedData/src/System/Security/Cryptography/ProtectedData.cs @@ -17,8 +17,7 @@ public static byte[] Protect(byte[] userData, byte[]? optionalEntropy, DataProte { CheckPlatformSupport(); - if (userData is null) - throw new ArgumentNullException(nameof(userData)); + ArgumentNullException.ThrowIfNull(userData); byte[]? outputData; bool result = TryProtectOrUnprotect( @@ -169,8 +168,7 @@ public static byte[] Unprotect(byte[] encryptedData, byte[]? optionalEntropy, Da { CheckPlatformSupport(); - if (encryptedData is null) - throw new ArgumentNullException(nameof(encryptedData)); + ArgumentNullException.ThrowIfNull(encryptedData); byte[]? outputData; bool result = TryProtectOrUnprotect( diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXml.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXml.cs index 98a5c73ea6e4e2..f8564b06eaaba8 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXml.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXml.cs @@ -14,10 +14,7 @@ internal sealed class CanonicalXml internal CanonicalXml(Stream inputStream, bool includeComments, XmlResolver? resolver, string strBaseUri) { - if (inputStream is null) - { - throw new ArgumentNullException(nameof(inputStream)); - } + ArgumentNullException.ThrowIfNull(inputStream); _c14nDoc = new CanonicalXmlDocument(true, includeComments); _c14nDoc.XmlResolver = resolver; @@ -28,10 +25,7 @@ internal CanonicalXml(Stream inputStream, bool includeComments, XmlResolver? res internal CanonicalXml(XmlDocument document, XmlResolver? resolver) : this(document, resolver, false) { } internal CanonicalXml(XmlDocument document, XmlResolver? resolver, bool includeComments) { - if (document is null) - { - throw new ArgumentNullException(nameof(document)); - } + ArgumentNullException.ThrowIfNull(document); _c14nDoc = new CanonicalXmlDocument(true, includeComments); _c14nDoc.XmlResolver = resolver; @@ -41,10 +35,7 @@ internal CanonicalXml(XmlDocument document, XmlResolver? resolver, bool includeC internal CanonicalXml(XmlNodeList nodeList, XmlResolver? resolver, bool includeComments) { - if (nodeList is null) - { - throw new ArgumentNullException(nameof(nodeList)); - } + ArgumentNullException.ThrowIfNull(nodeList); XmlDocument? doc = Utils.GetOwnerDocument(nodeList); if (doc == null) diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalizationDispatcher.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalizationDispatcher.cs index a28a2517f55eb0..b73839e5c7cfd1 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalizationDispatcher.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalizationDispatcher.cs @@ -24,10 +24,7 @@ public static void Write(XmlNode node, StringBuilder strBuilder, DocPosition doc public static void WriteGenericNode(XmlNode node, StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) { - if (node is null) - { - throw new ArgumentNullException(nameof(node)); - } + ArgumentNullException.ThrowIfNull(node); XmlNodeList childNodes = node.ChildNodes; foreach (XmlNode childNode in childNodes) @@ -50,10 +47,7 @@ public static void WriteHash(XmlNode node, HashAlgorithm hash, DocPosition docPo public static void WriteHashGenericNode(XmlNode node, HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) { - if (node is null) - { - throw new ArgumentNullException(nameof(node)); - } + ArgumentNullException.ThrowIfNull(node); XmlNodeList childNodes = node.ChildNodes; foreach (XmlNode childNode in childNodes) diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CipherData.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CipherData.cs index ebc7b1980d2b2a..86d89a3668f83a 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CipherData.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CipherData.cs @@ -98,10 +98,7 @@ internal XmlElement GetXml(XmlDocument document) [RequiresUnreferencedCode(CryptoHelpers.CreateFromNameUnreferencedCodeMessage)] public void LoadXml(XmlElement value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable); nsm.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CipherReference.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CipherReference.cs index 14741e3c069892..51e8ffb36a3257 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CipherReference.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CipherReference.cs @@ -70,10 +70,7 @@ public override XmlElement GetXml() [RequiresUnreferencedCode(CryptoHelpers.CreateFromNameUnreferencedCodeMessage)] public override void LoadXml(XmlElement value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); ReferenceType = value.LocalName; string? uri = Utils.GetAttribute(value, "URI", EncryptedXml.XmlEncNamespaceUrl); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DSAKeyValue.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DSAKeyValue.cs index a9c09663d4fb73..9b29468fd053df 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DSAKeyValue.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DSAKeyValue.cs @@ -25,10 +25,7 @@ public DSAKeyValue() public DSAKeyValue(DSA key) { - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); _key = key; } @@ -42,10 +39,7 @@ public DSA Key get => _key; set { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _key = value; } @@ -153,10 +147,7 @@ internal override XmlElement GetXml(XmlDocument xmlDocument) /// public override void LoadXml(XmlElement value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); if (value.Name != KeyValueElementName || value.NamespaceURI != SignedXml.XmlDsigNamespaceUrl) diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DataObject.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DataObject.cs index 3242122610acd5..cebe80c5fd15a2 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DataObject.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DataObject.cs @@ -26,10 +26,7 @@ public DataObject() public DataObject(string id, string mimeType, string encoding, XmlElement data) { - if (data is null) - { - throw new ArgumentNullException(nameof(data)); - } + ArgumentNullException.ThrowIfNull(data); _id = id; _mimeType = mimeType; @@ -137,10 +134,7 @@ internal XmlElement GetXml(XmlDocument document) public void LoadXml(XmlElement value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _id = Utils.GetAttribute(value, "Id", SignedXml.XmlDsigNamespaceUrl); _mimeType = Utils.GetAttribute(value, "MimeType", SignedXml.XmlDsigNamespaceUrl); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedData.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedData.cs index 3de83fe10ebc08..1c8da88a6d8370 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedData.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedData.cs @@ -12,10 +12,7 @@ public sealed class EncryptedData : EncryptedType [RequiresUnreferencedCode(CryptoHelpers.CreateFromNameUnreferencedCodeMessage)] public override void LoadXml(XmlElement value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable); nsm.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedKey.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedKey.cs index 3cd2a7bc0a35ee..b4646648f50fcd 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedKey.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedKey.cs @@ -51,10 +51,7 @@ public void AddReference(KeyReference keyReference) [RequiresUnreferencedCode(CryptoHelpers.CreateFromNameUnreferencedCodeMessage)] public override void LoadXml(XmlElement value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable); nsm.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedReference.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedReference.cs index 159bc6ac0b5ea9..a65053b711fdc0 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedReference.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedReference.cs @@ -106,10 +106,7 @@ internal XmlElement GetXml(XmlDocument document) [RequiresUnreferencedCode(CryptoHelpers.CreateFromNameUnreferencedCodeMessage)] public virtual void LoadXml(XmlElement value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); ReferenceType = value.LocalName; diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedXml.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedXml.cs index 1e42b3a73ac9ee..706c112f2e9e44 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedXml.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedXml.cs @@ -182,10 +182,7 @@ public string Recipient private byte[] GetCipherValue(CipherData cipherData) { - if (cipherData is null) - { - throw new ArgumentNullException(nameof(cipherData)); - } + ArgumentNullException.ThrowIfNull(cipherData); MemoryStream? inputStream = null; @@ -269,10 +266,7 @@ private byte[] GetCipherValue(CipherData cipherData) // default behaviour is to look for the IV in the CipherValue public virtual byte[] GetDecryptionIV(EncryptedData encryptedData, string? symmetricAlgorithmUri) { - if (encryptedData is null) - { - throw new ArgumentNullException(nameof(encryptedData)); - } + ArgumentNullException.ThrowIfNull(encryptedData); int initBytesSize; // If the Uri is not provided by the application, try to get it from the EncryptionMethod @@ -309,10 +303,7 @@ public virtual byte[] GetDecryptionIV(EncryptedData encryptedData, string? symme [UnconditionalSuppressMessage("ILLink", "IL2026:RequiresUnreferencedCode", Justification = "ctors are marked as RUC")] public virtual SymmetricAlgorithm? GetDecryptionKey(EncryptedData encryptedData, string? symmetricAlgorithmUri) { - if (encryptedData is null) - { - throw new ArgumentNullException(nameof(encryptedData)); - } + ArgumentNullException.ThrowIfNull(encryptedData); if (encryptedData.KeyInfo == null) return null; @@ -398,10 +389,7 @@ public virtual byte[] GetDecryptionIV(EncryptedData encryptedData, string? symme [UnconditionalSuppressMessage("ILLink", "IL2026:RequiresUnreferencedCode", Justification = "ctors are marked as RUC")] public virtual byte[]? DecryptEncryptedKey(EncryptedKey encryptedKey) { - if (encryptedKey is null) - { - throw new ArgumentNullException(nameof(encryptedKey)); - } + ArgumentNullException.ThrowIfNull(encryptedKey); if (encryptedKey.KeyInfo == null) return null; @@ -520,14 +508,8 @@ public virtual byte[] GetDecryptionIV(EncryptedData encryptedData, string? symme // to be an RSA key or a SymmetricAlgorithm public void AddKeyNameMapping(string keyName, object keyObject) { - if (keyName is null) - { - throw new ArgumentNullException(nameof(keyName)); - } - if (keyObject is null) - { - throw new ArgumentNullException(nameof(keyObject)); - } + ArgumentNullException.ThrowIfNull(keyName); + ArgumentNullException.ThrowIfNull(keyObject); if (!(keyObject is SymmetricAlgorithm) && !(keyObject is RSA)) throw new CryptographicException(SR.Cryptography_Xml_NotSupportedCryptographicTransform); @@ -545,14 +527,8 @@ public void ClearKeyNameMappings() [UnconditionalSuppressMessage("ILLink", "IL2026:RequiresUnreferencedCode", Justification = "ctors are marked as RUC")] public EncryptedData Encrypt(XmlElement inputElement, X509Certificate2 certificate) { - if (inputElement is null) - { - throw new ArgumentNullException(nameof(inputElement)); - } - if (certificate is null) - { - throw new ArgumentNullException(nameof(certificate)); - } + ArgumentNullException.ThrowIfNull(inputElement); + ArgumentNullException.ThrowIfNull(certificate); using (RSA? rsaPublicKey = certificate.GetRSAPublicKey()) { @@ -591,14 +567,8 @@ public EncryptedData Encrypt(XmlElement inputElement, X509Certificate2 certifica [UnconditionalSuppressMessage("ILLink", "IL2026:RequiresUnreferencedCode", Justification = "ctors are marked as RUC")] public EncryptedData Encrypt(XmlElement inputElement, string keyName) { - if (inputElement is null) - { - throw new ArgumentNullException(nameof(inputElement)); - } - if (keyName is null) - { - throw new ArgumentNullException(nameof(keyName)); - } + ArgumentNullException.ThrowIfNull(inputElement); + ArgumentNullException.ThrowIfNull(keyName); object? encryptionKey = null; if (_keyNameMapping != null) @@ -698,14 +668,8 @@ public void DecryptDocument() // encrypts the supplied arbitrary data public byte[] EncryptData(byte[] plaintext, SymmetricAlgorithm symmetricAlgorithm) { - if (plaintext is null) - { - throw new ArgumentNullException(nameof(plaintext)); - } - if (symmetricAlgorithm is null) - { - throw new ArgumentNullException(nameof(symmetricAlgorithm)); - } + ArgumentNullException.ThrowIfNull(plaintext); + ArgumentNullException.ThrowIfNull(symmetricAlgorithm); // save the original symmetric algorithm CipherMode origMode = symmetricAlgorithm.Mode; @@ -745,14 +709,8 @@ public byte[] EncryptData(byte[] plaintext, SymmetricAlgorithm symmetricAlgorith // encrypts the supplied input element public byte[] EncryptData(XmlElement inputElement, SymmetricAlgorithm symmetricAlgorithm, bool content) { - if (inputElement is null) - { - throw new ArgumentNullException(nameof(inputElement)); - } - if (symmetricAlgorithm is null) - { - throw new ArgumentNullException(nameof(symmetricAlgorithm)); - } + ArgumentNullException.ThrowIfNull(inputElement); + ArgumentNullException.ThrowIfNull(symmetricAlgorithm); byte[] plainText = (content ? _encoding.GetBytes(inputElement.InnerXml) : _encoding.GetBytes(inputElement.OuterXml)); return EncryptData(plainText, symmetricAlgorithm); @@ -761,14 +719,8 @@ public byte[] EncryptData(XmlElement inputElement, SymmetricAlgorithm symmetricA // decrypts the supplied EncryptedData public byte[] DecryptData(EncryptedData encryptedData, SymmetricAlgorithm symmetricAlgorithm) { - if (encryptedData is null) - { - throw new ArgumentNullException(nameof(encryptedData)); - } - if (symmetricAlgorithm is null) - { - throw new ArgumentNullException(nameof(symmetricAlgorithm)); - } + ArgumentNullException.ThrowIfNull(encryptedData); + ArgumentNullException.ThrowIfNull(symmetricAlgorithm); // get the cipher value and decrypt byte[] cipherValue = GetCipherValue(encryptedData.CipherData); @@ -812,14 +764,8 @@ public byte[] DecryptData(EncryptedData encryptedData, SymmetricAlgorithm symmet // This method replaces an EncryptedData element with the decrypted sequence of bytes public void ReplaceData(XmlElement inputElement, byte[] decryptedData) { - if (inputElement is null) - { - throw new ArgumentNullException(nameof(inputElement)); - } - if (decryptedData is null) - { - throw new ArgumentNullException(nameof(decryptedData)); - } + ArgumentNullException.ThrowIfNull(inputElement); + ArgumentNullException.ThrowIfNull(decryptedData); XmlNode parent = inputElement.ParentNode!; if (parent.NodeType == XmlNodeType.Document) @@ -886,14 +832,8 @@ public void ReplaceData(XmlElement inputElement, byte[] decryptedData) // replaces the inputElement with the provided EncryptedData public static void ReplaceElement(XmlElement inputElement, EncryptedData encryptedData, bool content) { - if (inputElement is null) - { - throw new ArgumentNullException(nameof(inputElement)); - } - if (encryptedData is null) - { - throw new ArgumentNullException(nameof(encryptedData)); - } + ArgumentNullException.ThrowIfNull(inputElement); + ArgumentNullException.ThrowIfNull(encryptedData); // First, get the XML representation of the EncryptedData object XmlElement elemED = encryptedData.GetXml(inputElement.OwnerDocument); @@ -916,14 +856,8 @@ public static void ReplaceElement(XmlElement inputElement, EncryptedData encrypt // wraps the supplied input key data using the provided symmetric algorithm public static byte[] EncryptKey(byte[] keyData, SymmetricAlgorithm symmetricAlgorithm) { - if (keyData is null) - { - throw new ArgumentNullException(nameof(keyData)); - } - if (symmetricAlgorithm is null) - { - throw new ArgumentNullException(nameof(symmetricAlgorithm)); - } + ArgumentNullException.ThrowIfNull(keyData); + ArgumentNullException.ThrowIfNull(symmetricAlgorithm); if (symmetricAlgorithm is TripleDES) { @@ -946,14 +880,8 @@ public static byte[] EncryptKey(byte[] keyData, SymmetricAlgorithm symmetricAlgo // padding or PKCS#1 v1.5 padding as described in the PKCS specification public static byte[] EncryptKey(byte[] keyData, RSA rsa, bool useOAEP) { - if (keyData is null) - { - throw new ArgumentNullException(nameof(keyData)); - } - if (rsa is null) - { - throw new ArgumentNullException(nameof(rsa)); - } + ArgumentNullException.ThrowIfNull(keyData); + ArgumentNullException.ThrowIfNull(rsa); if (useOAEP) { @@ -970,14 +898,8 @@ public static byte[] EncryptKey(byte[] keyData, RSA rsa, bool useOAEP) // decrypts the supplied wrapped key using the provided symmetric algorithm public static byte[] DecryptKey(byte[] keyData, SymmetricAlgorithm symmetricAlgorithm) { - if (keyData is null) - { - throw new ArgumentNullException(nameof(keyData)); - } - if (symmetricAlgorithm is null) - { - throw new ArgumentNullException(nameof(symmetricAlgorithm)); - } + ArgumentNullException.ThrowIfNull(keyData); + ArgumentNullException.ThrowIfNull(symmetricAlgorithm); if (symmetricAlgorithm is TripleDES) { @@ -999,14 +921,8 @@ public static byte[] DecryptKey(byte[] keyData, SymmetricAlgorithm symmetricAlgo // padding or PKCS#1 v1.5 padding as described in the PKCS specification public static byte[] DecryptKey(byte[] keyData, RSA rsa, bool useOAEP) { - if (keyData is null) - { - throw new ArgumentNullException(nameof(keyData)); - } - if (rsa is null) - { - throw new ArgumentNullException(nameof(rsa)); - } + ArgumentNullException.ThrowIfNull(keyData); + ArgumentNullException.ThrowIfNull(rsa); if (useOAEP) { diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionMethod.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionMethod.cs index d50aa84b1dc2ae..a32d7b64a72320 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionMethod.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionMethod.cs @@ -81,10 +81,7 @@ internal XmlElement GetXml(XmlDocument document) public void LoadXml(XmlElement value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable); nsm.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionProperty.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionProperty.cs index 73fc558402c512..ba0dc7e5173b66 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionProperty.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionProperty.cs @@ -18,10 +18,7 @@ public EncryptionProperty() { } public EncryptionProperty(XmlElement elementProperty) { - if (elementProperty is null) - { - throw new ArgumentNullException(nameof(elementProperty)); - } + ArgumentNullException.ThrowIfNull(elementProperty); if (elementProperty.LocalName != "EncryptionProperty" || elementProperty.NamespaceURI != EncryptedXml.XmlEncNamespaceUrl) throw new CryptographicException(SR.Cryptography_Xml_InvalidEncryptionProperty); @@ -81,10 +78,7 @@ internal XmlElement GetXml(XmlDocument document) public void LoadXml(XmlElement value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); if (value.LocalName != "EncryptionProperty" || value.NamespaceURI != EncryptedXml.XmlEncNamespaceUrl) throw new CryptographicException(SR.Cryptography_Xml_InvalidEncryptionProperty); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ExcCanonicalXml.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ExcCanonicalXml.cs index 7d2cddd53e6b05..9541f24bf224f0 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ExcCanonicalXml.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ExcCanonicalXml.cs @@ -14,10 +14,7 @@ internal sealed class ExcCanonicalXml internal ExcCanonicalXml(Stream inputStream, bool includeComments, string inclusiveNamespacesPrefixList, XmlResolver resolver, string strBaseUri) { - if (inputStream is null) - { - throw new ArgumentNullException(nameof(inputStream)); - } + ArgumentNullException.ThrowIfNull(inputStream); _c14nDoc = new CanonicalXmlDocument(true, includeComments); _c14nDoc.XmlResolver = resolver; @@ -27,10 +24,7 @@ internal ExcCanonicalXml(Stream inputStream, bool includeComments, string inclus internal ExcCanonicalXml(XmlDocument document, bool includeComments, string inclusiveNamespacesPrefixList, XmlResolver resolver) { - if (document is null) - { - throw new ArgumentNullException(nameof(document)); - } + ArgumentNullException.ThrowIfNull(document); _c14nDoc = new CanonicalXmlDocument(true, includeComments); _c14nDoc.XmlResolver = resolver; @@ -40,10 +34,7 @@ internal ExcCanonicalXml(XmlDocument document, bool includeComments, string incl internal ExcCanonicalXml(XmlNodeList nodeList, bool includeComments, string inclusiveNamespacesPrefixList, XmlResolver resolver) { - if (nodeList is null) - { - throw new ArgumentNullException(nameof(nodeList)); - } + ArgumentNullException.ThrowIfNull(nodeList); XmlDocument? doc = Utils.GetOwnerDocument(nodeList); if (doc == null) diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfo.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfo.cs index 2beaa3eb31dbbb..86bd9685e31263 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfo.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfo.cs @@ -62,10 +62,7 @@ internal XmlElement GetXml(XmlDocument xmlDocument) [RequiresUnreferencedCode(CryptoHelpers.CreateFromNameUnreferencedCodeMessage)] public void LoadXml(XmlElement value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); XmlElement keyInfoElement = value; _id = Utils.GetAttribute(keyInfoElement, "Id", SignedXml.XmlDsigNamespaceUrl); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoName.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoName.cs index 46082bbb0aaeb0..53d473ba1afb1a 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoName.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoName.cs @@ -50,10 +50,7 @@ internal override XmlElement GetXml(XmlDocument xmlDocument) public override void LoadXml(XmlElement value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); XmlElement nameElement = value; _keyName = nameElement.InnerText.Trim(); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoRetrievalMethod.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoRetrievalMethod.cs index 9f26e6f18668c5..0ab9b07034a7e7 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoRetrievalMethod.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoRetrievalMethod.cs @@ -65,10 +65,7 @@ internal override XmlElement GetXml(XmlDocument xmlDocument) public override void LoadXml(XmlElement value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _uri = Utils.GetAttribute(value, "URI", SignedXml.XmlDsigNamespaceUrl); _type = Utils.GetAttribute(value, "Type", SignedXml.XmlDsigNamespaceUrl); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoX509Data.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoX509Data.cs index 3d88391ec779cf..4f98d32cbd0c33 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoX509Data.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoX509Data.cs @@ -49,10 +49,7 @@ public KeyInfoX509Data(X509Certificate cert) public KeyInfoX509Data(X509Certificate cert, X509IncludeOption includeOption) { - if (cert is null) - { - throw new ArgumentNullException(nameof(cert)); - } + ArgumentNullException.ThrowIfNull(cert); X509Certificate2 certificate = new X509Certificate2(cert); X509ChainElementCollection elements; @@ -112,10 +109,7 @@ public ArrayList? Certificates public void AddCertificate(X509Certificate certificate) { - if (certificate is null) - { - throw new ArgumentNullException(nameof(certificate)); - } + ArgumentNullException.ThrowIfNull(certificate); _certificates ??= new ArrayList(); @@ -279,10 +273,7 @@ internal override XmlElement GetXml(XmlDocument xmlDocument) public override void LoadXml(XmlElement element) { - if (element is null) - { - throw new ArgumentNullException(nameof(element)); - } + ArgumentNullException.ThrowIfNull(element); XmlNamespaceManager nsm = new XmlNamespaceManager(element.OwnerDocument.NameTable); nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAKeyValue.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAKeyValue.cs index c71e2b2016ab60..5798e509bbea49 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAKeyValue.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAKeyValue.cs @@ -20,10 +20,7 @@ public RSAKeyValue() public RSAKeyValue(RSA key) { - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); _key = key; } @@ -37,10 +34,7 @@ public RSA Key get => _key; set { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _key = value; } @@ -108,10 +102,7 @@ internal override XmlElement GetXml(XmlDocument xmlDocument) /// public override void LoadXml(XmlElement value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); if (value.LocalName != KeyValueElementName || value.NamespaceURI != SignedXml.XmlDsigNamespaceUrl) diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Reference.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Reference.cs index ec6e6cabc2cdfa..79c6750bcb0fc7 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Reference.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Reference.cs @@ -208,10 +208,7 @@ internal XmlElement GetXml(XmlDocument document) [RequiresUnreferencedCode(CryptoHelpers.CreateFromNameUnreferencedCodeMessage)] public void LoadXml(XmlElement value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _id = Utils.GetAttribute(value, "Id", SignedXml.XmlDsigNamespaceUrl); _uri = Utils.GetAttribute(value, "URI", SignedXml.XmlDsigNamespaceUrl); @@ -340,10 +337,7 @@ public void LoadXml(XmlElement value) public void AddTransform(Transform transform) { - if (transform is null) - { - throw new ArgumentNullException(nameof(transform)); - } + ArgumentNullException.ThrowIfNull(transform); transform.Reference = this; TransformChain.Add(transform); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ReferenceList.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ReferenceList.cs index a1c76e80507da8..b90981c89a29ad 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ReferenceList.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ReferenceList.cs @@ -27,10 +27,7 @@ public int Count #pragma warning disable CS8995 // Nullable type 'object?' is null-checked and will throw if null. public int Add(object? value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); if (!(value is DataReference) && !(value is KeyReference)) throw new ArgumentException(SR.Cryptography_Xml_IncorrectObjectType, nameof(value)); @@ -56,10 +53,7 @@ public int IndexOf(object? value) public void Insert(int index, object? value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); if (!(value is DataReference) && !(value is KeyReference)) throw new ArgumentException(SR.Cryptography_Xml_IncorrectObjectType, nameof(value)); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Signature.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Signature.cs index 89485f83f534b8..0a269fc1c20033 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Signature.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Signature.cs @@ -133,10 +133,7 @@ internal XmlElement GetXml(XmlDocument document) [RequiresUnreferencedCode(CryptoHelpers.CreateFromNameUnreferencedCodeMessage)] public void LoadXml(XmlElement value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); // Signature XmlElement signatureElement = value; diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedInfo.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedInfo.cs index 20b55828d594e0..bcdbcd4d31172e 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedInfo.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedInfo.cs @@ -204,10 +204,7 @@ internal XmlElement GetXml(XmlDocument document) public void LoadXml(XmlElement value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); // SignedInfo XmlElement signedInfoElement = value; @@ -283,10 +280,7 @@ public void LoadXml(XmlElement value) public void AddReference(Reference reference) { - if (reference is null) - { - throw new ArgumentNullException(nameof(reference)); - } + ArgumentNullException.ThrowIfNull(reference); reference.SignedXml = SignedXml; _references.Add(reference); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXml.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXml.cs index 314d8729fc6e48..9c8d836ab8d472 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXml.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXml.cs @@ -98,10 +98,7 @@ public SignedXml() [RequiresUnreferencedCode(CryptoHelpers.CreateFromNameUnreferencedCodeMessage)] public SignedXml(XmlDocument document) { - if (document is null) - { - throw new ArgumentNullException(nameof(document)); - } + ArgumentNullException.ThrowIfNull(document); Initialize(document.DocumentElement); } @@ -110,10 +107,7 @@ public SignedXml(XmlDocument document) [RequiresUnreferencedCode(CryptoHelpers.CreateFromNameUnreferencedCodeMessage)] public SignedXml(XmlElement elem) { - if (elem is null) - { - throw new ArgumentNullException(nameof(elem)); - } + ArgumentNullException.ThrowIfNull(elem); Initialize(elem); } @@ -231,10 +225,7 @@ public XmlElement GetXml() [UnconditionalSuppressMessage("ILLink", "IL2026:RequiresUnreferencedCode", Justification = "ctors are marked as RUC")] public void LoadXml(XmlElement value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); m_signature.LoadXml(value); @@ -437,10 +428,7 @@ public void ComputeSignature() public void ComputeSignature(KeyedHashAlgorithm macAlg) { - if (macAlg is null) - { - throw new ArgumentNullException(nameof(macAlg)); - } + ArgumentNullException.ThrowIfNull(macAlg); HMAC? hash = macAlg as HMAC; if (hash == null) @@ -1019,10 +1007,7 @@ private bool CheckSignatureFormat() [UnconditionalSuppressMessage("ILLink", "IL2057:UnrecognizedReflectionPattern", Justification = "ctors are marked as RDC")] private bool CheckSignedInfo(AsymmetricAlgorithm key) { - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); SignedXmlDebugLog.LogBeginCheckSignedInfo(this, m_signature.SignedInfo!); @@ -1053,10 +1038,7 @@ private bool CheckSignedInfo(AsymmetricAlgorithm key) private bool CheckSignedInfo(KeyedHashAlgorithm macAlg) { - if (macAlg is null) - { - throw new ArgumentNullException(nameof(macAlg)); - } + ArgumentNullException.ThrowIfNull(macAlg); SignedXmlDebugLog.LogBeginCheckSignedInfo(this, m_signature.SignedInfo!); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/TransformChain.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/TransformChain.cs index 8022ba73c8f879..336bc1d7ed1c06 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/TransformChain.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/TransformChain.cs @@ -171,10 +171,7 @@ internal XmlElement GetXml(XmlDocument document, string ns) [RequiresUnreferencedCode(CryptoHelpers.CreateFromNameUnreferencedCodeMessage)] internal void LoadXml(XmlElement value) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable); nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Utils.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Utils.cs index 2a1d5c51a08887..3829c0e7dadd7b 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Utils.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Utils.cs @@ -33,10 +33,7 @@ private static bool HasNamespace(XmlElement element, string prefix, string value // A helper function that determines if a namespace node is a committed attribute internal static bool IsCommittedNamespace(XmlElement element, string prefix, string value) { - if (element is null) - { - throw new ArgumentNullException(nameof(element)); - } + ArgumentNullException.ThrowIfNull(element); string name = ((prefix.Length > 0) ? "xmlns:" + prefix : "xmlns"); if (element.HasAttribute(name) && element.GetAttribute(name) == value) return true; @@ -45,10 +42,7 @@ internal static bool IsCommittedNamespace(XmlElement element, string prefix, str internal static bool IsRedundantNamespace(XmlElement element, string prefix, string value) { - if (element is null) - { - throw new ArgumentNullException(nameof(element)); - } + ArgumentNullException.ThrowIfNull(element); XmlNode? ancestorNode = ((XmlNode)element).ParentNode; while (ancestorNode != null) @@ -196,10 +190,7 @@ internal static XmlReaderSettings GetSecureXmlReaderSettings(XmlResolver? xmlRes internal static XmlDocument PreProcessDocumentInput(XmlDocument document, XmlResolver xmlResolver, string baseUri) { - if (document is null) - { - throw new ArgumentNullException(nameof(document)); - } + ArgumentNullException.ThrowIfNull(document); MyXmlDocument doc = new MyXmlDocument(); doc.PreserveWhitespace = document.PreserveWhitespace; @@ -220,10 +211,7 @@ internal static XmlDocument PreProcessDocumentInput(XmlDocument document, XmlRes internal static XmlDocument PreProcessElementInput(XmlElement elem, XmlResolver xmlResolver, string? baseUri) { - if (elem is null) - { - throw new ArgumentNullException(nameof(elem)); - } + ArgumentNullException.ThrowIfNull(elem); MyXmlDocument doc = new MyXmlDocument(); doc.PreserveWhitespace = true; diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDecryptionTransform.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDecryptionTransform.cs index 9633e0111c71a5..7113ea0346bfc9 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDecryptionTransform.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDecryptionTransform.cs @@ -78,10 +78,7 @@ public override Type[] OutputTypes public void AddExceptUri(string uri) { - if (uri is null) - { - throw new ArgumentNullException(nameof(uri)); - } + ArgumentNullException.ThrowIfNull(uri); ExceptUris.Add(uri); } @@ -162,10 +159,7 @@ private void LoadStreamInput(Stream stream) private void LoadXmlDocumentInput(XmlDocument document) { - if (document is null) - { - throw new ArgumentNullException(nameof(document)); - } + ArgumentNullException.ThrowIfNull(document); _containingDocument = document; _nsm = new XmlNamespaceManager(document.NameTable); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigEnvelopedSignatureTransform.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigEnvelopedSignatureTransform.cs index f9c7594c30dad0..59f2517ab58c27 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigEnvelopedSignatureTransform.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigEnvelopedSignatureTransform.cs @@ -91,10 +91,7 @@ private void LoadStreamInput(Stream stream) private void LoadXmlNodeListInput(XmlNodeList nodeList) { - if (nodeList is null) - { - throw new ArgumentNullException(nameof(nodeList)); - } + ArgumentNullException.ThrowIfNull(nodeList); _containingDocument = Utils.GetOwnerDocument(nodeList); if (_containingDocument == null) @@ -107,10 +104,7 @@ private void LoadXmlNodeListInput(XmlNodeList nodeList) private void LoadXmlDocumentInput(XmlDocument doc) { - if (doc is null) - { - throw new ArgumentNullException(nameof(doc)); - } + ArgumentNullException.ThrowIfNull(doc); _containingDocument = doc; _nsm = new XmlNamespaceManager(_containingDocument.NameTable); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDiffieHellmanCng.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDiffieHellmanCng.cs index 4a0d436cb45a21..133997876c2fa8 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDiffieHellmanCng.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDiffieHellmanCng.cs @@ -53,7 +53,7 @@ public CngAlgorithm HashAlgorithm set { - ArgumentNullException.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); _hashAlgorithm = value; } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509CertificateLoader.netcore.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509CertificateLoader.netcore.cs index 9eaed37784a652..81f8966e28d8e5 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509CertificateLoader.netcore.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509CertificateLoader.netcore.cs @@ -10,7 +10,7 @@ public static partial class X509CertificateLoader { public static partial X509Certificate2 LoadCertificate(byte[] data) { - ThrowIfNull(data); + ArgumentNullException.ThrowIfNull(data); return LoadCertificate(new ReadOnlySpan(data)); } diff --git a/src/libraries/System.Security.Permissions/src/System/Security/Permissions/PrincipalPermission.cs b/src/libraries/System.Security.Permissions/src/System/Security/Permissions/PrincipalPermission.cs index aebdfcfbe66185..859a63e6647891 100644 --- a/src/libraries/System.Security.Permissions/src/System/Security/Permissions/PrincipalPermission.cs +++ b/src/libraries/System.Security.Permissions/src/System/Security/Permissions/PrincipalPermission.cs @@ -269,10 +269,7 @@ public SecurityElement ToXml() public void FromXml(SecurityElement elem) { - if (elem is null) - { - throw new ArgumentNullException(nameof(elem)); - } + ArgumentNullException.ThrowIfNull(elem); if (elem.Tag == null || !elem.Tag.Equals("Permission") && !elem.Tag.Equals("IPermission")) throw new ArgumentException(SR.Argument_NotAPermissionElement); diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10FeedFormatter.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10FeedFormatter.cs index 3953b79f907f93..2a152cb395ca28 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10FeedFormatter.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10FeedFormatter.cs @@ -37,10 +37,7 @@ public Atom10FeedFormatter() : this(typeof(SyndicationFeed)) public Atom10FeedFormatter(Type feedTypeToCreate) : base() { - if (feedTypeToCreate is null) - { - throw new ArgumentNullException(nameof(feedTypeToCreate)); - } + ArgumentNullException.ThrowIfNull(feedTypeToCreate); if (!typeof(SyndicationFeed).IsAssignableFrom(feedTypeToCreate)) { @@ -73,10 +70,7 @@ internal override TryParseDateTimeCallback GetDefaultDateTimeParser() public override bool CanRead(XmlReader reader) { - if (reader is null) - { - throw new ArgumentNullException(nameof(reader)); - } + ArgumentNullException.ThrowIfNull(reader); return reader.IsStartElement(Atom10Constants.FeedTag, Atom10Constants.Atom10Namespace); } @@ -85,20 +79,14 @@ public override bool CanRead(XmlReader reader) void IXmlSerializable.ReadXml(XmlReader reader) { - if (reader is null) - { - throw new ArgumentNullException(nameof(reader)); - } + ArgumentNullException.ThrowIfNull(reader); ReadFeed(reader); } void IXmlSerializable.WriteXml(XmlWriter writer) { - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } + ArgumentNullException.ThrowIfNull(writer); WriteFeed(writer); } @@ -115,10 +103,7 @@ public override void ReadFrom(XmlReader reader) public override void WriteTo(XmlWriter writer) { - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } + ArgumentNullException.ThrowIfNull(writer); writer.WriteStartElement(Atom10Constants.FeedTag, Atom10Constants.Atom10Namespace); WriteFeed(writer); @@ -493,14 +478,8 @@ internal static void WriteLink(XmlWriter writer, SyndicationLink link, Uri baseU protected virtual SyndicationItem ReadItem(XmlReader reader, SyndicationFeed feed) { - if (reader is null) - { - throw new ArgumentNullException(nameof(reader)); - } - if (feed is null) - { - throw new ArgumentNullException(nameof(feed)); - } + ArgumentNullException.ThrowIfNull(reader); + ArgumentNullException.ThrowIfNull(feed); SyndicationItem item = CreateItem(feed); ReadItemFrom(reader, item, feed.BaseUri); @@ -509,14 +488,8 @@ protected virtual SyndicationItem ReadItem(XmlReader reader, SyndicationFeed fee protected virtual IEnumerable ReadItems(XmlReader reader, SyndicationFeed feed, out bool areAllItemsRead) { - if (reader is null) - { - throw new ArgumentNullException(nameof(reader)); - } - if (feed is null) - { - throw new ArgumentNullException(nameof(feed)); - } + ArgumentNullException.ThrowIfNull(reader); + ArgumentNullException.ThrowIfNull(feed); NullNotAllowedCollection items = new NullNotAllowedCollection(); while (reader.IsStartElement(Atom10Constants.EntryTag, Atom10Constants.Atom10Namespace)) diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10ItemFormatter.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10ItemFormatter.cs index 04014f9dad07d1..460219644da9e2 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10ItemFormatter.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10ItemFormatter.cs @@ -21,10 +21,7 @@ public Atom10ItemFormatter() : this(typeof(SyndicationItem)) public Atom10ItemFormatter(Type itemTypeToCreate) : base() { - if (itemTypeToCreate is null) - { - throw new ArgumentNullException(nameof(itemTypeToCreate)); - } + ArgumentNullException.ThrowIfNull(itemTypeToCreate); if (!typeof(SyndicationItem).IsAssignableFrom(itemTypeToCreate)) { @@ -65,10 +62,7 @@ public bool PreserveElementExtensions public override bool CanRead(XmlReader reader) { - if (reader is null) - { - throw new ArgumentNullException(nameof(reader)); - } + ArgumentNullException.ThrowIfNull(reader); return reader.IsStartElement(Atom10Constants.EntryTag, Atom10Constants.Atom10Namespace); } @@ -77,20 +71,14 @@ public override bool CanRead(XmlReader reader) void IXmlSerializable.ReadXml(XmlReader reader) { - if (reader is null) - { - throw new ArgumentNullException(nameof(reader)); - } + ArgumentNullException.ThrowIfNull(reader); ReadItem(reader); } void IXmlSerializable.WriteXml(XmlWriter writer) { - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } + ArgumentNullException.ThrowIfNull(writer); WriteItem(writer); } @@ -107,10 +95,7 @@ public override void ReadFrom(XmlReader reader) public override void WriteTo(XmlWriter writer) { - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } + ArgumentNullException.ThrowIfNull(writer); writer.WriteStartElement(Atom10Constants.EntryTag, Atom10Constants.Atom10Namespace); WriteItem(writer); diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/AtomPub10CategoriesDocumentFormatter.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/AtomPub10CategoriesDocumentFormatter.cs index 88d45208da4dd1..09e6ed86369730 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/AtomPub10CategoriesDocumentFormatter.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/AtomPub10CategoriesDocumentFormatter.cs @@ -21,18 +21,12 @@ public AtomPub10CategoriesDocumentFormatter() : this(typeof(InlineCategoriesDocu public AtomPub10CategoriesDocumentFormatter(Type inlineDocumentType, Type referencedDocumentType) : base() { - if (inlineDocumentType == null) - { - throw new ArgumentNullException(nameof(inlineDocumentType)); - } + ArgumentNullException.ThrowIfNull(inlineDocumentType); if (!typeof(InlineCategoriesDocument).IsAssignableFrom(inlineDocumentType)) { throw new ArgumentException(SR.Format(SR.InvalidObjectTypePassed, nameof(inlineDocumentType), nameof(InlineCategoriesDocument)), nameof(inlineDocumentType)); } - if (referencedDocumentType == null) - { - throw new ArgumentNullException(nameof(referencedDocumentType)); - } + ArgumentNullException.ThrowIfNull(referencedDocumentType); if (!typeof(ReferencedCategoriesDocument).IsAssignableFrom(referencedDocumentType)) { throw new ArgumentException(SR.Format(SR.InvalidObjectTypePassed, nameof(referencedDocumentType), nameof(ReferencedCategoriesDocument)), nameof(referencedDocumentType)); @@ -62,10 +56,7 @@ public AtomPub10CategoriesDocumentFormatter(CategoriesDocument documentToWrite) public override bool CanRead(XmlReader reader) { - if (reader is null) - { - throw new ArgumentNullException(nameof(reader)); - } + ArgumentNullException.ThrowIfNull(reader); return reader.IsStartElement(App10Constants.Categories, App10Constants.Namespace); } @@ -74,20 +65,14 @@ public override bool CanRead(XmlReader reader) void IXmlSerializable.ReadXml(XmlReader reader) { - if (reader is null) - { - throw new ArgumentNullException(nameof(reader)); - } + ArgumentNullException.ThrowIfNull(reader); ReadDocument(reader); } void IXmlSerializable.WriteXml(XmlWriter writer) { - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } + ArgumentNullException.ThrowIfNull(writer); if (Document == null) { @@ -99,10 +84,7 @@ void IXmlSerializable.WriteXml(XmlWriter writer) public override void ReadFrom(XmlReader reader) { - if (reader is null) - { - throw new ArgumentNullException(nameof(reader)); - } + ArgumentNullException.ThrowIfNull(reader); if (!CanRead(reader)) { @@ -114,10 +96,7 @@ public override void ReadFrom(XmlReader reader) public override void WriteTo(XmlWriter writer) { - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } + ArgumentNullException.ThrowIfNull(writer); if (Document == null) { diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/AtomPub10ServiceDocumentFormatter.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/AtomPub10ServiceDocumentFormatter.cs index 752fa84d51caf9..f0cb53421e98de 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/AtomPub10ServiceDocumentFormatter.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/AtomPub10ServiceDocumentFormatter.cs @@ -24,10 +24,7 @@ public AtomPub10ServiceDocumentFormatter() : this(typeof(ServiceDocument)) public AtomPub10ServiceDocumentFormatter(Type documentTypeToCreate) : base() { - if (documentTypeToCreate is null) - { - throw new ArgumentNullException(nameof(documentTypeToCreate)); - } + ArgumentNullException.ThrowIfNull(documentTypeToCreate); if (!typeof(ServiceDocument).IsAssignableFrom(documentTypeToCreate)) { @@ -48,10 +45,7 @@ public AtomPub10ServiceDocumentFormatter(ServiceDocument documentToWrite) : base public override bool CanRead(XmlReader reader) { - if (reader is null) - { - throw new ArgumentNullException(nameof(reader)); - } + ArgumentNullException.ThrowIfNull(reader); return reader.IsStartElement(App10Constants.Service, App10Constants.Namespace); } @@ -60,20 +54,14 @@ public override bool CanRead(XmlReader reader) void IXmlSerializable.ReadXml(XmlReader reader) { - if (reader is null) - { - throw new ArgumentNullException(nameof(reader)); - } + ArgumentNullException.ThrowIfNull(reader); ReadDocument(reader); } void IXmlSerializable.WriteXml(XmlWriter writer) { - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } + ArgumentNullException.ThrowIfNull(writer); if (Document == null) { @@ -85,10 +73,7 @@ void IXmlSerializable.WriteXml(XmlWriter writer) public override void ReadFrom(XmlReader reader) { - if (reader is null) - { - throw new ArgumentNullException(nameof(reader)); - } + ArgumentNullException.ThrowIfNull(reader); reader.MoveToContent(); if (!CanRead(reader)) @@ -101,10 +86,7 @@ public override void ReadFrom(XmlReader reader) public override void WriteTo(XmlWriter writer) { - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } + ArgumentNullException.ThrowIfNull(writer); if (Document == null) { diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/CategoriesDocumentFormatter.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/CategoriesDocumentFormatter.cs index 078aaad3def526..84ea577632d557 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/CategoriesDocumentFormatter.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/CategoriesDocumentFormatter.cs @@ -17,10 +17,7 @@ protected CategoriesDocumentFormatter() protected CategoriesDocumentFormatter(CategoriesDocument documentToWrite) { - if (documentToWrite is null) - { - throw new ArgumentNullException(nameof(documentToWrite)); - } + ArgumentNullException.ThrowIfNull(documentToWrite); _document = documentToWrite; } diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ExtensibleSyndicationObject.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ExtensibleSyndicationObject.cs index 3ae098aaa550b6..fd3a2cce3a33f6 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ExtensibleSyndicationObject.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ExtensibleSyndicationObject.cs @@ -65,10 +65,7 @@ private static XmlBuffer CreateXmlBuffer(XmlDictionaryReader unparsedExtensionsR internal void LoadElementExtensions(XmlReader readerOverUnparsedExtensions, int maxExtensionSize) { - if (readerOverUnparsedExtensions is null) - { - throw new ArgumentNullException(nameof(readerOverUnparsedExtensions)); - } + ArgumentNullException.ThrowIfNull(readerOverUnparsedExtensions); if (maxExtensionSize < 0) { @@ -87,10 +84,7 @@ internal void LoadElementExtensions(XmlBuffer buffer) internal void WriteAttributeExtensions(XmlWriter writer) { - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } + ArgumentNullException.ThrowIfNull(writer); if (_attributeExtensions != null) { @@ -104,10 +98,7 @@ internal void WriteAttributeExtensions(XmlWriter writer) internal void WriteElementExtensions(XmlWriter writer, Func shouldSkipElement = null) { - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } + ArgumentNullException.ThrowIfNull(writer); _elementExtensions?.WriteTo(writer, shouldSkipElement); } diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/NullNotAllowedCollection.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/NullNotAllowedCollection.cs index a33013931078aa..2ef46dee9469b7 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/NullNotAllowedCollection.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/NullNotAllowedCollection.cs @@ -13,20 +13,14 @@ public NullNotAllowedCollection() : base() protected override void InsertItem(int index, TCollectionItem item) { - if (item is null) - { - throw new ArgumentNullException(nameof(item)); - } + ArgumentNullException.ThrowIfNull(item); base.InsertItem(index, item); } protected override void SetItem(int index, TCollectionItem item) { - if (item is null) - { - throw new ArgumentNullException(nameof(item)); - } + ArgumentNullException.ThrowIfNull(item); base.SetItem(index, item); } diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ReferencedCategoriesDocument.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ReferencedCategoriesDocument.cs index ac4eecb766f1cc..49b751c02d5ceb 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ReferencedCategoriesDocument.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ReferencedCategoriesDocument.cs @@ -11,10 +11,7 @@ public ReferencedCategoriesDocument() public ReferencedCategoriesDocument(Uri link) : base() { - if (link is null) - { - throw new ArgumentNullException(nameof(link)); - } + ArgumentNullException.ThrowIfNull(link); Link = link; } diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ResourceCollectionInfo.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ResourceCollectionInfo.cs index ed4d91c57b1db0..cc2bbf9ddbfc79 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ResourceCollectionInfo.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ResourceCollectionInfo.cs @@ -33,14 +33,8 @@ public ResourceCollectionInfo(TextSyndicationContent title, Uri link, IEnumerabl public ResourceCollectionInfo(TextSyndicationContent title, Uri link, IEnumerable categories, IEnumerable accepts) { - if (title is null) - { - throw new ArgumentNullException(nameof(title)); - } - if (link is null) - { - throw new ArgumentNullException(nameof(link)); - } + ArgumentNullException.ThrowIfNull(title); + ArgumentNullException.ThrowIfNull(link); Title = title; Link = link; diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Rss20FeedFormatter.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Rss20FeedFormatter.cs index b71004972ad700..3515a3fca5276c 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Rss20FeedFormatter.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Rss20FeedFormatter.cs @@ -30,10 +30,7 @@ public Rss20FeedFormatter() : this(typeof(SyndicationFeed)) public Rss20FeedFormatter(Type feedTypeToCreate) : base() { - if (feedTypeToCreate is null) - { - throw new ArgumentNullException(nameof(feedTypeToCreate)); - } + ArgumentNullException.ThrowIfNull(feedTypeToCreate); if (!typeof(SyndicationFeed).IsAssignableFrom(feedTypeToCreate)) { @@ -73,10 +70,7 @@ public Rss20FeedFormatter(SyndicationFeed feedToWrite, bool serializeExtensionsA public override bool CanRead(XmlReader reader) { - if (reader is null) - { - throw new ArgumentNullException(nameof(reader)); - } + ArgumentNullException.ThrowIfNull(reader); return reader.IsStartElement(Rss20Constants.RssTag, Rss20Constants.Rss20Namespace); } @@ -85,20 +79,14 @@ public override bool CanRead(XmlReader reader) void IXmlSerializable.ReadXml(XmlReader reader) { - if (reader is null) - { - throw new ArgumentNullException(nameof(reader)); - } + ArgumentNullException.ThrowIfNull(reader); ReadFeed(reader); } void IXmlSerializable.WriteXml(XmlWriter writer) { - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } + ArgumentNullException.ThrowIfNull(writer); WriteFeed(writer); } @@ -115,10 +103,7 @@ public override void ReadFrom(XmlReader reader) public override void WriteTo(XmlWriter writer) { - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } + ArgumentNullException.ThrowIfNull(writer); writer.WriteStartElement(Rss20Constants.RssTag, Rss20Constants.Rss20Namespace); WriteFeed(writer); @@ -145,14 +130,8 @@ internal void WriteItemContents(XmlWriter writer, SyndicationItem item) protected virtual SyndicationItem ReadItem(XmlReader reader, SyndicationFeed feed) { - if (reader is null) - { - throw new ArgumentNullException(nameof(reader)); - } - if (feed is null) - { - throw new ArgumentNullException(nameof(feed)); - } + ArgumentNullException.ThrowIfNull(reader); + ArgumentNullException.ThrowIfNull(feed); SyndicationItem item = CreateItem(feed); ReadItemFrom(reader, item, feed.BaseUri); @@ -161,14 +140,8 @@ protected virtual SyndicationItem ReadItem(XmlReader reader, SyndicationFeed fee protected virtual IEnumerable ReadItems(XmlReader reader, SyndicationFeed feed, out bool areAllItemsRead) { - if (reader is null) - { - throw new ArgumentNullException(nameof(reader)); - } - if (feed is null) - { - throw new ArgumentNullException(nameof(feed)); - } + ArgumentNullException.ThrowIfNull(reader); + ArgumentNullException.ThrowIfNull(feed); NullNotAllowedCollection items = new NullNotAllowedCollection(); while (reader.IsStartElement(Rss20Constants.ItemTag, Rss20Constants.Rss20Namespace)) diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Rss20ItemFormatter.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Rss20ItemFormatter.cs index 7f9b1c5f01b475..89a4f381af8806 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Rss20ItemFormatter.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Rss20ItemFormatter.cs @@ -22,10 +22,7 @@ public Rss20ItemFormatter() : this(typeof(SyndicationItem)) public Rss20ItemFormatter(Type itemTypeToCreate) : base() { - if (itemTypeToCreate is null) - { - throw new ArgumentNullException(nameof(itemTypeToCreate)); - } + ArgumentNullException.ThrowIfNull(itemTypeToCreate); if (!typeof(SyndicationItem).IsAssignableFrom(itemTypeToCreate)) { @@ -88,10 +85,7 @@ public bool SerializeExtensionsAsAtom public override bool CanRead(XmlReader reader) { - if (reader is null) - { - throw new ArgumentNullException(nameof(reader)); - } + ArgumentNullException.ThrowIfNull(reader); return reader.IsStartElement(Rss20Constants.ItemTag, Rss20Constants.Rss20Namespace); } @@ -100,20 +94,14 @@ public override bool CanRead(XmlReader reader) void IXmlSerializable.ReadXml(XmlReader reader) { - if (reader is null) - { - throw new ArgumentNullException(nameof(reader)); - } + ArgumentNullException.ThrowIfNull(reader); ReadItem(reader); } void IXmlSerializable.WriteXml(XmlWriter writer) { - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } + ArgumentNullException.ThrowIfNull(writer); WriteItem(writer); } @@ -130,10 +118,7 @@ public override void ReadFrom(XmlReader reader) public override void WriteTo(XmlWriter writer) { - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } + ArgumentNullException.ThrowIfNull(writer); writer.WriteStartElement(Rss20Constants.ItemTag, Rss20Constants.Rss20Namespace); WriteItem(writer); diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ServiceDocumentFormatter.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ServiceDocumentFormatter.cs index bd5ace62f4a086..b9ca58192b0b01 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ServiceDocumentFormatter.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ServiceDocumentFormatter.cs @@ -18,10 +18,7 @@ protected ServiceDocumentFormatter() protected ServiceDocumentFormatter(ServiceDocument documentToWrite) { - if (documentToWrite is null) - { - throw new ArgumentNullException(nameof(documentToWrite)); - } + ArgumentNullException.ThrowIfNull(documentToWrite); _document = documentToWrite; } @@ -60,10 +57,7 @@ internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, ServiceDocument document) { - if (document is null) - { - throw new ArgumentNullException(nameof(document)); - } + ArgumentNullException.ThrowIfNull(document); SyndicationFeedFormatter.CloseBuffer(buffer, writer); document.LoadElementExtensions(buffer); @@ -71,20 +65,14 @@ internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter protected static SyndicationCategory CreateCategory(InlineCategoriesDocument inlineCategories) { - if (inlineCategories is null) - { - throw new ArgumentNullException(nameof(inlineCategories)); - } + ArgumentNullException.ThrowIfNull(inlineCategories); return inlineCategories.CreateCategory(); } protected static ResourceCollectionInfo CreateCollection(Workspace workspace) { - if (workspace is null) - { - throw new ArgumentNullException(nameof(workspace)); - } + ArgumentNullException.ThrowIfNull(workspace); return workspace.CreateResourceCollection(); } @@ -101,210 +89,147 @@ protected static ReferencedCategoriesDocument CreateReferencedCategories(Resourc protected static Workspace CreateWorkspace(ServiceDocument document) { - if (document is null) - { - throw new ArgumentNullException(nameof(document)); - } + ArgumentNullException.ThrowIfNull(document); return document.CreateWorkspace(); } protected static void LoadElementExtensions(XmlReader reader, CategoriesDocument categories, int maxExtensionSize) { - if (categories is null) - { - throw new ArgumentNullException(nameof(categories)); - } + ArgumentNullException.ThrowIfNull(categories); categories.LoadElementExtensions(reader, maxExtensionSize); } protected static void LoadElementExtensions(XmlReader reader, ResourceCollectionInfo collection, int maxExtensionSize) { - if (collection is null) - { - throw new ArgumentNullException(nameof(collection)); - } + ArgumentNullException.ThrowIfNull(collection); collection.LoadElementExtensions(reader, maxExtensionSize); } protected static void LoadElementExtensions(XmlReader reader, Workspace workspace, int maxExtensionSize) { - if (workspace is null) - { - throw new ArgumentNullException(nameof(workspace)); - } + ArgumentNullException.ThrowIfNull(workspace); workspace.LoadElementExtensions(reader, maxExtensionSize); } protected static void LoadElementExtensions(XmlReader reader, ServiceDocument document, int maxExtensionSize) { - if (document is null) - { - throw new ArgumentNullException(nameof(document)); - } + ArgumentNullException.ThrowIfNull(document); document.LoadElementExtensions(reader, maxExtensionSize); } protected static bool TryParseAttribute(string name, string ns, string value, ServiceDocument document, string version) { - if (document is null) - { - throw new ArgumentNullException(nameof(document)); - } + ArgumentNullException.ThrowIfNull(document); return document.TryParseAttribute(name, ns, value, version); } protected static bool TryParseAttribute(string name, string ns, string value, ResourceCollectionInfo collection, string version) { - if (collection is null) - { - throw new ArgumentNullException(nameof(collection)); - } + ArgumentNullException.ThrowIfNull(collection); return collection.TryParseAttribute(name, ns, value, version); } protected static bool TryParseAttribute(string name, string ns, string value, CategoriesDocument categories, string version) { - if (categories is null) - { - throw new ArgumentNullException(nameof(categories)); - } + ArgumentNullException.ThrowIfNull(categories); return categories.TryParseAttribute(name, ns, value, version); } protected static bool TryParseAttribute(string name, string ns, string value, Workspace workspace, string version) { - if (workspace is null) - { - throw new ArgumentNullException(nameof(workspace)); - } + ArgumentNullException.ThrowIfNull(workspace); return workspace.TryParseAttribute(name, ns, value, version); } protected static bool TryParseElement(XmlReader reader, ResourceCollectionInfo collection, string version) { - if (collection is null) - { - throw new ArgumentNullException(nameof(collection)); - } + ArgumentNullException.ThrowIfNull(collection); return collection.TryParseElement(reader, version); } protected static bool TryParseElement(XmlReader reader, ServiceDocument document, string version) { - if (document is null) - { - throw new ArgumentNullException(nameof(document)); - } + ArgumentNullException.ThrowIfNull(document); return document.TryParseElement(reader, version); } protected static bool TryParseElement(XmlReader reader, Workspace workspace, string version) { - if (workspace is null) - { - throw new ArgumentNullException(nameof(workspace)); - } + ArgumentNullException.ThrowIfNull(workspace); return workspace.TryParseElement(reader, version); } protected static bool TryParseElement(XmlReader reader, CategoriesDocument categories, string version) { - if (categories is null) - { - throw new ArgumentNullException(nameof(categories)); - } + ArgumentNullException.ThrowIfNull(categories); return categories.TryParseElement(reader, version); } protected static void WriteAttributeExtensions(XmlWriter writer, ServiceDocument document, string version) { - if (document is null) - { - throw new ArgumentNullException(nameof(document)); - } + ArgumentNullException.ThrowIfNull(document); document.WriteAttributeExtensions(writer, version); } protected static void WriteAttributeExtensions(XmlWriter writer, Workspace workspace, string version) { - if (workspace is null) - { - throw new ArgumentNullException(nameof(workspace)); - } + ArgumentNullException.ThrowIfNull(workspace); workspace.WriteAttributeExtensions(writer, version); } protected static void WriteAttributeExtensions(XmlWriter writer, ResourceCollectionInfo collection, string version) { - if (collection is null) - { - throw new ArgumentNullException(nameof(collection)); - } + ArgumentNullException.ThrowIfNull(collection); collection.WriteAttributeExtensions(writer, version); } protected static void WriteAttributeExtensions(XmlWriter writer, CategoriesDocument categories, string version) { - if (categories is null) - { - throw new ArgumentNullException(nameof(categories)); - } + ArgumentNullException.ThrowIfNull(categories); categories.WriteAttributeExtensions(writer, version); } protected static void WriteElementExtensions(XmlWriter writer, ServiceDocument document, string version) { - if (document is null) - { - throw new ArgumentNullException(nameof(document)); - } + ArgumentNullException.ThrowIfNull(document); document.WriteElementExtensions(writer, version); } protected static void WriteElementExtensions(XmlWriter writer, Workspace workspace, string version) { - if (workspace is null) - { - throw new ArgumentNullException(nameof(workspace)); - } + ArgumentNullException.ThrowIfNull(workspace); workspace.WriteElementExtensions(writer, version); } protected static void WriteElementExtensions(XmlWriter writer, ResourceCollectionInfo collection, string version) { - if (collection is null) - { - throw new ArgumentNullException(nameof(collection)); - } + ArgumentNullException.ThrowIfNull(collection); collection.WriteElementExtensions(writer, version); } protected static void WriteElementExtensions(XmlWriter writer, CategoriesDocument categories, string version) { - if (categories is null) - { - throw new ArgumentNullException(nameof(categories)); - } + ArgumentNullException.ThrowIfNull(categories); categories.WriteElementExtensions(writer, version); } diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationCategory.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationCategory.cs index 7e8cf5657e8340..e25de6b926a1cb 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationCategory.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationCategory.cs @@ -28,10 +28,7 @@ public SyndicationCategory(string name, string scheme, string label) protected SyndicationCategory(SyndicationCategory source) { - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } + ArgumentNullException.ThrowIfNull(source); Label = source.Label; Name = source.Name; diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationContent.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationContent.cs index cf689db1874780..6e898c90a7dfe5 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationContent.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationContent.cs @@ -69,10 +69,7 @@ public static XmlSyndicationContent CreateXmlContent(object xmlSerializerObject, public void WriteTo(XmlWriter writer, string outerElementName, string outerElementNamespace) { - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } + ArgumentNullException.ThrowIfNull(writer); if (string.IsNullOrEmpty(outerElementName)) { @@ -99,10 +96,7 @@ public void WriteTo(XmlWriter writer, string outerElementName, string outerEleme internal void CopyAttributeExtensions(SyndicationContent source) { - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } + ArgumentNullException.ThrowIfNull(source); if (source._attributeExtensions != null) { diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtension.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtension.cs index 9c7f0c170d08a9..99a6da6f6ed30f 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtension.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtension.cs @@ -21,10 +21,7 @@ public class SyndicationElementExtension public SyndicationElementExtension(XmlReader xmlReader) { - if (xmlReader is null) - { - throw new ArgumentNullException(nameof(xmlReader)); - } + ArgumentNullException.ThrowIfNull(xmlReader); SyndicationFeedFormatter.MoveToStartElement(xmlReader); _outerName = xmlReader.LocalName; @@ -57,10 +54,7 @@ public SyndicationElementExtension(string outerName, string outerNamespace, obje public SyndicationElementExtension(string outerName, string outerNamespace, object dataContractExtension, XmlObjectSerializer dataContractSerializer) { - if (dataContractExtension is null) - { - throw new ArgumentNullException(nameof(dataContractExtension)); - } + ArgumentNullException.ThrowIfNull(dataContractExtension); if (outerName == string.Empty) { @@ -76,10 +70,7 @@ public SyndicationElementExtension(string outerName, string outerNamespace, obje public SyndicationElementExtension(object xmlSerializerExtension, XmlSerializer serializer) { - if (xmlSerializerExtension is null) - { - throw new ArgumentNullException(nameof(xmlSerializerExtension)); - } + ArgumentNullException.ThrowIfNull(xmlSerializerExtension); serializer ??= new XmlSerializer(xmlSerializerExtension.GetType()); _extensionData = xmlSerializerExtension; @@ -124,10 +115,7 @@ public string OuterNamespace public TExtension GetObject(XmlObjectSerializer serializer) { - if (serializer is null) - { - throw new ArgumentNullException(nameof(serializer)); - } + ArgumentNullException.ThrowIfNull(serializer); if (_extensionData != null && typeof(TExtension).IsAssignableFrom(_extensionData.GetType())) { @@ -141,10 +129,7 @@ public TExtension GetObject(XmlObjectSerializer serializer) public TExtension GetObject(XmlSerializer serializer) { - if (serializer is null) - { - throw new ArgumentNullException(nameof(serializer)); - } + ArgumentNullException.ThrowIfNull(serializer); if (_extensionData != null && typeof(TExtension).IsAssignableFrom(_extensionData.GetType())) { @@ -176,10 +161,7 @@ public XmlReader GetReader() public void WriteTo(XmlWriter writer) { - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } + ArgumentNullException.ThrowIfNull(writer); if (_extensionDataWriter != null) { diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtensionCollection.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtensionCollection.cs index f6530db583de52..ca19f46b3e6ddb 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtensionCollection.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtensionCollection.cs @@ -63,10 +63,7 @@ public void Add(object dataContractExtension, DataContractSerializer serializer) public void Add(string outerName, string outerNamespace, object dataContractExtension, XmlObjectSerializer dataContractSerializer) { - if (dataContractExtension is null) - { - throw new ArgumentNullException(nameof(dataContractExtension)); - } + ArgumentNullException.ThrowIfNull(dataContractExtension); dataContractSerializer ??= new DataContractSerializer(dataContractExtension.GetType()); base.Add(new SyndicationElementExtension(outerName, outerNamespace, dataContractExtension, dataContractSerializer)); @@ -74,10 +71,7 @@ public void Add(string outerName, string outerNamespace, object dataContractExte public void Add(object xmlSerializerExtension, XmlSerializer serializer) { - if (xmlSerializerExtension is null) - { - throw new ArgumentNullException(nameof(xmlSerializerExtension)); - } + ArgumentNullException.ThrowIfNull(xmlSerializerExtension); serializer ??= new XmlSerializer(xmlSerializerExtension.GetType()); base.Add(new SyndicationElementExtension(xmlSerializerExtension, serializer)); @@ -85,10 +79,7 @@ public void Add(object xmlSerializerExtension, XmlSerializer serializer) public void Add(XmlReader xmlReader) { - if (xmlReader is null) - { - throw new ArgumentNullException(nameof(xmlReader)); - } + ArgumentNullException.ThrowIfNull(xmlReader); base.Add(new SyndicationElementExtension(xmlReader)); } @@ -108,20 +99,14 @@ public Collection ReadElementExtensions(string extension public Collection ReadElementExtensions(string extensionName, string extensionNamespace, XmlObjectSerializer serializer) { - if (serializer is null) - { - throw new ArgumentNullException(nameof(serializer)); - } + ArgumentNullException.ThrowIfNull(serializer); return ReadExtensions(extensionName, extensionNamespace, serializer, null); } public Collection ReadElementExtensions(string extensionName, string extensionNamespace, XmlSerializer serializer) { - if (serializer is null) - { - throw new ArgumentNullException(nameof(serializer)); - } + ArgumentNullException.ThrowIfNull(serializer); return ReadExtensions(extensionName, extensionNamespace, null, serializer); } @@ -164,10 +149,7 @@ protected override void ClearItems() protected override void InsertItem(int index, SyndicationElementExtension item) { - if (item is null) - { - throw new ArgumentNullException(nameof(item)); - } + ArgumentNullException.ThrowIfNull(item); base.InsertItem(index, item); // clear the cached buffer if the operation is happening outside the constructor @@ -187,10 +169,7 @@ protected override void RemoveItem(int index) protected override void SetItem(int index, SyndicationElementExtension item) { - if (item is null) - { - throw new ArgumentNullException(nameof(item)); - } + ArgumentNullException.ThrowIfNull(item); base.SetItem(index, item); Debug.Assert(_initialized, "The constructor should never set items in the collection."); diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationFeed.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationFeed.cs index 968cb3af12cbca..aabd10f43fd92b 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationFeed.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationFeed.cs @@ -69,10 +69,7 @@ public SyndicationFeed(string title, string description, Uri feedAlternateLink, protected SyndicationFeed(SyndicationFeed source, bool cloneItems) { - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } + ArgumentNullException.ThrowIfNull(source); _authors = FeedUtils.ClonePersons(source._authors); _categories = FeedUtils.CloneCategories(source._categories); @@ -411,10 +408,7 @@ private static bool IsValidTextInput(SyndicationTextInput textInput) public static TSyndicationFeed Load(XmlReader reader) where TSyndicationFeed : SyndicationFeed, new() { - if (reader is null) - { - throw new ArgumentNullException(nameof(reader)); - } + ArgumentNullException.ThrowIfNull(reader); Atom10FeedFormatter atomSerializer = new Atom10FeedFormatter(); if (atomSerializer.CanRead(reader)) diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationFeedFormatter.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationFeedFormatter.cs index b3e631745fd43d..4b4117cbbdd84a 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationFeedFormatter.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationFeedFormatter.cs @@ -24,10 +24,7 @@ protected SyndicationFeedFormatter() protected SyndicationFeedFormatter(SyndicationFeed feedToWrite) { - if (feedToWrite is null) - { - throw new ArgumentNullException(nameof(feedToWrite)); - } + ArgumentNullException.ThrowIfNull(feedToWrite); _feed = feedToWrite; DateTimeParser = GetDefaultDateTimeParser(); @@ -60,130 +57,91 @@ private bool NotImplementedDateTimeParser(XmlDateTimeData XmlDateTimeData, out D protected internal static SyndicationCategory CreateCategory(SyndicationFeed feed) { - if (feed is null) - { - throw new ArgumentNullException(nameof(feed)); - } + ArgumentNullException.ThrowIfNull(feed); return GetNonNullValue(feed.CreateCategory(), SR.FeedCreatedNullCategory); } protected internal static SyndicationCategory CreateCategory(SyndicationItem item) { - if (item is null) - { - throw new ArgumentNullException(nameof(item)); - } + ArgumentNullException.ThrowIfNull(item); return GetNonNullValue(item.CreateCategory(), SR.ItemCreatedNullCategory); } protected internal static SyndicationItem CreateItem(SyndicationFeed feed) { - if (feed is null) - { - throw new ArgumentNullException(nameof(feed)); - } + ArgumentNullException.ThrowIfNull(feed); return GetNonNullValue(feed.CreateItem(), SR.FeedCreatedNullItem); } protected internal static SyndicationLink CreateLink(SyndicationFeed feed) { - if (feed is null) - { - throw new ArgumentNullException(nameof(feed)); - } + ArgumentNullException.ThrowIfNull(feed); return GetNonNullValue(feed.CreateLink(), SR.FeedCreatedNullPerson); } protected internal static SyndicationLink CreateLink(SyndicationItem item) { - if (item is null) - { - throw new ArgumentNullException(nameof(item)); - } + ArgumentNullException.ThrowIfNull(item); return GetNonNullValue(item.CreateLink(), SR.ItemCreatedNullPerson); } protected internal static SyndicationPerson CreatePerson(SyndicationFeed feed) { - if (feed is null) - { - throw new ArgumentNullException(nameof(feed)); - } + ArgumentNullException.ThrowIfNull(feed); return GetNonNullValue(feed.CreatePerson(), SR.FeedCreatedNullPerson); } protected internal static SyndicationPerson CreatePerson(SyndicationItem item) { - if (item is null) - { - throw new ArgumentNullException(nameof(item)); - } + ArgumentNullException.ThrowIfNull(item); return GetNonNullValue(item.CreatePerson(), SR.ItemCreatedNullPerson); } protected internal static void LoadElementExtensions(XmlReader reader, SyndicationFeed feed, int maxExtensionSize) { - if (feed is null) - { - throw new ArgumentNullException(nameof(feed)); - } + ArgumentNullException.ThrowIfNull(feed); feed.LoadElementExtensions(reader, maxExtensionSize); } protected internal static void LoadElementExtensions(XmlReader reader, SyndicationItem item, int maxExtensionSize) { - if (item is null) - { - throw new ArgumentNullException(nameof(item)); - } + ArgumentNullException.ThrowIfNull(item); item.LoadElementExtensions(reader, maxExtensionSize); } protected internal static void LoadElementExtensions(XmlReader reader, SyndicationCategory category, int maxExtensionSize) { - if (category is null) - { - throw new ArgumentNullException(nameof(category)); - } + ArgumentNullException.ThrowIfNull(category); category.LoadElementExtensions(reader, maxExtensionSize); } protected internal static void LoadElementExtensions(XmlReader reader, SyndicationLink link, int maxExtensionSize) { - if (link is null) - { - throw new ArgumentNullException(nameof(link)); - } + ArgumentNullException.ThrowIfNull(link); link.LoadElementExtensions(reader, maxExtensionSize); } protected internal static void LoadElementExtensions(XmlReader reader, SyndicationPerson person, int maxExtensionSize) { - if (person is null) - { - throw new ArgumentNullException(nameof(person)); - } + ArgumentNullException.ThrowIfNull(person); person.LoadElementExtensions(reader, maxExtensionSize); } protected internal static bool TryParseAttribute(string name, string ns, string value, SyndicationFeed feed, string version) { - if (feed is null) - { - throw new ArgumentNullException(nameof(feed)); - } + ArgumentNullException.ThrowIfNull(feed); if (FeedUtils.IsXmlns(name, ns)) { @@ -194,10 +152,7 @@ protected internal static bool TryParseAttribute(string name, string ns, string protected internal static bool TryParseAttribute(string name, string ns, string value, SyndicationItem item, string version) { - if (item is null) - { - throw new ArgumentNullException(nameof(item)); - } + ArgumentNullException.ThrowIfNull(item); if (FeedUtils.IsXmlns(name, ns)) { @@ -208,10 +163,7 @@ protected internal static bool TryParseAttribute(string name, string ns, string protected internal static bool TryParseAttribute(string name, string ns, string value, SyndicationCategory category, string version) { - if (category is null) - { - throw new ArgumentNullException(nameof(category)); - } + ArgumentNullException.ThrowIfNull(category); if (FeedUtils.IsXmlns(name, ns)) { @@ -222,10 +174,7 @@ protected internal static bool TryParseAttribute(string name, string ns, string protected internal static bool TryParseAttribute(string name, string ns, string value, SyndicationLink link, string version) { - if (link is null) - { - throw new ArgumentNullException(nameof(link)); - } + ArgumentNullException.ThrowIfNull(link); if (FeedUtils.IsXmlns(name, ns)) { @@ -236,10 +185,7 @@ protected internal static bool TryParseAttribute(string name, string ns, string protected internal static bool TryParseAttribute(string name, string ns, string value, SyndicationPerson person, string version) { - if (person is null) - { - throw new ArgumentNullException(nameof(person)); - } + ArgumentNullException.ThrowIfNull(person); if (FeedUtils.IsXmlns(name, ns)) { @@ -255,160 +201,112 @@ protected internal static bool TryParseContent(XmlReader reader, SyndicationItem protected internal static bool TryParseElement(XmlReader reader, SyndicationFeed feed, string version) { - if (feed is null) - { - throw new ArgumentNullException(nameof(feed)); - } + ArgumentNullException.ThrowIfNull(feed); return feed.TryParseElement(reader, version); } protected internal static bool TryParseElement(XmlReader reader, SyndicationItem item, string version) { - if (item is null) - { - throw new ArgumentNullException(nameof(item)); - } + ArgumentNullException.ThrowIfNull(item); return item.TryParseElement(reader, version); } protected internal static bool TryParseElement(XmlReader reader, SyndicationCategory category, string version) { - if (category is null) - { - throw new ArgumentNullException(nameof(category)); - } + ArgumentNullException.ThrowIfNull(category); return category.TryParseElement(reader, version); } protected internal static bool TryParseElement(XmlReader reader, SyndicationLink link, string version) { - if (link is null) - { - throw new ArgumentNullException(nameof(link)); - } + ArgumentNullException.ThrowIfNull(link); return link.TryParseElement(reader, version); } protected internal static bool TryParseElement(XmlReader reader, SyndicationPerson person, string version) { - if (person is null) - { - throw new ArgumentNullException(nameof(person)); - } + ArgumentNullException.ThrowIfNull(person); return person.TryParseElement(reader, version); } protected internal static void WriteAttributeExtensions(XmlWriter writer, SyndicationFeed feed, string version) { - if (feed is null) - { - throw new ArgumentNullException(nameof(feed)); - } + ArgumentNullException.ThrowIfNull(feed); feed.WriteAttributeExtensions(writer, version); } protected internal static void WriteAttributeExtensions(XmlWriter writer, SyndicationItem item, string version) { - if (item is null) - { - throw new ArgumentNullException(nameof(item)); - } + ArgumentNullException.ThrowIfNull(item); item.WriteAttributeExtensions(writer, version); } protected internal static void WriteAttributeExtensions(XmlWriter writer, SyndicationCategory category, string version) { - if (category is null) - { - throw new ArgumentNullException(nameof(category)); - } + ArgumentNullException.ThrowIfNull(category); category.WriteAttributeExtensions(writer, version); } protected internal static void WriteAttributeExtensions(XmlWriter writer, SyndicationLink link, string version) { - if (link is null) - { - throw new ArgumentNullException(nameof(link)); - } + ArgumentNullException.ThrowIfNull(link); link.WriteAttributeExtensions(writer, version); } protected internal static void WriteAttributeExtensions(XmlWriter writer, SyndicationPerson person, string version) { - if (person is null) - { - throw new ArgumentNullException(nameof(person)); - } + ArgumentNullException.ThrowIfNull(person); person.WriteAttributeExtensions(writer, version); } protected internal static void WriteElementExtensions(XmlWriter writer, SyndicationFeed feed, string version) { - if (feed is null) - { - throw new ArgumentNullException(nameof(feed)); - } + ArgumentNullException.ThrowIfNull(feed); feed.WriteElementExtensions(writer, version); } protected internal static void WriteElementExtensions(XmlWriter writer, SyndicationItem item, string version) { - if (item is null) - { - throw new ArgumentNullException(nameof(item)); - } + ArgumentNullException.ThrowIfNull(item); item.WriteElementExtensions(writer, version); } protected internal static void WriteElementExtensions(XmlWriter writer, SyndicationCategory category, string version) { - if (category is null) - { - throw new ArgumentNullException(nameof(category)); - } + ArgumentNullException.ThrowIfNull(category); category.WriteElementExtensions(writer, version); } protected internal static void WriteElementExtensions(XmlWriter writer, SyndicationLink link, string version) { - if (link is null) - { - throw new ArgumentNullException(nameof(link)); - } + ArgumentNullException.ThrowIfNull(link); link.WriteElementExtensions(writer, version); } protected internal static void WriteElementExtensions(XmlWriter writer, SyndicationPerson person, string version) { - if (person is null) - { - throw new ArgumentNullException(nameof(person)); - } + ArgumentNullException.ThrowIfNull(person); person.WriteElementExtensions(writer, version); } protected internal virtual void SetFeed(SyndicationFeed feed) { - if (feed is null) - { - throw new ArgumentNullException(nameof(feed)); - } + ArgumentNullException.ThrowIfNull(feed); _feed = feed; } @@ -511,10 +409,7 @@ internal static SyndicationFeed CreateFeedInstance(Type feedType) internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, SyndicationFeed feed) { - if (feed is null) - { - throw new ArgumentNullException(nameof(feed)); - } + ArgumentNullException.ThrowIfNull(feed); CloseBuffer(buffer, writer); feed.LoadElementExtensions(buffer); diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationItem.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationItem.cs index 625da27aaff4ed..5a0ef11c342080 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationItem.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationItem.cs @@ -50,10 +50,7 @@ public SyndicationItem(string title, SyndicationContent content, Uri itemAlterna protected SyndicationItem(SyndicationItem source) { - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } + ArgumentNullException.ThrowIfNull(source); _extensions = source._extensions.Clone(); _authors = FeedUtils.ClonePersons(source._authors); @@ -157,10 +154,7 @@ public DateTimeOffset PublishDate public static TSyndicationItem Load(XmlReader reader) where TSyndicationItem : SyndicationItem, new() { - if (reader is null) - { - throw new ArgumentNullException(nameof(reader)); - } + ArgumentNullException.ThrowIfNull(reader); Atom10ItemFormatter atomSerializer = new Atom10ItemFormatter(); if (atomSerializer.CanRead(reader)) @@ -181,10 +175,7 @@ public DateTimeOffset PublishDate public void AddPermalink(Uri permalink) { - if (permalink is null) - { - throw new ArgumentNullException(nameof(permalink)); - } + ArgumentNullException.ThrowIfNull(permalink); Id = permalink.AbsoluteUri; Links.Add(SyndicationLink.CreateAlternateLink(permalink)); diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationItemFormatter.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationItemFormatter.cs index c1f5dd064bcd3f..324c387a9eb78e 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationItemFormatter.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationItemFormatter.cs @@ -18,10 +18,7 @@ protected SyndicationItemFormatter() protected SyndicationItemFormatter(SyndicationItem itemToWrite) { - if (itemToWrite is null) - { - throw new ArgumentNullException(nameof(itemToWrite)); - } + ArgumentNullException.ThrowIfNull(itemToWrite); _item = itemToWrite; } @@ -40,10 +37,7 @@ protected SyndicationItemFormatter(SyndicationItem itemToWrite) protected internal virtual void SetItem(SyndicationItem item) { - if (item is null) - { - throw new ArgumentNullException(nameof(item)); - } + ArgumentNullException.ThrowIfNull(item); _item = item; } diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationLink.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationLink.cs index cfcb1efa5a746b..6044f902b22fbe 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationLink.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationLink.cs @@ -37,10 +37,7 @@ public SyndicationLink() : this(null, null, null, null, 0) protected SyndicationLink(SyndicationLink source) { - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } + ArgumentNullException.ThrowIfNull(source); _length = source._length; MediaType = source.MediaType; diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationPerson.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationPerson.cs index ce9897c4eaeb3e..d97e2b2e87f3ba 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationPerson.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationPerson.cs @@ -29,10 +29,7 @@ public SyndicationPerson(string email, string name, string uri) protected SyndicationPerson(SyndicationPerson source) { - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } + ArgumentNullException.ThrowIfNull(source); Email = source.Email; Name = source.Name; diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/UrlSyndicationContent.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/UrlSyndicationContent.cs index f42e33222ad3fb..bc233af98f913c 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/UrlSyndicationContent.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/UrlSyndicationContent.cs @@ -13,10 +13,7 @@ public class UrlSyndicationContent : SyndicationContent public UrlSyndicationContent(Uri url, string mediaType) : base() { - if (url is null) - { - throw new ArgumentNullException(nameof(url)); - } + ArgumentNullException.ThrowIfNull(url); Url = url; _mediaType = mediaType; diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/XmlSyndicationContent.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/XmlSyndicationContent.cs index c9b5d4352840dd..8c413870f9d1d6 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/XmlSyndicationContent.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/XmlSyndicationContent.cs @@ -19,10 +19,7 @@ public class XmlSyndicationContent : SyndicationContent // Reader must be positioned at an element public XmlSyndicationContent(XmlReader reader) { - if (reader is null) - { - throw new ArgumentNullException(nameof(reader)); - } + ArgumentNullException.ThrowIfNull(reader); SyndicationFeedFormatter.MoveToStartElement(reader); if (reader.HasAttributes) @@ -67,10 +64,7 @@ public XmlSyndicationContent(string type, object xmlSerializerExtension, XmlSeri public XmlSyndicationContent(string type, SyndicationElementExtension extension) { - if (extension is null) - { - throw new ArgumentNullException(nameof(extension)); - } + ArgumentNullException.ThrowIfNull(extension); _type = string.IsNullOrEmpty(type) ? Atom10Constants.XmlMediaType : type; Extension = extension; @@ -139,10 +133,7 @@ public TContent ReadContent(XmlSerializer serializer) // does not write start element or type attribute, writes other attributes and rest of content protected override void WriteContentsTo(XmlWriter writer) { - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } + ArgumentNullException.ThrowIfNull(writer); if (Extension != null) { diff --git a/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceController.cs b/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceController.cs index 6c83caaf1b8e35..d8b98fc2003828 100644 --- a/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceController.cs +++ b/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceController.cs @@ -65,10 +65,7 @@ public ServiceController(string name, string machineName) if (!CheckMachineName(machineName)) throw new ArgumentException(SR.Format(SR.BadMachineName, machineName)); - if (name is null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); if (name.Length == 0) { throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(name), name), nameof(name)); diff --git a/src/libraries/System.Speech/src/Internal/Helpers.cs b/src/libraries/System.Speech/src/Internal/Helpers.cs index 85b567434faca4..3dc7b49cc4d2ec 100644 --- a/src/libraries/System.Speech/src/Internal/Helpers.cs +++ b/src/libraries/System.Speech/src/Internal/Helpers.cs @@ -28,15 +28,6 @@ internal static void ThrowIfEmptyOrNull(string s, string paramName) } } - // Throws exception if the specified Rule does not have a valid Id. - internal static void ThrowIfNull(object value, string paramName) - { - if (value == null) - { - throw new ArgumentNullException(paramName); - } - } - internal static bool CompareInvariantCulture(CultureInfo culture1, CultureInfo culture2) { // If perfect match easy diff --git a/src/libraries/System.Speech/src/Internal/SrgsCompiler/GrammarElement.cs b/src/libraries/System.Speech/src/Internal/SrgsCompiler/GrammarElement.cs index 453087ca5c5a6f..226984b826dd69 100644 --- a/src/libraries/System.Speech/src/Internal/SrgsCompiler/GrammarElement.cs +++ b/src/libraries/System.Speech/src/Internal/SrgsCompiler/GrammarElement.cs @@ -136,7 +136,7 @@ CultureInfo IGrammar.Culture { set { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); _backend.LangId = value.LCID; } diff --git a/src/libraries/System.Speech/src/Internal/Synthesis/VoiceSynthesis.cs b/src/libraries/System.Speech/src/Internal/Synthesis/VoiceSynthesis.cs index 2accf7f19406a2..101ccb07123504 100644 --- a/src/libraries/System.Speech/src/Internal/Synthesis/VoiceSynthesis.cs +++ b/src/libraries/System.Speech/src/Internal/Synthesis/VoiceSynthesis.cs @@ -301,7 +301,7 @@ internal void AddEvent(TtsEventId ttsEvent, ref EventHandler internalEvent { lock (_thisObjectLock) { - Helpers.ThrowIfNull(eventHandler, nameof(eventHandler)); + ArgumentNullException.ThrowIfNull(eventHandler); // could through if unsuccessful - delay the SetEventInterest bool fSetSapiInterest = internalEventHandler == null; @@ -320,7 +320,7 @@ internal void RemoveEvent(TtsEventId ttsEvent, ref EventHandler internalEv { lock (_thisObjectLock) { - Helpers.ThrowIfNull(eventHandler, nameof(eventHandler)); + ArgumentNullException.ThrowIfNull(eventHandler); // could through if unsuccessful - delay the SetEventInterest internalEventHandler -= eventHandler; @@ -1670,7 +1670,7 @@ private void QueuePrompt(Prompt prompt) /// private void Speak(string textToSpeak, Prompt prompt, bool fIsXml) { - Helpers.ThrowIfNull(textToSpeak, nameof(textToSpeak)); + ArgumentNullException.ThrowIfNull(textToSpeak); if (_isDisposed) { diff --git a/src/libraries/System.Speech/src/Recognition/Choices.cs b/src/libraries/System.Speech/src/Recognition/Choices.cs index 86884acea7df97..9c7610ae8f46d9 100644 --- a/src/libraries/System.Speech/src/Recognition/Choices.cs +++ b/src/libraries/System.Speech/src/Recognition/Choices.cs @@ -18,14 +18,14 @@ public Choices() public Choices(params string[] phrases) { - Helpers.ThrowIfNull(phrases, nameof(phrases)); + ArgumentNullException.ThrowIfNull(phrases); Add(phrases); } public Choices(params GrammarBuilder[] alternateChoices) { - Helpers.ThrowIfNull(alternateChoices, nameof(alternateChoices)); + ArgumentNullException.ThrowIfNull(alternateChoices); Add(alternateChoices); } @@ -36,7 +36,7 @@ public Choices(params GrammarBuilder[] alternateChoices) public void Add(params string[] phrases) { - Helpers.ThrowIfNull(phrases, nameof(phrases)); + ArgumentNullException.ThrowIfNull(phrases); foreach (string phrase in phrases) { @@ -48,11 +48,11 @@ public void Add(params string[] phrases) public void Add(params GrammarBuilder[] alternateChoices) { - Helpers.ThrowIfNull(alternateChoices, nameof(alternateChoices)); + ArgumentNullException.ThrowIfNull(alternateChoices); foreach (GrammarBuilder alternateChoice in alternateChoices) { - Helpers.ThrowIfNull(alternateChoice, "alternateChoice"); + ArgumentNullException.ThrowIfNull(alternateChoice, "alternateChoice"); _oneOf.Items.Add(new ItemElement(alternateChoice)); } diff --git a/src/libraries/System.Speech/src/Recognition/Grammar.cs b/src/libraries/System.Speech/src/Recognition/Grammar.cs index b4737ed283a411..3407862e0e888a 100644 --- a/src/libraries/System.Speech/src/Recognition/Grammar.cs +++ b/src/libraries/System.Speech/src/Recognition/Grammar.cs @@ -28,7 +28,7 @@ public class Grammar #pragma warning disable 6507 internal Grammar(Uri uri, string ruleName, object[] parameters) { - Helpers.ThrowIfNull(uri, nameof(uri)); + ArgumentNullException.ThrowIfNull(uri); _uri = uri; InitialGrammarLoad(ruleName, parameters, false); @@ -74,7 +74,7 @@ public Grammar(SrgsDocument srgsDocument, string ruleName, Uri baseUri) [EditorBrowsable(EditorBrowsableState.Never)] public Grammar(SrgsDocument srgsDocument, string ruleName, Uri baseUri, object[] parameters) { - Helpers.ThrowIfNull(srgsDocument, nameof(srgsDocument)); + ArgumentNullException.ThrowIfNull(srgsDocument); _srgsDocument = srgsDocument; _isSrgsDocument = srgsDocument != null; @@ -101,7 +101,7 @@ public Grammar(Stream stream, string ruleName, Uri baseUri) [EditorBrowsable(EditorBrowsableState.Never)] public Grammar(Stream stream, string ruleName, Uri baseUri, object[] parameters) { - Helpers.ThrowIfNull(stream, nameof(stream)); + ArgumentNullException.ThrowIfNull(stream); if (!stream.CanRead) { @@ -114,7 +114,7 @@ public Grammar(Stream stream, string ruleName, Uri baseUri, object[] parameters) public Grammar(GrammarBuilder builder) { - Helpers.ThrowIfNull(builder, nameof(builder)); + ArgumentNullException.ThrowIfNull(builder); _grammarBuilder = builder; InitialGrammarLoad(null, null, false); @@ -143,7 +143,7 @@ protected void StgInit(object[] parameters) #region Public Methods public static Grammar LoadLocalizedGrammarFromType(Type type, params object[] onInitParameters) { - Helpers.ThrowIfNull(type, nameof(type)); + ArgumentNullException.ThrowIfNull(type); if (type == typeof(Grammar) || !type.IsSubclassOf(typeof(Grammar))) { diff --git a/src/libraries/System.Speech/src/Recognition/GrammarBuilder.cs b/src/libraries/System.Speech/src/Recognition/GrammarBuilder.cs index 203d6adfa346ea..ceee9c465e3091 100644 --- a/src/libraries/System.Speech/src/Recognition/GrammarBuilder.cs +++ b/src/libraries/System.Speech/src/Recognition/GrammarBuilder.cs @@ -108,11 +108,11 @@ public void Append(string phrase, int minRepeat, int maxRepeat) public void Append(GrammarBuilder builder) { - Helpers.ThrowIfNull(builder, nameof(builder)); + ArgumentNullException.ThrowIfNull(builder); // Should never happens has it is a RO value - Helpers.ThrowIfNull(builder.InternalBuilder, "builder.InternalBuilder"); - Helpers.ThrowIfNull(builder.InternalBuilder.Items, "builder.InternalBuilder.Items"); + ArgumentNullException.ThrowIfNull(builder.InternalBuilder, "builder.InternalBuilder"); + ArgumentNullException.ThrowIfNull(builder.InternalBuilder.Items, "builder.InternalBuilder.Items"); // Clone the items if we are playing with the local list. foreach (GrammarBuilderBase item in builder.InternalBuilder.Items) @@ -137,32 +137,32 @@ public void Append(GrammarBuilder builder) public void Append(Choices alternateChoices) { - Helpers.ThrowIfNull(alternateChoices, nameof(alternateChoices)); + ArgumentNullException.ThrowIfNull(alternateChoices); AddItem(alternateChoices.OneOf); } public void Append(SemanticResultKey key) { - Helpers.ThrowIfNull(key, "builder"); + ArgumentNullException.ThrowIfNull(key, "builder"); AddItem(key.SemanticKeyElement); } public void Append(SemanticResultValue value) { - Helpers.ThrowIfNull(value, "builder"); + ArgumentNullException.ThrowIfNull(value, "builder"); AddItem(value.Tag); } public void Append(GrammarBuilder builder, int minRepeat, int maxRepeat) { - Helpers.ThrowIfNull(builder, nameof(builder)); + ArgumentNullException.ThrowIfNull(builder); GrammarBuilder.ValidateRepeatArguments(minRepeat, maxRepeat, "minRepeat", "maxRepeat"); // Should never happens has it is a RO value - Helpers.ThrowIfNull(builder.InternalBuilder, "builder.InternalBuilder"); + ArgumentNullException.ThrowIfNull(builder.InternalBuilder, "builder.InternalBuilder"); // Wrap the phrase in an item if min and max repeat are set if (minRepeat != 1 || maxRepeat != 1) @@ -255,10 +255,7 @@ public CultureInfo Culture } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _culture = value; } @@ -275,7 +272,7 @@ public CultureInfo Culture public static GrammarBuilder Add(string phrase, GrammarBuilder builder) { - Helpers.ThrowIfNull(builder, nameof(builder)); + ArgumentNullException.ThrowIfNull(builder); GrammarBuilder grammar = new(phrase); grammar.Append(builder); @@ -289,7 +286,7 @@ public static GrammarBuilder Add(string phrase, GrammarBuilder builder) public static GrammarBuilder Add(GrammarBuilder builder, string phrase) { - Helpers.ThrowIfNull(builder, nameof(builder)); + ArgumentNullException.ThrowIfNull(builder); GrammarBuilder grammar = builder.Clone(); grammar.Append(phrase); @@ -303,8 +300,8 @@ public static GrammarBuilder Add(GrammarBuilder builder, string phrase) public static GrammarBuilder Add(Choices choices, GrammarBuilder builder) { - Helpers.ThrowIfNull(choices, nameof(choices)); - Helpers.ThrowIfNull(builder, nameof(builder)); + ArgumentNullException.ThrowIfNull(choices); + ArgumentNullException.ThrowIfNull(builder); GrammarBuilder grammar = new(choices); grammar.Append(builder); @@ -318,8 +315,8 @@ public static GrammarBuilder Add(Choices choices, GrammarBuilder builder) public static GrammarBuilder Add(GrammarBuilder builder, Choices choices) { - Helpers.ThrowIfNull(builder, nameof(builder)); - Helpers.ThrowIfNull(choices, nameof(choices)); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(choices); GrammarBuilder grammar = builder.Clone(); grammar.Append(choices); @@ -333,8 +330,8 @@ public static GrammarBuilder Add(GrammarBuilder builder, Choices choices) public static GrammarBuilder Add(GrammarBuilder builder1, GrammarBuilder builder2) { - Helpers.ThrowIfNull(builder1, nameof(builder1)); - Helpers.ThrowIfNull(builder2, nameof(builder2)); + ArgumentNullException.ThrowIfNull(builder1); + ArgumentNullException.ThrowIfNull(builder2); GrammarBuilder grammar = builder1.Clone(); grammar.Append(builder2); diff --git a/src/libraries/System.Speech/src/Recognition/RecognizerBase.cs b/src/libraries/System.Speech/src/Recognition/RecognizerBase.cs index 29be40695d2d70..1d8f932513adfe 100644 --- a/src/libraries/System.Speech/src/Recognition/RecognizerBase.cs +++ b/src/libraries/System.Speech/src/Recognition/RecognizerBase.cs @@ -366,7 +366,7 @@ internal RecognitionResult EmulateRecognize(RecognizedWordUnit[] wordUnits, Comp // Note that even if there are no threading issues, baseUri is not supported with SAPI 5.1. throw new NotSupportedException(SR.Get(SRID.NotSupportedWithThisVersionOfSAPI)); } - Helpers.ThrowIfNull(wordUnits, nameof(wordUnits)); + ArgumentNullException.ThrowIfNull(wordUnits); foreach (RecognizedWordUnit wordUnit in wordUnits) { @@ -389,7 +389,7 @@ internal void EmulateRecognizeAsync(RecognizedWordUnit[] wordUnits, CompareOptio // Note that even if there are no threading issues, baseUri is not supported with SAPI 5.1. throw new NotSupportedException(SR.Get(SRID.NotSupportedWithThisVersionOfSAPI)); } - Helpers.ThrowIfNull(wordUnits, nameof(wordUnits)); + ArgumentNullException.ThrowIfNull(wordUnits); foreach (RecognizedWordUnit wordUnit in wordUnits) { @@ -1804,7 +1804,7 @@ private SapiGrammar CreateNewSapiGrammar(out ulong grammarId) // Do some basic parameter validation on a passed in Grammar private void ValidateGrammar(Grammar grammar, params GrammarState[] validStates) { - Helpers.ThrowIfNull(grammar, nameof(grammar)); + ArgumentNullException.ThrowIfNull(grammar); // Check if grammar is in a valid state for the caller. foreach (GrammarState state in validStates) diff --git a/src/libraries/System.Speech/src/Recognition/SemanticResultKey.cs b/src/libraries/System.Speech/src/Recognition/SemanticResultKey.cs index 34b6466d1c3839..4291a7c5546ee1 100644 --- a/src/libraries/System.Speech/src/Recognition/SemanticResultKey.cs +++ b/src/libraries/System.Speech/src/Recognition/SemanticResultKey.cs @@ -24,7 +24,7 @@ public SemanticResultKey(string semanticResultKey, params string[] phrases) : this(semanticResultKey) { Helpers.ThrowIfEmptyOrNull(semanticResultKey, nameof(semanticResultKey)); - Helpers.ThrowIfNull(phrases, nameof(phrases)); + ArgumentNullException.ThrowIfNull(phrases); // Build a grammar builder with all the phrases foreach (string phrase in phrases) @@ -37,7 +37,7 @@ public SemanticResultKey(string semanticResultKey, params GrammarBuilder[] build : this(semanticResultKey) { Helpers.ThrowIfEmptyOrNull(semanticResultKey, nameof(semanticResultKey)); - Helpers.ThrowIfNull(builders, "phrases"); + ArgumentNullException.ThrowIfNull(builders, "phrases"); // Build a grammar builder with all the grammar builders foreach (GrammarBuilder builder in builders) diff --git a/src/libraries/System.Speech/src/Recognition/SemanticResultValue.cs b/src/libraries/System.Speech/src/Recognition/SemanticResultValue.cs index eb0a597f31b66e..cbc01ce9384a01 100644 --- a/src/libraries/System.Speech/src/Recognition/SemanticResultValue.cs +++ b/src/libraries/System.Speech/src/Recognition/SemanticResultValue.cs @@ -13,21 +13,21 @@ public class SemanticResultValue #region Constructors public SemanticResultValue(object value) { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); _tag = new TagElement(value); } public SemanticResultValue(string phrase, object value) { Helpers.ThrowIfEmptyOrNull(phrase, nameof(phrase)); - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); _tag = new TagElement(new GrammarBuilderPhrase(phrase), value); } public SemanticResultValue(GrammarBuilder builder, object value) { - Helpers.ThrowIfNull(builder, nameof(builder)); - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(value); _tag = new TagElement(builder.Clone(), value); } diff --git a/src/libraries/System.Speech/src/Recognition/SpeechRecognitionEngine.cs b/src/libraries/System.Speech/src/Recognition/SpeechRecognitionEngine.cs index 1551e22f02925e..36a7d13f08871a 100644 --- a/src/libraries/System.Speech/src/Recognition/SpeechRecognitionEngine.cs +++ b/src/libraries/System.Speech/src/Recognition/SpeechRecognitionEngine.cs @@ -24,7 +24,7 @@ public SpeechRecognitionEngine() } public SpeechRecognitionEngine(CultureInfo culture) { - Helpers.ThrowIfNull(culture, nameof(culture)); + ArgumentNullException.ThrowIfNull(culture); if (culture.Equals(CultureInfo.InvariantCulture)) { @@ -70,7 +70,7 @@ public SpeechRecognitionEngine(string recognizerId) } public SpeechRecognitionEngine(RecognizerInfo recognizerInfo) { - Helpers.ThrowIfNull(recognizerInfo, nameof(recognizerInfo)); + ArgumentNullException.ThrowIfNull(recognizerInfo); Initialize(recognizerInfo); } @@ -234,8 +234,8 @@ public void SetInputToWaveStream(Stream audioSource) } public void SetInputToAudioStream(Stream audioSource, SpeechAudioFormatInfo audioFormat) { - Helpers.ThrowIfNull(audioSource, nameof(audioSource)); - Helpers.ThrowIfNull(audioFormat, nameof(audioFormat)); + ArgumentNullException.ThrowIfNull(audioSource); + ArgumentNullException.ThrowIfNull(audioFormat); RecoBase.SetInput(audioSource, audioFormat); } @@ -414,7 +414,7 @@ public event EventHandler SpeechHypothesized [MethodImplAttribute(MethodImplOptions.Synchronized)] add { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); if (_speechHypothesizedDelegate == null) { RecoBase.SpeechHypothesized += SpeechHypothesizedProxy; @@ -425,7 +425,7 @@ public event EventHandler SpeechHypothesized [MethodImplAttribute(MethodImplOptions.Synchronized)] remove { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); _speechHypothesizedDelegate -= value; if (_speechHypothesizedDelegate == null) { @@ -438,7 +438,7 @@ public event EventHandler AudioSignalProble [MethodImplAttribute(MethodImplOptions.Synchronized)] add { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); if (_audioSignalProblemOccurredDelegate == null) { RecoBase.AudioSignalProblemOccurred += AudioSignalProblemOccurredProxy; @@ -449,7 +449,7 @@ public event EventHandler AudioSignalProble [MethodImplAttribute(MethodImplOptions.Synchronized)] remove { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); _audioSignalProblemOccurredDelegate -= value; if (_audioSignalProblemOccurredDelegate == null) { @@ -462,7 +462,7 @@ public event EventHandler AudioLevelUpdated [MethodImplAttribute(MethodImplOptions.Synchronized)] add { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); if (_audioLevelUpdatedDelegate == null) { RecoBase.AudioLevelUpdated += AudioLevelUpdatedProxy; @@ -473,7 +473,7 @@ public event EventHandler AudioLevelUpdated [MethodImplAttribute(MethodImplOptions.Synchronized)] remove { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); _audioLevelUpdatedDelegate -= value; if (_audioLevelUpdatedDelegate == null) { @@ -486,7 +486,7 @@ public event EventHandler AudioStateChanged [MethodImplAttribute(MethodImplOptions.Synchronized)] add { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); if (_audioStateChangedDelegate == null) { RecoBase.AudioStateChanged += AudioStateChangedProxy; @@ -497,7 +497,7 @@ public event EventHandler AudioStateChanged [MethodImplAttribute(MethodImplOptions.Synchronized)] remove { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); _audioStateChangedDelegate -= value; if (_audioStateChangedDelegate == null) { diff --git a/src/libraries/System.Speech/src/Recognition/SpeechRecognizer.cs b/src/libraries/System.Speech/src/Recognition/SpeechRecognizer.cs index 9f6b96542bc297..342b470aff468b 100644 --- a/src/libraries/System.Speech/src/Recognition/SpeechRecognizer.cs +++ b/src/libraries/System.Speech/src/Recognition/SpeechRecognizer.cs @@ -233,7 +233,7 @@ public event EventHandler SpeechHypothesized [MethodImplAttribute(MethodImplOptions.Synchronized)] add { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); if (_speechHypothesizedDelegate == null) { RecoBase.SpeechHypothesized += SpeechHypothesizedProxy; @@ -244,7 +244,7 @@ public event EventHandler SpeechHypothesized [MethodImplAttribute(MethodImplOptions.Synchronized)] remove { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); _speechHypothesizedDelegate -= value; if (_speechHypothesizedDelegate == null) { @@ -257,7 +257,7 @@ public event EventHandler AudioSignalProble [MethodImplAttribute(MethodImplOptions.Synchronized)] add { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); if (_audioSignalProblemOccurredDelegate == null) { RecoBase.AudioSignalProblemOccurred += AudioSignalProblemOccurredProxy; @@ -268,7 +268,7 @@ public event EventHandler AudioSignalProble [MethodImplAttribute(MethodImplOptions.Synchronized)] remove { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); _audioSignalProblemOccurredDelegate -= value; if (_audioSignalProblemOccurredDelegate == null) { @@ -281,7 +281,7 @@ public event EventHandler AudioLevelUpdated [MethodImplAttribute(MethodImplOptions.Synchronized)] add { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); if (_audioLevelUpdatedDelegate == null) { RecoBase.AudioLevelUpdated += AudioLevelUpdatedProxy; @@ -292,7 +292,7 @@ public event EventHandler AudioLevelUpdated [MethodImplAttribute(MethodImplOptions.Synchronized)] remove { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); _audioLevelUpdatedDelegate -= value; if (_audioLevelUpdatedDelegate == null) { @@ -305,7 +305,7 @@ public event EventHandler AudioStateChanged [MethodImplAttribute(MethodImplOptions.Synchronized)] add { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); if (_audioStateChangedDelegate == null) { RecoBase.AudioStateChanged += AudioStateChangedProxy; @@ -316,7 +316,7 @@ public event EventHandler AudioStateChanged [MethodImplAttribute(MethodImplOptions.Synchronized)] remove { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); _audioStateChangedDelegate -= value; if (_audioStateChangedDelegate == null) { diff --git a/src/libraries/System.Speech/src/Recognition/SpeechUI.cs b/src/libraries/System.Speech/src/Recognition/SpeechUI.cs index 68acc806d06a04..414e76fe7f9f0c 100644 --- a/src/libraries/System.Speech/src/Recognition/SpeechUI.cs +++ b/src/libraries/System.Speech/src/Recognition/SpeechUI.cs @@ -12,7 +12,7 @@ internal SpeechUI() } public static bool SendTextFeedback(RecognitionResult result, string feedback, bool isSuccessfulAction) { - Helpers.ThrowIfNull(result, nameof(result)); + ArgumentNullException.ThrowIfNull(result); Helpers.ThrowIfEmptyOrNull(feedback, nameof(feedback)); return result.SetTextFeedback(feedback, isSuccessfulAction); diff --git a/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsDocument.cs b/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsDocument.cs index 14020f6bc480df..ee0b4835689ede 100644 --- a/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsDocument.cs +++ b/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsDocument.cs @@ -39,13 +39,13 @@ public SrgsDocument(string path) } public SrgsDocument(XmlReader srgsGrammar) { - Helpers.ThrowIfNull(srgsGrammar, nameof(srgsGrammar)); + ArgumentNullException.ThrowIfNull(srgsGrammar); Load(srgsGrammar); } public SrgsDocument(GrammarBuilder builder) { - Helpers.ThrowIfNull(builder, nameof(builder)); + ArgumentNullException.ThrowIfNull(builder); // New grammar _grammar = new SrgsGrammar @@ -64,7 +64,7 @@ public SrgsDocument(GrammarBuilder builder) public SrgsDocument(SrgsRule grammarRootRule) : this() { - Helpers.ThrowIfNull(grammarRootRule, nameof(grammarRootRule)); + ArgumentNullException.ThrowIfNull(grammarRootRule); Root = grammarRootRule; Rules.Add(grammarRootRule); @@ -75,7 +75,7 @@ public SrgsDocument(SrgsRule grammarRootRule) : this() #region public methods public void WriteSrgs(XmlWriter srgsGrammar) { - Helpers.ThrowIfNull(srgsGrammar, nameof(srgsGrammar)); + ArgumentNullException.ThrowIfNull(srgsGrammar); // Make sure the grammar is ok _grammar.Validate(); @@ -117,7 +117,7 @@ public CultureInfo Culture } set { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); if (value.Equals(CultureInfo.InvariantCulture)) { throw new ArgumentException(SR.Get(SRID.InvariantCultureInfo), nameof(value)); diff --git a/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsElementList.cs b/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsElementList.cs index 2bfaeaf1dc08a7..21875750af81e6 100644 --- a/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsElementList.cs +++ b/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsElementList.cs @@ -13,7 +13,7 @@ internal class SrgsElementList : Collection protected override void InsertItem(int index, SrgsElement element) { - Helpers.ThrowIfNull(element, nameof(element)); + ArgumentNullException.ThrowIfNull(element); base.InsertItem(index, element); } diff --git a/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsGrammar.cs b/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsGrammar.cs index 469ce61d829b03..2a6697fad39cc6 100644 --- a/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsGrammar.cs +++ b/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsGrammar.cs @@ -303,7 +303,7 @@ public CultureInfo Culture } set { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); _culture = value; } diff --git a/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsGrammarCompiler.cs b/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsGrammarCompiler.cs index 8418c2fe9019a3..25db585f949c4d 100644 --- a/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsGrammarCompiler.cs +++ b/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsGrammarCompiler.cs @@ -22,7 +22,7 @@ public static class SrgsGrammarCompiler public static void Compile(string inputPath, Stream outputStream) { Helpers.ThrowIfEmptyOrNull(inputPath, nameof(inputPath)); - Helpers.ThrowIfNull(outputStream, nameof(outputStream)); + ArgumentNullException.ThrowIfNull(outputStream); using (XmlTextReader reader = new(new Uri(inputPath, UriKind.RelativeOrAbsolute).ToString())) { @@ -35,8 +35,8 @@ public static void Compile(string inputPath, Stream outputStream) /// public static void Compile(SrgsDocument srgsGrammar, Stream outputStream) { - Helpers.ThrowIfNull(srgsGrammar, nameof(srgsGrammar)); - Helpers.ThrowIfNull(outputStream, nameof(outputStream)); + ArgumentNullException.ThrowIfNull(srgsGrammar); + ArgumentNullException.ThrowIfNull(outputStream); SrgsCompiler.CompileStream(srgsGrammar, null, outputStream, true, null, null); } @@ -46,8 +46,8 @@ public static void Compile(SrgsDocument srgsGrammar, Stream outputStream) /// public static void Compile(XmlReader reader, Stream outputStream) { - Helpers.ThrowIfNull(reader, nameof(reader)); - Helpers.ThrowIfNull(outputStream, nameof(outputStream)); + ArgumentNullException.ThrowIfNull(reader); + ArgumentNullException.ThrowIfNull(outputStream); SrgsCompiler.CompileStream(new XmlReader[] { reader }, null, outputStream, true, null, null, null); } @@ -57,7 +57,7 @@ public static void Compile(XmlReader reader, Stream outputStream) /// public static void CompileClassLibrary(string[] inputPaths, string outputPath, string[] referencedAssemblies, string keyFile) { - Helpers.ThrowIfNull(inputPaths, nameof(inputPaths)); + ArgumentNullException.ThrowIfNull(inputPaths); Helpers.ThrowIfEmptyOrNull(outputPath, nameof(outputPath)); XmlTextReader[] readers = new XmlTextReader[inputPaths.Length]; @@ -91,7 +91,7 @@ public static void CompileClassLibrary(string[] inputPaths, string outputPath, s /// public static void CompileClassLibrary(SrgsDocument srgsGrammar, string outputPath, string[] referencedAssemblies, string keyFile) { - Helpers.ThrowIfNull(srgsGrammar, nameof(srgsGrammar)); + ArgumentNullException.ThrowIfNull(srgsGrammar); Helpers.ThrowIfEmptyOrNull(outputPath, nameof(outputPath)); SrgsCompiler.CompileStream(srgsGrammar, outputPath, null, false, referencedAssemblies, keyFile); @@ -102,7 +102,7 @@ public static void CompileClassLibrary(SrgsDocument srgsGrammar, string outputPa /// public static void CompileClassLibrary(XmlReader reader, string outputPath, string[] referencedAssemblies, string keyFile) { - Helpers.ThrowIfNull(reader, nameof(reader)); + ArgumentNullException.ThrowIfNull(reader); Helpers.ThrowIfEmptyOrNull(outputPath, nameof(outputPath)); SrgsCompiler.CompileStream(new XmlReader[] { reader }, outputPath, null, false, null, referencedAssemblies, keyFile); diff --git a/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsItem.cs b/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsItem.cs index c26fb7638ef737..81342ba5c3b779 100644 --- a/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsItem.cs +++ b/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsItem.cs @@ -31,7 +31,7 @@ public SrgsItem(string text) public SrgsItem(params SrgsElement[] elements) : this() { - Helpers.ThrowIfNull(elements, nameof(elements)); + ArgumentNullException.ThrowIfNull(elements); for (int iElement = 0; iElement < elements.Length; iElement++) { @@ -99,7 +99,7 @@ public void SetRepeat(int minRepeat, int maxRepeat) } public void Add(SrgsElement element) { - Helpers.ThrowIfNull(element, nameof(element)); + ArgumentNullException.ThrowIfNull(element); Elements.Add(element); } diff --git a/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsItemList.cs b/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsItemList.cs index 86d75c6fc8d49a..f12be3fbc5a9e4 100644 --- a/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsItemList.cs +++ b/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsItemList.cs @@ -13,7 +13,7 @@ internal class SrgsItemList : Collection protected override void InsertItem(int index, SrgsItem item) { - Helpers.ThrowIfNull(item, nameof(item)); + ArgumentNullException.ThrowIfNull(item); base.InsertItem(index, item); } diff --git a/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsNameValueTag.cs b/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsNameValueTag.cs index 5a2676247f8347..41baac794a5600 100644 --- a/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsNameValueTag.cs +++ b/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsNameValueTag.cs @@ -20,7 +20,7 @@ public SrgsNameValueTag() } public SrgsNameValueTag(object value) { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); Value = value; } @@ -54,7 +54,7 @@ public object Value get { return _value; } set { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); if ((value is string) || (value is bool) || diff --git a/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsOneOf.cs b/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsOneOf.cs index b787331ba27ab3..7ac78f080b3426 100644 --- a/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsOneOf.cs +++ b/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsOneOf.cs @@ -22,7 +22,7 @@ public SrgsOneOf() public SrgsOneOf(params string[] items) : this() { - Helpers.ThrowIfNull(items, nameof(items)); + ArgumentNullException.ThrowIfNull(items); for (int i = 0; i < items.Length; i++) { @@ -37,7 +37,7 @@ public SrgsOneOf(params string[] items) public SrgsOneOf(params SrgsItem[] items) : this() { - Helpers.ThrowIfNull(items, nameof(items)); + ArgumentNullException.ThrowIfNull(items); for (int i = 0; i < items.Length; i++) { @@ -56,7 +56,7 @@ public SrgsOneOf(params SrgsItem[] items) #region public Method public void Add(SrgsItem item) { - Helpers.ThrowIfNull(item, nameof(item)); + ArgumentNullException.ThrowIfNull(item); Items.Add(item); } diff --git a/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsRule.cs b/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsRule.cs index 030fe78a4780b9..776c664415f248 100644 --- a/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsRule.cs +++ b/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsRule.cs @@ -31,7 +31,7 @@ public SrgsRule(string id) public SrgsRule(string id, params SrgsElement[] elements) : this() { - Helpers.ThrowIfNull(elements, nameof(elements)); + ArgumentNullException.ThrowIfNull(elements); XmlParser.ValidateRuleId(id); Id = id; @@ -51,7 +51,7 @@ public SrgsRule(string id, params SrgsElement[] elements) #region public Method public void Add(SrgsElement element) { - Helpers.ThrowIfNull(element, nameof(element)); + ArgumentNullException.ThrowIfNull(element); Elements.Add(element); } diff --git a/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsRuleRef.cs b/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsRuleRef.cs index 77e81deee86f48..4fa675f88efdb3 100644 --- a/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsRuleRef.cs +++ b/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsRuleRef.cs @@ -40,7 +40,7 @@ public SrgsRuleRef(Uri uri, string rule, string semanticKey, string parameters) } public SrgsRuleRef(SrgsRule rule) { - Helpers.ThrowIfNull(rule, nameof(rule)); + ArgumentNullException.ThrowIfNull(rule); _uri = new Uri("#" + rule.Id, UriKind.Relative); } @@ -242,7 +242,7 @@ internal override string DebuggerDisplayString() /// private void UriInit(Uri uri, string rule, string semanticKey, string initParameters) { - Helpers.ThrowIfNull(uri, nameof(uri)); + ArgumentNullException.ThrowIfNull(uri); if (string.IsNullOrEmpty(rule)) { diff --git a/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsRulesCollection.cs b/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsRulesCollection.cs index 3b0f2e17b59fd5..86bb4c2e318cd7 100644 --- a/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsRulesCollection.cs +++ b/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsRulesCollection.cs @@ -11,7 +11,7 @@ public sealed class SrgsRulesCollection : KeyedCollection { public void Add(params SrgsRule[] rules) { - Helpers.ThrowIfNull(rules, nameof(rules)); + ArgumentNullException.ThrowIfNull(rules); for (int iRule = 0; iRule < rules.Length; iRule++) { diff --git a/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsSemanticInterpretationTag.cs b/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsSemanticInterpretationTag.cs index 8a77b9f2bd48d8..a0dc00b7305ed6 100644 --- a/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsSemanticInterpretationTag.cs +++ b/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsSemanticInterpretationTag.cs @@ -19,7 +19,7 @@ public SrgsSemanticInterpretationTag() } public SrgsSemanticInterpretationTag(string script) { - Helpers.ThrowIfNull(script, nameof(script)); + ArgumentNullException.ThrowIfNull(script); _script = script; } @@ -35,7 +35,7 @@ public string Script } set { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); _script = value; } diff --git a/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsText.cs b/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsText.cs index 18142e5442846b..c3ad65b9d87900 100644 --- a/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsText.cs +++ b/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsText.cs @@ -18,7 +18,7 @@ public SrgsText() } public SrgsText(string text) { - Helpers.ThrowIfNull(text, nameof(text)); + ArgumentNullException.ThrowIfNull(text); Text = text; } @@ -34,7 +34,7 @@ public string Text } set { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); // Parse the text to check for errors XmlParser.ParseText(null, value, null, null, -1f, null); diff --git a/src/libraries/System.Speech/src/Result/RecognitionResult.cs b/src/libraries/System.Speech/src/Result/RecognitionResult.cs index c8146ff4eb224d..75e49157ef1bb8 100644 --- a/src/libraries/System.Speech/src/Result/RecognitionResult.cs +++ b/src/libraries/System.Speech/src/Result/RecognitionResult.cs @@ -62,8 +62,8 @@ private RecognitionResult(SerializationInfo info, StreamingContext context) #region Public Methods public RecognizedAudio GetAudioForWordRange(RecognizedWordUnit firstWord, RecognizedWordUnit lastWord) { - Helpers.ThrowIfNull(firstWord, nameof(firstWord)); - Helpers.ThrowIfNull(lastWord, nameof(lastWord)); + ArgumentNullException.ThrowIfNull(firstWord); + ArgumentNullException.ThrowIfNull(lastWord); return Audio.GetRange(firstWord._audioPosition, lastWord._audioPosition + lastWord._audioDuration - firstWord._audioPosition); } @@ -71,7 +71,7 @@ public RecognizedAudio GetAudioForWordRange(RecognizedWordUnit firstWord, Recogn #pragma warning disable SYSLIB0050 // Legacy formatter infrastructure is obsolete void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { - Helpers.ThrowIfNull(info, nameof(info)); + ArgumentNullException.ThrowIfNull(info); bool appDomainTransition = context.State == StreamingContextStates.CrossAppDomain; diff --git a/src/libraries/System.Speech/src/Result/RecognizedAudio.cs b/src/libraries/System.Speech/src/Result/RecognizedAudio.cs index 6fdca205667cbc..341e1aff2f8d02 100644 --- a/src/libraries/System.Speech/src/Result/RecognizedAudio.cs +++ b/src/libraries/System.Speech/src/Result/RecognizedAudio.cs @@ -45,7 +45,7 @@ public TimeSpan Duration // Different ways to store the audio, either as a binary data stream or as a wave file. public void WriteToWaveStream(Stream outputStream) { - Helpers.ThrowIfNull(outputStream, nameof(outputStream)); + ArgumentNullException.ThrowIfNull(outputStream); using (StreamMarshaler sm = new(outputStream)) { @@ -61,7 +61,7 @@ public void WriteToWaveStream(Stream outputStream) // Different ways to store the audio, either as a binary data stream or as a wave file. public void WriteToAudioStream(Stream outputStream) { - Helpers.ThrowIfNull(outputStream, nameof(outputStream)); + ArgumentNullException.ThrowIfNull(outputStream); // now write the raw data outputStream.Write(_rawAudioData, 0, _rawAudioData.Length); diff --git a/src/libraries/System.Speech/src/Result/SemanticValue.cs b/src/libraries/System.Speech/src/Result/SemanticValue.cs index 7f03ed9b793301..b20ce1c7fad81c 100644 --- a/src/libraries/System.Speech/src/Result/SemanticValue.cs +++ b/src/libraries/System.Speech/src/Result/SemanticValue.cs @@ -18,7 +18,7 @@ public sealed class SemanticValue : IDictionary #pragma warning disable 6504, 56507 public SemanticValue(string keyName, object value, float confidence) { - Helpers.ThrowIfNull(keyName, nameof(keyName)); + ArgumentNullException.ThrowIfNull(keyName); _dictionary = new Dictionary(); _confidence = confidence; diff --git a/src/libraries/System.Speech/src/Synthesis/Prompt.cs b/src/libraries/System.Speech/src/Synthesis/Prompt.cs index 4c281cb8dbbe0a..7f56e5f4339d27 100644 --- a/src/libraries/System.Speech/src/Synthesis/Prompt.cs +++ b/src/libraries/System.Speech/src/Synthesis/Prompt.cs @@ -17,7 +17,7 @@ public Prompt(string textToSpeak) } public Prompt(PromptBuilder promptBuilder) { - Helpers.ThrowIfNull(promptBuilder, nameof(promptBuilder)); + ArgumentNullException.ThrowIfNull(promptBuilder); _text = promptBuilder.ToXml(); _media = SynthesisMediaType.Ssml; @@ -26,7 +26,7 @@ public Prompt(PromptBuilder promptBuilder) // Disable parameter validation check for empty strings public Prompt(string textToSpeak, SynthesisTextFormat media) { - Helpers.ThrowIfNull(textToSpeak, nameof(textToSpeak)); + ArgumentNullException.ThrowIfNull(textToSpeak); switch (_media = (SynthesisMediaType)media) { @@ -41,7 +41,7 @@ public Prompt(string textToSpeak, SynthesisTextFormat media) } internal Prompt(Uri promptFile, SynthesisMediaType media) { - Helpers.ThrowIfNull(promptFile, nameof(promptFile)); + ArgumentNullException.ThrowIfNull(promptFile); switch (_media = media) { diff --git a/src/libraries/System.Speech/src/Synthesis/PromptBuilder.cs b/src/libraries/System.Speech/src/Synthesis/PromptBuilder.cs index 5cabd2f19490f9..3d9dee757eb473 100644 --- a/src/libraries/System.Speech/src/Synthesis/PromptBuilder.cs +++ b/src/libraries/System.Speech/src/Synthesis/PromptBuilder.cs @@ -22,7 +22,7 @@ public PromptBuilder() } public PromptBuilder(CultureInfo culture) { - Helpers.ThrowIfNull(culture, nameof(culture)); + ArgumentNullException.ThrowIfNull(culture); if (culture.Equals(CultureInfo.InvariantCulture)) { @@ -54,7 +54,7 @@ public void ClearContent() /// public void AppendText(string textToSpeak) { - Helpers.ThrowIfNull(textToSpeak, nameof(textToSpeak)); + ArgumentNullException.ThrowIfNull(textToSpeak); // Validate that text can be added in this context ValidateElement(_elementStack.Peek(), SsmlElement.Text); @@ -63,7 +63,7 @@ public void AppendText(string textToSpeak) } public void AppendText(string textToSpeak, PromptRate rate) { - Helpers.ThrowIfNull(textToSpeak, nameof(textToSpeak)); + ArgumentNullException.ThrowIfNull(textToSpeak); if (rate < PromptRate.NotSet || rate > PromptRate.ExtraSlow) { @@ -101,7 +101,7 @@ public void AppendText(string textToSpeak, PromptRate rate) } public void AppendText(string textToSpeak, PromptVolume volume) { - Helpers.ThrowIfNull(textToSpeak, nameof(textToSpeak)); + ArgumentNullException.ThrowIfNull(textToSpeak); if (volume < PromptVolume.NotSet || volume > PromptVolume.Default) { @@ -141,7 +141,7 @@ public void AppendText(string textToSpeak, PromptVolume volume) } public void AppendText(string textToSpeak, PromptEmphasis emphasis) { - Helpers.ThrowIfNull(textToSpeak, nameof(textToSpeak)); + ArgumentNullException.ThrowIfNull(textToSpeak); if (emphasis < PromptEmphasis.NotSet || emphasis > PromptEmphasis.Reduced) { @@ -162,7 +162,7 @@ public void AppendText(string textToSpeak, PromptEmphasis emphasis) } public void StartStyle(PromptStyle style) { - Helpers.ThrowIfNull(style, nameof(style)); + ArgumentNullException.ThrowIfNull(style); // Validate that text can be added in this context StackElement stackElement = _elementStack.Peek(); @@ -268,7 +268,7 @@ public void EndStyle() } public void StartVoice(VoiceInfo voice) { - Helpers.ThrowIfNull(voice, nameof(voice)); + ArgumentNullException.ThrowIfNull(voice); if (!VoiceInfo.ValidateGender(voice.Gender)) { @@ -424,7 +424,7 @@ public void EndSentence() } public void AppendTextWithHint(string textToSpeak, SayAs sayAs) { - Helpers.ThrowIfNull(textToSpeak, nameof(textToSpeak)); + ArgumentNullException.ThrowIfNull(textToSpeak); if (sayAs < SayAs.SpellOut || sayAs > SayAs.Text) { @@ -543,7 +543,7 @@ public void AppendTextWithHint(string textToSpeak, SayAs sayAs) } public void AppendTextWithHint(string textToSpeak, string sayAs) { - Helpers.ThrowIfNull(textToSpeak, nameof(textToSpeak)); + ArgumentNullException.ThrowIfNull(textToSpeak); Helpers.ThrowIfEmptyOrNull(sayAs, nameof(sayAs)); // check for well formed document @@ -574,8 +574,8 @@ public void AppendTextWithPronunciation(string textToSpeak, string pronunciation } public void AppendTextWithAlias(string textToSpeak, string substitute) { - Helpers.ThrowIfNull(textToSpeak, nameof(textToSpeak)); - Helpers.ThrowIfNull(substitute, nameof(substitute)); + ArgumentNullException.ThrowIfNull(textToSpeak); + ArgumentNullException.ThrowIfNull(substitute); // check for well formed document ValidateElement(_elementStack.Peek(), SsmlElement.Text); @@ -675,7 +675,7 @@ public void AppendAudio(string path) } public void AppendAudio(Uri audioFile) { - Helpers.ThrowIfNull(audioFile, nameof(audioFile)); + ArgumentNullException.ThrowIfNull(audioFile); // check for well formed document ValidateElement(_elementStack.Peek(), SsmlElement.Audio); @@ -688,8 +688,8 @@ public void AppendAudio(Uri audioFile) } public void AppendAudio(Uri audioFile, string alternateText) { - Helpers.ThrowIfNull(audioFile, nameof(audioFile)); - Helpers.ThrowIfNull(alternateText, nameof(alternateText)); + ArgumentNullException.ThrowIfNull(audioFile); + ArgumentNullException.ThrowIfNull(alternateText); // check for well formed document ValidateElement(_elementStack.Peek(), SsmlElement.Audio); @@ -717,7 +717,7 @@ public void AppendBookmark(string bookmarkName) } public void AppendPromptBuilder(PromptBuilder promptBuilder) { - Helpers.ThrowIfNull(promptBuilder, nameof(promptBuilder)); + ArgumentNullException.ThrowIfNull(promptBuilder); StringReader sr = new(promptBuilder.ToXml()); XmlTextReader reader = new(sr); @@ -733,7 +733,7 @@ public void AppendSsml(string path) } public void AppendSsml(Uri ssmlFile) { - Helpers.ThrowIfNull(ssmlFile, nameof(ssmlFile)); + ArgumentNullException.ThrowIfNull(ssmlFile); string localFile; Uri redirectUri; @@ -751,7 +751,7 @@ public void AppendSsml(Uri ssmlFile) } public void AppendSsml(XmlReader ssmlFile) { - Helpers.ThrowIfNull(ssmlFile, nameof(ssmlFile)); + ArgumentNullException.ThrowIfNull(ssmlFile); AppendSsmlInternal(ssmlFile); } @@ -832,10 +832,7 @@ public CultureInfo Culture } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _culture = value; } diff --git a/src/libraries/System.Speech/src/Synthesis/SpeechSynthesizer.cs b/src/libraries/System.Speech/src/Synthesis/SpeechSynthesizer.cs index cce89a9df95ce9..9ce5166bb57914 100644 --- a/src/libraries/System.Speech/src/Synthesis/SpeechSynthesizer.cs +++ b/src/libraries/System.Speech/src/Synthesis/SpeechSynthesizer.cs @@ -58,7 +58,7 @@ public void SelectVoiceByHints(VoiceGender gender, VoiceAge age, int voiceAltern } public void SelectVoiceByHints(VoiceGender gender, VoiceAge age, int voiceAlternate, CultureInfo culture) { - Helpers.ThrowIfNull(culture, nameof(culture)); + ArgumentNullException.ThrowIfNull(culture); if (voiceAlternate < 0) { @@ -85,7 +85,7 @@ public void SelectVoiceByHints(VoiceGender gender, VoiceAge age, int voiceAltern } public Prompt SpeakAsync(string textToSpeak) { - Helpers.ThrowIfNull(textToSpeak, nameof(textToSpeak)); + ArgumentNullException.ThrowIfNull(textToSpeak); Prompt prompt = new(textToSpeak, SynthesisTextFormat.Text); SpeakAsync(prompt); @@ -93,14 +93,14 @@ public Prompt SpeakAsync(string textToSpeak) } public void SpeakAsync(Prompt prompt) { - Helpers.ThrowIfNull(prompt, nameof(prompt)); + ArgumentNullException.ThrowIfNull(prompt); prompt.Synthesizer = this; VoiceSynthesizer.SpeakAsync(prompt); } public Prompt SpeakSsmlAsync(string textToSpeak) { - Helpers.ThrowIfNull(textToSpeak, nameof(textToSpeak)); + ArgumentNullException.ThrowIfNull(textToSpeak); Prompt prompt = new(textToSpeak, SynthesisTextFormat.Ssml); SpeakAsync(prompt); @@ -108,7 +108,7 @@ public Prompt SpeakSsmlAsync(string textToSpeak) } public Prompt SpeakAsync(PromptBuilder promptBuilder) { - Helpers.ThrowIfNull(promptBuilder, nameof(promptBuilder)); + ArgumentNullException.ThrowIfNull(promptBuilder); Prompt prompt = new(promptBuilder); SpeakAsync(prompt); @@ -120,7 +120,7 @@ public void Speak(string textToSpeak) } public void Speak(Prompt prompt) { - Helpers.ThrowIfNull(prompt, nameof(prompt)); + ArgumentNullException.ThrowIfNull(prompt); // Avoid a dead lock if the synthesizer is Paused if (State == SynthesizerState.Paused) @@ -171,7 +171,7 @@ public void Resume() /// public void SpeakAsyncCancel(Prompt prompt) { - Helpers.ThrowIfNull(prompt, nameof(prompt)); + ArgumentNullException.ThrowIfNull(prompt); VoiceSynthesizer.Abort(prompt); } @@ -195,21 +195,21 @@ public void SetOutputToWaveFile(string path) public void SetOutputToWaveFile(string path, SpeechAudioFormatInfo formatInfo) { Helpers.ThrowIfEmptyOrNull(path, nameof(path)); - Helpers.ThrowIfNull(formatInfo, nameof(formatInfo)); + ArgumentNullException.ThrowIfNull(formatInfo); SetOutputToNull(); SetOutputStream(new FileStream(path, FileMode.Create, FileAccess.Write), formatInfo, true, true); } public void SetOutputToWaveStream(Stream audioDestination) { - Helpers.ThrowIfNull(audioDestination, nameof(audioDestination)); + ArgumentNullException.ThrowIfNull(audioDestination); SetOutputStream(audioDestination, null, true, false); } public void SetOutputToAudioStream(Stream audioDestination, SpeechAudioFormatInfo formatInfo) { - Helpers.ThrowIfNull(audioDestination, nameof(audioDestination)); - Helpers.ThrowIfNull(formatInfo, nameof(formatInfo)); + ArgumentNullException.ThrowIfNull(audioDestination); + ArgumentNullException.ThrowIfNull(formatInfo); SetOutputStream(audioDestination, formatInfo, false, false); } @@ -246,7 +246,7 @@ public ReadOnlyCollection GetInstalledVoices() } public ReadOnlyCollection GetInstalledVoices(CultureInfo culture) { - Helpers.ThrowIfNull(culture, nameof(culture)); + ArgumentNullException.ThrowIfNull(culture); if (culture.Equals(CultureInfo.InvariantCulture)) { @@ -257,13 +257,13 @@ public ReadOnlyCollection GetInstalledVoices(CultureInfo culture } public void AddLexicon(Uri uri, string mediaType) { - Helpers.ThrowIfNull(uri, nameof(uri)); + ArgumentNullException.ThrowIfNull(uri); VoiceSynthesizer.AddLexicon(uri, mediaType); } public void RemoveLexicon(Uri uri) { - Helpers.ThrowIfNull(uri, nameof(uri)); + ArgumentNullException.ThrowIfNull(uri); VoiceSynthesizer.RemoveLexicon(uri); } @@ -274,13 +274,13 @@ public event EventHandler SpeakStarted [MethodImplAttribute(MethodImplOptions.Synchronized)] add { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); VoiceSynthesizer._speakStarted += value; } [MethodImplAttribute(MethodImplOptions.Synchronized)] remove { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); VoiceSynthesizer._speakStarted -= value; } } @@ -289,13 +289,13 @@ public event EventHandler SpeakCompleted [MethodImplAttribute(MethodImplOptions.Synchronized)] add { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); VoiceSynthesizer._speakCompleted += value; } [MethodImplAttribute(MethodImplOptions.Synchronized)] remove { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); VoiceSynthesizer._speakCompleted -= value; } } @@ -304,13 +304,13 @@ public event EventHandler SpeakProgress [MethodImplAttribute(MethodImplOptions.Synchronized)] add { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); VoiceSynthesizer.AddEvent(TtsEventId.WordBoundary, ref VoiceSynthesizer._speakProgress, value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] remove { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); VoiceSynthesizer.RemoveEvent(TtsEventId.WordBoundary, ref VoiceSynthesizer._speakProgress, value); } } @@ -319,13 +319,13 @@ public event EventHandler BookmarkReached [MethodImplAttribute(MethodImplOptions.Synchronized)] add { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); VoiceSynthesizer.AddEvent(TtsEventId.Bookmark, ref VoiceSynthesizer._bookmarkReached, value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] remove { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); VoiceSynthesizer.RemoveEvent(TtsEventId.Bookmark, ref VoiceSynthesizer._bookmarkReached, value); } } @@ -334,13 +334,13 @@ public event EventHandler VoiceChange [MethodImplAttribute(MethodImplOptions.Synchronized)] add { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); VoiceSynthesizer.AddEvent(TtsEventId.VoiceChange, ref VoiceSynthesizer._voiceChange, value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] remove { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); VoiceSynthesizer.RemoveEvent(TtsEventId.VoiceChange, ref VoiceSynthesizer._voiceChange, value); } } @@ -351,13 +351,13 @@ public event EventHandler PhonemeReached [MethodImplAttribute(MethodImplOptions.Synchronized)] add { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); VoiceSynthesizer.AddEvent(TtsEventId.Phoneme, ref VoiceSynthesizer._phonemeReached, value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] remove { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); VoiceSynthesizer.RemoveEvent(TtsEventId.Phoneme, ref VoiceSynthesizer._phonemeReached, value); } } @@ -366,13 +366,13 @@ public event EventHandler VisemeReached [MethodImplAttribute(MethodImplOptions.Synchronized)] add { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); VoiceSynthesizer.AddEvent(TtsEventId.Viseme, ref VoiceSynthesizer._visemeReached, value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] remove { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); VoiceSynthesizer.RemoveEvent(TtsEventId.Viseme, ref VoiceSynthesizer._visemeReached, value); } } @@ -383,13 +383,13 @@ public event EventHandler StateChanged [MethodImplAttribute(MethodImplOptions.Synchronized)] add { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); VoiceSynthesizer._stateChanged += value; } [MethodImplAttribute(MethodImplOptions.Synchronized)] remove { - Helpers.ThrowIfNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(value); VoiceSynthesizer._stateChanged -= value; } } diff --git a/src/libraries/System.Speech/src/Synthesis/TTSEngine/TTSEngineTypes.cs b/src/libraries/System.Speech/src/Synthesis/TTSEngine/TTSEngineTypes.cs index 68dc82082025e2..88152217ca42b3 100644 --- a/src/libraries/System.Speech/src/Synthesis/TTSEngine/TTSEngineTypes.cs +++ b/src/libraries/System.Speech/src/Synthesis/TTSEngine/TTSEngineTypes.cs @@ -216,9 +216,9 @@ public struct FragmentState : IEquatable public int LangId { get { return _langId; } internal set { _langId = value; } } public int Emphasis { get { return _emphasis; } internal set { _emphasis = value; } } public int Duration { get { return _duration; } internal set { _duration = value; } } - public SayAs SayAs { get { return _sayAs; } internal set { Helpers.ThrowIfNull(value, nameof(value)); _sayAs = value; } } - public Prosody Prosody { get { return _prosody; } internal set { Helpers.ThrowIfNull(value, nameof(value)); _prosody = value; } } - public char[] Phoneme { get { return _phoneme; } internal set { Helpers.ThrowIfNull(value, nameof(value)); _phoneme = value; } } + public SayAs SayAs { get { return _sayAs; } internal set { ArgumentNullException.ThrowIfNull(value); _sayAs = value; } } + public Prosody Prosody { get { return _prosody; } internal set { ArgumentNullException.ThrowIfNull(value); _prosody = value; } } + public char[] Phoneme { get { return _phoneme; } internal set { ArgumentNullException.ThrowIfNull(value); _phoneme = value; } } public FragmentState(TtsEngineAction action, int langId, int emphasis, @@ -280,7 +280,7 @@ public class Prosody public ContourPoint[] GetContourPoints() { return _contourPoints; } public void SetContourPoints(ContourPoint[] points) { - Helpers.ThrowIfNull(points, nameof(points)); + ArgumentNullException.ThrowIfNull(points); _contourPoints = (ContourPoint[])points.Clone(); } diff --git a/src/libraries/System.Speech/src/Synthesis/VoiceInfo.cs b/src/libraries/System.Speech/src/Synthesis/VoiceInfo.cs index 10f432b90429c0..a4034e25ae3778 100644 --- a/src/libraries/System.Speech/src/Synthesis/VoiceInfo.cs +++ b/src/libraries/System.Speech/src/Synthesis/VoiceInfo.cs @@ -26,7 +26,7 @@ internal VoiceInfo(string name) internal VoiceInfo(CultureInfo culture) { // Fails if no culture is provided - Helpers.ThrowIfNull(culture, nameof(culture)); + ArgumentNullException.ThrowIfNull(culture); if (culture.Equals(CultureInfo.InvariantCulture)) { diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DecoderNLS.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DecoderNLS.cs index 1858c3d4940e10..84305755b0caee 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DecoderNLS.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DecoderNLS.cs @@ -79,8 +79,7 @@ public override unsafe int GetCharCount(byte[] bytes, int index, int count) public override unsafe int GetCharCount(byte[] bytes, int index, int count, bool flush) { - if (bytes is null) - throw new ArgumentNullException(nameof(bytes)); + ArgumentNullException.ThrowIfNull(bytes); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -120,11 +119,8 @@ public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, bool flush) { - if (bytes is null) - throw new ArgumentNullException(nameof(bytes)); - - if (chars is null) - throw new ArgumentNullException(nameof(chars)); + ArgumentNullException.ThrowIfNull(bytes); + ArgumentNullException.ThrowIfNull(chars); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -172,11 +168,8 @@ public override unsafe void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { - if (bytes is null) - throw new ArgumentNullException(nameof(bytes)); - - if (chars is null) - throw new ArgumentNullException(nameof(chars)); + ArgumentNullException.ThrowIfNull(bytes); + ArgumentNullException.ThrowIfNull(chars); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncoderNLS.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncoderNLS.cs index d8cfb558c801b1..80d33ad18e6700 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncoderNLS.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncoderNLS.cs @@ -77,8 +77,7 @@ public override void Reset() public override unsafe int GetByteCount(char[] chars, int index, int count, bool flush) { - if (chars is null) - throw new ArgumentNullException(nameof(chars)); + ArgumentNullException.ThrowIfNull(chars); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -109,11 +108,8 @@ public override unsafe int GetByteCount(char* chars, int count, bool flush) public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, bool flush) { - if (chars is null) - throw new ArgumentNullException(nameof(chars)); - - if (bytes is null) - throw new ArgumentNullException(nameof(bytes)); + ArgumentNullException.ThrowIfNull(chars); + ArgumentNullException.ThrowIfNull(bytes); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -157,11 +153,8 @@ public override unsafe void Convert(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { - if (chars is null) - throw new ArgumentNullException(nameof(chars)); - - if (bytes is null) - throw new ArgumentNullException(nameof(bytes)); + ArgumentNullException.ThrowIfNull(chars); + ArgumentNullException.ThrowIfNull(bytes); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncodingNLS.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncodingNLS.cs index a5c2c085583ac3..20ab8cf22afa9f 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncodingNLS.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncodingNLS.cs @@ -48,8 +48,7 @@ protected EncodingNLS(int codePage, EncoderFallback enc, DecoderFallback dec) // parent method is safe public override unsafe int GetByteCount(char[] chars, int index, int count) { - if (chars is null) - throw new ArgumentNullException(nameof(chars)); + ArgumentNullException.ThrowIfNull(chars); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -71,8 +70,7 @@ public override unsafe int GetByteCount(char[] chars, int index, int count) // parent method is safe public override unsafe int GetByteCount(string s) { - if (s is null) - throw new ArgumentNullException(nameof(s)); + ArgumentNullException.ThrowIfNull(s); fixed (char* pChars = s) return GetByteCount(pChars, s.Length, null); @@ -99,11 +97,8 @@ public override unsafe int GetByteCount(char* chars, int count) public override unsafe int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { - if (s is null) - throw new ArgumentNullException(nameof(s)); - - if (bytes is null) - throw new ArgumentNullException(nameof(bytes)); + ArgumentNullException.ThrowIfNull(s); + ArgumentNullException.ThrowIfNull(bytes); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -139,11 +134,8 @@ public override unsafe int GetBytes(string s, int charIndex, int charCount, public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { - if (chars is null) - throw new ArgumentNullException(nameof(chars)); - - if (bytes is null) - throw new ArgumentNullException(nameof(bytes)); + ArgumentNullException.ThrowIfNull(chars); + ArgumentNullException.ThrowIfNull(bytes); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -194,8 +186,7 @@ public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int // parent method is safe public override unsafe int GetCharCount(byte[] bytes, int index, int count) { - if (bytes is null) - throw new ArgumentNullException(nameof(bytes)); + ArgumentNullException.ThrowIfNull(bytes); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -231,11 +222,8 @@ public override unsafe int GetCharCount(byte* bytes, int count) public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { - if (bytes is null) - throw new ArgumentNullException(nameof(bytes)); - - if (chars is null) - throw new ArgumentNullException(nameof(chars)); + ArgumentNullException.ThrowIfNull(bytes); + ArgumentNullException.ThrowIfNull(chars); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -286,8 +274,7 @@ public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int // parent method is safe public override unsafe string GetString(byte[] bytes, int index, int count) { - if (bytes is null) - throw new ArgumentNullException(nameof(bytes)); + ArgumentNullException.ThrowIfNull(bytes); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); diff --git a/src/libraries/System.Text.Json/Common/JsonSeparatorNamingPolicy.cs b/src/libraries/System.Text.Json/Common/JsonSeparatorNamingPolicy.cs index 80dfdfc84b3b45..2f9d03e80b9da0 100644 --- a/src/libraries/System.Text.Json/Common/JsonSeparatorNamingPolicy.cs +++ b/src/libraries/System.Text.Json/Common/JsonSeparatorNamingPolicy.cs @@ -23,10 +23,7 @@ internal JsonSeparatorNamingPolicy(bool lowercase, char separator) public sealed override string ConvertName(string name) { - if (name is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); return ConvertNameCore(_separator, _lowercase, name.AsSpan()); } diff --git a/src/libraries/System.Text.Json/src/System.Text.Json.csproj b/src/libraries/System.Text.Json/src/System.Text.Json.csproj index 0acc35d1987792..2d3b2af2e99d66 100644 --- a/src/libraries/System.Text.Json/src/System.Text.Json.csproj +++ b/src/libraries/System.Text.Json/src/System.Text.Json.csproj @@ -388,7 +388,6 @@ The System.Text.Json library is built-in as part of the shared framework in .NET - diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.Parse.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.Parse.cs index d0383eb756eecb..0d89711b5631d7 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.Parse.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.Parse.cs @@ -117,10 +117,7 @@ public static JsonDocument Parse(ReadOnlySequence utf8Json, JsonDocumentOp /// public static JsonDocument Parse(Stream utf8Json, JsonDocumentOptions options = default) { - if (utf8Json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); - } + ArgumentNullException.ThrowIfNull(utf8Json); ArraySegment drained = ReadToEnd(utf8Json); Debug.Assert(drained.Array != null); @@ -198,10 +195,7 @@ public static Task ParseAsync( JsonDocumentOptions options = default, CancellationToken cancellationToken = default) { - if (utf8Json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); - } + ArgumentNullException.ThrowIfNull(utf8Json); return ParseAsyncCore(utf8Json, options, cancellationToken); } @@ -329,10 +323,7 @@ internal static JsonDocument ParseValue(ReadOnlyMemory json, JsonDocumentO /// public static JsonDocument Parse([StringSyntax(StringSyntaxAttribute.Json)] string json, JsonDocumentOptions options = default) { - if (json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(json)); - } + ArgumentNullException.ThrowIfNull(json); return Parse(json.AsMemory(), options); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.cs index 7b3ffa246a90ca..75b177ecb28391 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.cs @@ -103,10 +103,7 @@ public void Dispose() /// public void WriteTo(Utf8JsonWriter writer) { - if (writer is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(writer)); - } + ArgumentNullException.ThrowIfNull(writer); RootElement.WriteTo(writer); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonElement.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonElement.cs index ad561c5dbff392..a4e0fd0496ef50 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonElement.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonElement.cs @@ -132,10 +132,7 @@ public int GetPropertyCount() /// public JsonElement GetProperty(string propertyName) { - if (propertyName is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); - } + ArgumentNullException.ThrowIfNull(propertyName); if (TryGetProperty(propertyName, out JsonElement property)) { @@ -255,10 +252,7 @@ public JsonElement GetProperty(ReadOnlySpan utf8PropertyName) /// public bool TryGetProperty(string propertyName, out JsonElement value) { - if (propertyName is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); - } + ArgumentNullException.ThrowIfNull(propertyName); return TryGetProperty(propertyName.AsSpan(), out value); } @@ -1550,10 +1544,7 @@ internal bool ValueIsEscapedHelper(bool isPropertyName) /// public void WriteTo(Utf8JsonWriter writer) { - if (writer is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(writer)); - } + ArgumentNullException.ThrowIfNull(writer); CheckValidInstance(); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonProperty.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonProperty.cs index c81095bfe386bf..84675bc0b4e36b 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonProperty.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonProperty.cs @@ -114,10 +114,7 @@ internal bool EscapedNameEquals(ReadOnlySpan utf8Text) /// > public void WriteTo(Utf8JsonWriter writer) { - if (writer is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(writer)); - } + ArgumentNullException.ThrowIfNull(writer); if (_name is null) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/JsonEncodedText.cs b/src/libraries/System.Text.Json/src/System/Text/Json/JsonEncodedText.cs index 10b719be833371..21bcac5cd1b65c 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/JsonEncodedText.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/JsonEncodedText.cs @@ -50,10 +50,7 @@ private JsonEncodedText(byte[] utf8Value) /// public static JsonEncodedText Encode(string value, JavaScriptEncoder? encoder = null) { - if (value is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); return Encode(value.AsSpan(), encoder); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonArray.IList.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonArray.IList.cs index 40fd817658ef27..7ffe4e7b56644c 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonArray.IList.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonArray.IList.cs @@ -124,10 +124,7 @@ public void RemoveAt(int index) /// public int RemoveAll(Func match) { - if (match == null) - { - ThrowHelper.ThrowArgumentNullException(nameof(match)); - } + ArgumentNullException.ThrowIfNull(match); return List.RemoveAll(node => { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonArray.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonArray.cs index 815a3348d4b041..54dfdd3c0c9934 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonArray.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonArray.cs @@ -263,10 +263,7 @@ internal override void GetPath(ref ValueStringBuilder path, JsonNode? child) /// public override void WriteTo(Utf8JsonWriter writer, JsonSerializerOptions? options = null) { - if (writer is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(writer)); - } + ArgumentNullException.ThrowIfNull(writer); GetUnderlyingRepresentation(out List? list, out JsonElement? jsonElement); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonNode.Parse.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonNode.Parse.cs index 2e3b083e1b4613..c5b39e3a685e72 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonNode.Parse.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonNode.Parse.cs @@ -72,10 +72,7 @@ public abstract partial class JsonNode JsonNodeOptions? nodeOptions = null, JsonDocumentOptions documentOptions = default(JsonDocumentOptions)) { - if (json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(json)); - } + ArgumentNullException.ThrowIfNull(json); JsonElement element = JsonElement.ParseValue(json, documentOptions); return JsonNodeConverter.Create(element, nodeOptions); @@ -120,10 +117,7 @@ public abstract partial class JsonNode JsonNodeOptions? nodeOptions = null, JsonDocumentOptions documentOptions = default) { - if (utf8Json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); - } + ArgumentNullException.ThrowIfNull(utf8Json); JsonElement element = JsonElement.ParseValue(utf8Json, documentOptions); return JsonNodeConverter.Create(element, nodeOptions); @@ -149,10 +143,7 @@ public abstract partial class JsonNode JsonDocumentOptions documentOptions = default, CancellationToken cancellationToken = default) { - if (utf8Json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); - } + ArgumentNullException.ThrowIfNull(utf8Json); JsonDocument document = await JsonDocument.ParseAsyncCoreUnrented(utf8Json, documentOptions, cancellationToken).ConfigureAwait(false); return JsonNodeConverter.Create(document.RootElement, nodeOptions); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.IDictionary.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.IDictionary.cs index 3de8d933a1b070..857cb57f2c7cf5 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.IDictionary.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.IDictionary.cs @@ -25,10 +25,7 @@ public partial class JsonObject : IDictionary /// public void Add(string propertyName, JsonNode? value) { - if (propertyName is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); - } + ArgumentNullException.ThrowIfNull(propertyName); Dictionary.Add(propertyName, value); value?.AssignParent(this); @@ -81,10 +78,7 @@ public void Clear() /// public bool ContainsKey(string propertyName) { - if (propertyName is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); - } + ArgumentNullException.ThrowIfNull(propertyName); return Dictionary.ContainsKey(propertyName); } @@ -106,10 +100,7 @@ public bool ContainsKey(string propertyName) /// public bool Remove(string propertyName) { - if (propertyName is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); - } + ArgumentNullException.ThrowIfNull(propertyName); bool success = Dictionary.Remove(propertyName, out JsonNode? removedNode); if (success) @@ -195,10 +186,7 @@ public bool Remove(string propertyName) /// bool IDictionary.TryGetValue(string propertyName, out JsonNode? jsonNode) { - if (propertyName is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); - } + ArgumentNullException.ThrowIfNull(propertyName); return Dictionary.TryGetValue(propertyName, out jsonNode); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.IList.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.IList.cs index 372eccdcfe016a..1f851499c52694 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.IList.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.IList.cs @@ -23,10 +23,7 @@ public partial class JsonObject : IList> /// already has a parent. public void SetAt(int index, string propertyName, JsonNode? value) { - if (propertyName is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); - } + ArgumentNullException.ThrowIfNull(propertyName); OrderedDictionary dictionary = Dictionary; KeyValuePair existing = dictionary.GetAt(index); @@ -55,10 +52,7 @@ public void SetAt(int index, JsonNode? value) /// is null. public int IndexOf(string propertyName) { - if (propertyName is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); - } + ArgumentNullException.ThrowIfNull(propertyName); return Dictionary.IndexOf(propertyName); } @@ -72,10 +66,7 @@ public int IndexOf(string propertyName) /// is less than 0 or greater than . public void Insert(int index, string propertyName, JsonNode? value) { - if (propertyName is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); - } + ArgumentNullException.ThrowIfNull(propertyName); Dictionary.Insert(index, propertyName, value); value?.AssignParent(this); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.cs index b86bf1a2ad8321..f903a005d76dfd 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.cs @@ -120,10 +120,7 @@ internal string GetPropertyName(JsonNode? node) /// public bool TryGetPropertyValue(string propertyName, out JsonNode? jsonNode) { - if (propertyName is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); - } + ArgumentNullException.ThrowIfNull(propertyName); return Dictionary.TryGetValue(propertyName, out jsonNode); } @@ -131,10 +128,7 @@ public bool TryGetPropertyValue(string propertyName, out JsonNode? jsonNode) /// public override void WriteTo(Utf8JsonWriter writer, JsonSerializerOptions? options = null) { - if (writer is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(writer)); - } + ArgumentNullException.ThrowIfNull(writer); GetUnderlyingRepresentation(out OrderedDictionary? dictionary, out JsonElement? jsonElement); @@ -202,10 +196,7 @@ internal override bool DeepEqualsCore(JsonNode node) internal JsonNode? GetItem(string propertyName) { - if (propertyName is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); - } + ArgumentNullException.ThrowIfNull(propertyName); if (TryGetPropertyValue(propertyName, out JsonNode? value)) { @@ -239,10 +230,7 @@ internal override void GetPath(ref ValueStringBuilder path, JsonNode? child) internal void SetItem(string propertyName, JsonNode? value) { - if (propertyName is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); - } + ArgumentNullException.ThrowIfNull(propertyName); OrderedDictionary dict = Dictionary; diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValue.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValue.cs index b3d72f57e28435..f4a7808f43f184 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValue.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValue.cs @@ -81,10 +81,7 @@ private protected JsonValue(JsonNodeOptions? options) : base(options) { } /// The new instance of the class that contains the specified value. public static JsonValue? Create(T? value, JsonTypeInfo jsonTypeInfo, JsonNodeOptions? options = null) { - if (jsonTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); - } + ArgumentNullException.ThrowIfNull(jsonTypeInfo); if (value is null) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueOfElement.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueOfElement.cs index ddccceb8250330..79f304d7dc43ea 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueOfElement.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueOfElement.cs @@ -196,10 +196,7 @@ public override bool TryGetValue([NotNullWhen(true)] out TypeToCo public override void WriteTo(Utf8JsonWriter writer, JsonSerializerOptions? options = null) { - if (writer is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(writer)); - } + ArgumentNullException.ThrowIfNull(writer); Value.WriteTo(writer); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueOfTCustomized.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueOfTCustomized.cs index ceaa849f957ccc..4d1e18dc1b8852 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueOfTCustomized.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueOfTCustomized.cs @@ -28,10 +28,7 @@ public JsonValueCustomized(TValue value, JsonTypeInfo jsonTypeInfo, Json public override void WriteTo(Utf8JsonWriter writer, JsonSerializerOptions? options = null) { - if (writer is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(writer)); - } + ArgumentNullException.ThrowIfNull(writer); JsonTypeInfo jsonTypeInfo = _jsonTypeInfo; diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueOfTPrimitive.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueOfTPrimitive.cs index fce1d5fbf04cf4..3e66f2141757e1 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueOfTPrimitive.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueOfTPrimitive.cs @@ -41,10 +41,7 @@ internal override bool DeepEqualsCore(JsonNode otherNode) public override void WriteTo(Utf8JsonWriter writer, JsonSerializerOptions? options = null) { - if (writer is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(writer)); - } + ArgumentNullException.ThrowIfNull(writer); JsonConverter converter = _converter; options ??= s_defaultOptions; diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Schema/JsonSchemaExporter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Schema/JsonSchemaExporter.cs index 0551255273b833..4f1de1a514b4b0 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Schema/JsonSchemaExporter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Schema/JsonSchemaExporter.cs @@ -26,15 +26,8 @@ public static class JsonSchemaExporter /// A JSON object containing the schema for . public static JsonNode GetJsonSchemaAsNode(this JsonSerializerOptions options, Type type, JsonSchemaExporterOptions? exporterOptions = null) { - if (options is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(options)); - } - - if (type is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(type)); - } + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(type); ValidateOptions(options); JsonTypeInfo typeInfo = options.GetTypeInfoInternal(type); @@ -49,10 +42,7 @@ public static JsonNode GetJsonSchemaAsNode(this JsonSerializerOptions options, T /// A JSON object containing the schema for . public static JsonNode GetJsonSchemaAsNode(this JsonTypeInfo typeInfo, JsonSchemaExporterOptions? exporterOptions = null) { - if (typeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(typeInfo)); - } + ArgumentNullException.ThrowIfNull(typeInfo); ValidateOptions(typeInfo.Options); exporterOptions ??= JsonSchemaExporterOptions.Default; diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/ConfigurationList.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/ConfigurationList.cs index 39593f39d297dd..dacb8773d8e418 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/ConfigurationList.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/ConfigurationList.cs @@ -34,10 +34,7 @@ public TItem this[int index] } set { - if (value is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); OnCollectionModifying(); ValidateAddedValue(value); @@ -50,10 +47,7 @@ public TItem this[int index] public void Add(TItem item) { - if (item is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(item)); - } + ArgumentNullException.ThrowIfNull(item); OnCollectionModifying(); ValidateAddedValue(item); @@ -90,10 +84,7 @@ public int IndexOf(TItem item) public void Insert(int index, TItem item) { - if (item is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(item)); - } + ArgumentNullException.ThrowIfNull(item); OnCollectionModifying(); ValidateAddedValue(item); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectConverter.cs index 9c0745bf851503..203e3e9b0b1ccd 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectConverter.cs @@ -48,10 +48,7 @@ public sealed override void WriteAsPropertyName(Utf8JsonWriter writer, object va internal sealed override void WriteAsPropertyNameCore(Utf8JsonWriter writer, object value, JsonSerializerOptions options, bool isWritingExtensionDataProperty) { - if (value is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); Type runtimeType = value.GetType(); if (runtimeType == Type) diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/JsonPrimitiveConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/JsonPrimitiveConverter.cs index d7330ce675423e..cb839ea56d3267 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/JsonPrimitiveConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/JsonPrimitiveConverter.cs @@ -15,10 +15,7 @@ internal abstract class JsonPrimitiveConverter : JsonConverter { public sealed override void WriteAsPropertyName(Utf8JsonWriter writer, [DisallowNull] T value, JsonSerializerOptions options) { - if (value is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); WriteAsPropertyNameCore(writer, value, options, isWritingExtensionDataProperty: false); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/StringConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/StringConverter.cs index 8a290109e7e369..075ecef03ae035 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/StringConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/StringConverter.cs @@ -35,10 +35,7 @@ internal override string ReadAsPropertyNameCore(ref Utf8JsonReader reader, Type internal override void WriteAsPropertyNameCore(Utf8JsonWriter writer, string value, JsonSerializerOptions options, bool isWritingExtensionDataProperty) { - if (value is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); if (options.DictionaryKeyPolicy != null && !isWritingExtensionDataProperty) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/UriConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/UriConverter.cs index 5c6bceef66bfc4..265303a00f4e5d 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/UriConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/UriConverter.cs @@ -45,10 +45,7 @@ private static Uri ReadCore(ref Utf8JsonReader reader) internal override void WriteAsPropertyNameCore(Utf8JsonWriter writer, Uri value, JsonSerializerOptions options, bool isWritingExtensionDataProperty) { - if (value is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); writer.WritePropertyName(value.OriginalString); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/VersionConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/VersionConverter.cs index fffa210475cd6e..5f3757bb8ae926 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/VersionConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/VersionConverter.cs @@ -107,10 +107,7 @@ internal override Version ReadAsPropertyNameCore(ref Utf8JsonReader reader, Type internal override void WriteAsPropertyNameCore(Utf8JsonWriter writer, Version value, JsonSerializerOptions options, bool isWritingExtensionDataProperty) { - if (value is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); #if NET #if NET8_0_OR_GREATER diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonConverterOfT.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonConverterOfT.cs index f03bbbee3cfde4..3a9684f3fd86e9 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonConverterOfT.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonConverterOfT.cs @@ -635,10 +635,7 @@ public virtual void WriteAsPropertyName(Utf8JsonWriter writer, [DisallowNull] T internal virtual void WriteAsPropertyNameCore(Utf8JsonWriter writer, [DisallowNull] T value, JsonSerializerOptions options, bool isWritingExtensionDataProperty) { - if (value is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); if (isWritingExtensionDataProperty) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonResumableConverterOfT.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonResumableConverterOfT.cs index 81bceda8d8404c..0c0430b525a82e 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonResumableConverterOfT.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonResumableConverterOfT.cs @@ -16,10 +16,7 @@ internal abstract class JsonResumableConverter : JsonConverter public sealed override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - if (options is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); // Bridge from resumable to value converters. @@ -33,10 +30,7 @@ internal abstract class JsonResumableConverter : JsonConverter public sealed override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) { - if (options is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); // Bridge from resumable to value converters. WriteStack state = default; diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Helpers.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Helpers.cs index 0b3301fcc0a125..af8c95ff889c48 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Helpers.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Helpers.cs @@ -67,10 +67,7 @@ private static JsonTypeInfo GetTypeInfo(JsonSerializerContext context, Type inpu private static void ValidateInputType(object? value, Type inputType) { - if (inputType is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(inputType)); - } + ArgumentNullException.ThrowIfNull(inputType); if (value is not null) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Document.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Document.cs index 8f7aefcbc30a3c..f45766224d32f3 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Document.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Document.cs @@ -30,10 +30,7 @@ public static partial class JsonSerializer [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)] public static TValue? Deserialize(this JsonDocument document, JsonSerializerOptions? options = null) { - if (document is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(document)); - } + ArgumentNullException.ThrowIfNull(document); JsonTypeInfo jsonTypeInfo = GetTypeInfo(options); ReadOnlySpan utf8Json = document.GetRootRawValue().Span; @@ -61,14 +58,8 @@ public static partial class JsonSerializer [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)] public static object? Deserialize(this JsonDocument document, Type returnType, JsonSerializerOptions? options = null) { - if (document is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(document)); - } - if (returnType is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(returnType)); - } + ArgumentNullException.ThrowIfNull(document); + ArgumentNullException.ThrowIfNull(returnType); JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType); ReadOnlySpan utf8Json = document.GetRootRawValue().Span; @@ -94,14 +85,8 @@ public static partial class JsonSerializer /// public static TValue? Deserialize(this JsonDocument document, JsonTypeInfo jsonTypeInfo) { - if (document is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(document)); - } - if (jsonTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); - } + ArgumentNullException.ThrowIfNull(document); + ArgumentNullException.ThrowIfNull(jsonTypeInfo); jsonTypeInfo.EnsureConfigured(); ReadOnlySpan utf8Json = document.GetRootRawValue().Span; @@ -123,14 +108,8 @@ public static partial class JsonSerializer /// public static object? Deserialize(this JsonDocument document, JsonTypeInfo jsonTypeInfo) { - if (document is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(document)); - } - if (jsonTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); - } + ArgumentNullException.ThrowIfNull(document); + ArgumentNullException.ThrowIfNull(jsonTypeInfo); jsonTypeInfo.EnsureConfigured(); ReadOnlySpan utf8Json = document.GetRootRawValue().Span; @@ -175,18 +154,9 @@ public static partial class JsonSerializer /// public static object? Deserialize(this JsonDocument document, Type returnType, JsonSerializerContext context) { - if (document is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(document)); - } - if (returnType is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(returnType)); - } - if (context is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(document); + ArgumentNullException.ThrowIfNull(returnType); + ArgumentNullException.ThrowIfNull(context); JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, returnType); ReadOnlySpan utf8Json = document.GetRootRawValue().Span; diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Element.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Element.cs index 301979e50b43b0..5e9549e87f49c1 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Element.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Element.cs @@ -53,10 +53,7 @@ public static partial class JsonSerializer [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)] public static object? Deserialize(this JsonElement element, Type returnType, JsonSerializerOptions? options = null) { - if (returnType is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(returnType)); - } + ArgumentNullException.ThrowIfNull(returnType); JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType); ReadOnlySpan utf8Json = element.GetRawValue().Span; @@ -82,10 +79,7 @@ public static partial class JsonSerializer /// public static TValue? Deserialize(this JsonElement element, JsonTypeInfo jsonTypeInfo) { - if (jsonTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); - } + ArgumentNullException.ThrowIfNull(jsonTypeInfo); jsonTypeInfo.EnsureConfigured(); ReadOnlySpan utf8Json = element.GetRawValue().Span; @@ -103,10 +97,7 @@ public static partial class JsonSerializer /// public static object? Deserialize(this JsonElement element, JsonTypeInfo jsonTypeInfo) { - if (jsonTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); - } + ArgumentNullException.ThrowIfNull(jsonTypeInfo); jsonTypeInfo.EnsureConfigured(); ReadOnlySpan utf8Json = element.GetRawValue().Span; @@ -147,14 +138,8 @@ public static partial class JsonSerializer /// public static object? Deserialize(this JsonElement element, Type returnType, JsonSerializerContext context) { - if (returnType is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(returnType)); - } - if (context is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(returnType); + ArgumentNullException.ThrowIfNull(context); JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, returnType); ReadOnlySpan utf8Json = element.GetRawValue().Span; diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Node.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Node.cs index c1e3892060a072..bd855e55bc30b8 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Node.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Node.cs @@ -51,10 +51,7 @@ public static partial class JsonSerializer [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)] public static object? Deserialize(this JsonNode? node, Type returnType, JsonSerializerOptions? options = null) { - if (returnType is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(returnType)); - } + ArgumentNullException.ThrowIfNull(returnType); JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType); return ReadFromNodeAsObject(node, jsonTypeInfo); @@ -75,10 +72,7 @@ public static partial class JsonSerializer /// public static TValue? Deserialize(this JsonNode? node, JsonTypeInfo jsonTypeInfo) { - if (jsonTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); - } + ArgumentNullException.ThrowIfNull(jsonTypeInfo); jsonTypeInfo.EnsureConfigured(); return ReadFromNode(node, jsonTypeInfo); @@ -95,10 +89,7 @@ public static partial class JsonSerializer /// public static object? Deserialize(this JsonNode? node, JsonTypeInfo jsonTypeInfo) { - if (jsonTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); - } + ArgumentNullException.ThrowIfNull(jsonTypeInfo); jsonTypeInfo.EnsureConfigured(); return ReadFromNodeAsObject(node, jsonTypeInfo); @@ -138,14 +129,8 @@ public static partial class JsonSerializer /// public static object? Deserialize(this JsonNode? node, Type returnType, JsonSerializerContext context) { - if (returnType is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(returnType)); - } - if (context is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(returnType); + ArgumentNullException.ThrowIfNull(context); JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, returnType); return ReadFromNodeAsObject(node, jsonTypeInfo); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Span.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Span.cs index a90f4f791b3608..7c5f1a4870e4f0 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Span.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Span.cs @@ -57,10 +57,7 @@ public static partial class JsonSerializer [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)] public static object? Deserialize(ReadOnlySpan utf8Json, Type returnType, JsonSerializerOptions? options = null) { - if (returnType is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(returnType)); - } + ArgumentNullException.ThrowIfNull(returnType); JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType); return ReadFromSpanAsObject(utf8Json, jsonTypeInfo); @@ -80,10 +77,7 @@ public static partial class JsonSerializer /// public static TValue? Deserialize(ReadOnlySpan utf8Json, JsonTypeInfo jsonTypeInfo) { - if (jsonTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); - } + ArgumentNullException.ThrowIfNull(jsonTypeInfo); jsonTypeInfo.EnsureConfigured(); return ReadFromSpan(utf8Json, jsonTypeInfo); @@ -101,10 +95,7 @@ public static partial class JsonSerializer /// public static object? Deserialize(ReadOnlySpan utf8Json, JsonTypeInfo jsonTypeInfo) { - if (jsonTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); - } + ArgumentNullException.ThrowIfNull(jsonTypeInfo); jsonTypeInfo.EnsureConfigured(); return ReadFromSpanAsObject(utf8Json, jsonTypeInfo); @@ -135,14 +126,8 @@ public static partial class JsonSerializer /// public static object? Deserialize(ReadOnlySpan utf8Json, Type returnType, JsonSerializerContext context) { - if (returnType is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(returnType)); - } - if (context is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(returnType); + ArgumentNullException.ThrowIfNull(context); return ReadFromSpanAsObject(utf8Json, GetTypeInfo(context, returnType)); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Stream.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Stream.cs index d804cca460c2bd..005fb7c9de3943 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Stream.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Stream.cs @@ -46,10 +46,7 @@ public static partial class JsonSerializer JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { - if (utf8Json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); - } + ArgumentNullException.ThrowIfNull(utf8Json); JsonTypeInfo jsonTypeInfo = GetTypeInfo(options); return jsonTypeInfo.DeserializeAsync(utf8Json, cancellationToken); @@ -81,10 +78,7 @@ public static partial class JsonSerializer Stream utf8Json, JsonSerializerOptions? options = null) { - if (utf8Json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); - } + ArgumentNullException.ThrowIfNull(utf8Json); JsonTypeInfo jsonTypeInfo = GetTypeInfo(options); return jsonTypeInfo.Deserialize(utf8Json); @@ -121,14 +115,8 @@ public static partial class JsonSerializer JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { - if (utf8Json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); - } - if (returnType is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(returnType)); - } + ArgumentNullException.ThrowIfNull(utf8Json); + ArgumentNullException.ThrowIfNull(returnType); JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType); return jsonTypeInfo.DeserializeAsObjectAsync(utf8Json, cancellationToken); @@ -161,14 +149,8 @@ public static partial class JsonSerializer Type returnType, JsonSerializerOptions? options = null) { - if (utf8Json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); - } - if (returnType is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(returnType)); - } + ArgumentNullException.ThrowIfNull(utf8Json); + ArgumentNullException.ThrowIfNull(returnType); JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType); return jsonTypeInfo.DeserializeAsObject(utf8Json); @@ -198,14 +180,8 @@ public static partial class JsonSerializer JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) { - if (utf8Json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); - } - if (jsonTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); - } + ArgumentNullException.ThrowIfNull(utf8Json); + ArgumentNullException.ThrowIfNull(jsonTypeInfo); jsonTypeInfo.EnsureConfigured(); return jsonTypeInfo.DeserializeAsync(utf8Json, cancellationToken); @@ -233,14 +209,8 @@ public static partial class JsonSerializer JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) { - if (utf8Json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); - } - if (jsonTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); - } + ArgumentNullException.ThrowIfNull(utf8Json); + ArgumentNullException.ThrowIfNull(jsonTypeInfo); jsonTypeInfo.EnsureConfigured(); return jsonTypeInfo.DeserializeAsObjectAsync(utf8Json, cancellationToken); @@ -266,14 +236,8 @@ public static partial class JsonSerializer Stream utf8Json, JsonTypeInfo jsonTypeInfo) { - if (utf8Json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); - } - if (jsonTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); - } + ArgumentNullException.ThrowIfNull(utf8Json); + ArgumentNullException.ThrowIfNull(jsonTypeInfo); jsonTypeInfo.EnsureConfigured(); return jsonTypeInfo.Deserialize(utf8Json); @@ -297,14 +261,8 @@ public static partial class JsonSerializer Stream utf8Json, JsonTypeInfo jsonTypeInfo) { - if (utf8Json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); - } - if (jsonTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); - } + ArgumentNullException.ThrowIfNull(utf8Json); + ArgumentNullException.ThrowIfNull(jsonTypeInfo); jsonTypeInfo.EnsureConfigured(); return jsonTypeInfo.DeserializeAsObject(utf8Json); @@ -343,18 +301,9 @@ public static partial class JsonSerializer JsonSerializerContext context, CancellationToken cancellationToken = default) { - if (utf8Json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); - } - if (returnType is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(returnType)); - } - if (context is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(utf8Json); + ArgumentNullException.ThrowIfNull(returnType); + ArgumentNullException.ThrowIfNull(context); JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, returnType); return jsonTypeInfo.DeserializeAsObjectAsync(utf8Json, cancellationToken); @@ -389,18 +338,9 @@ public static partial class JsonSerializer Type returnType, JsonSerializerContext context) { - if (utf8Json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); - } - if (returnType is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(returnType)); - } - if (context is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(utf8Json); + ArgumentNullException.ThrowIfNull(returnType); + ArgumentNullException.ThrowIfNull(context); JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, returnType); return jsonTypeInfo.DeserializeAsObject(utf8Json); @@ -455,10 +395,7 @@ public static partial class JsonSerializer JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { - if (utf8Json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); - } + ArgumentNullException.ThrowIfNull(utf8Json); JsonTypeInfo jsonTypeInfo = GetTypeInfo(options); return DeserializeAsyncEnumerableCore(utf8Json, jsonTypeInfo, topLevelValues, cancellationToken); @@ -509,15 +446,8 @@ public static partial class JsonSerializer bool topLevelValues, CancellationToken cancellationToken = default) { - if (utf8Json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); - } - - if (jsonTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); - } + ArgumentNullException.ThrowIfNull(utf8Json); + ArgumentNullException.ThrowIfNull(jsonTypeInfo); jsonTypeInfo.EnsureConfigured(); return DeserializeAsyncEnumerableCore(utf8Json, jsonTypeInfo, topLevelValues, cancellationToken); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.String.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.String.cs index 3f0451e12d9fb7..3014fd3892118f 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.String.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.String.cs @@ -46,10 +46,7 @@ public static partial class JsonSerializer [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)] public static TValue? Deserialize([StringSyntax(StringSyntaxAttribute.Json)] string json, JsonSerializerOptions? options = null) { - if (json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(json)); - } + ArgumentNullException.ThrowIfNull(json); JsonTypeInfo jsonTypeInfo = GetTypeInfo(options); return ReadFromSpan(json.AsSpan(), jsonTypeInfo); @@ -118,14 +115,8 @@ public static partial class JsonSerializer [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)] public static object? Deserialize([StringSyntax(StringSyntaxAttribute.Json)] string json, Type returnType, JsonSerializerOptions? options = null) { - if (json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(json)); - } - if (returnType is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(returnType)); - } + ArgumentNullException.ThrowIfNull(json); + ArgumentNullException.ThrowIfNull(returnType); JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType); return ReadFromSpanAsObject(json.AsSpan(), jsonTypeInfo); @@ -162,10 +153,7 @@ public static partial class JsonSerializer [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)] public static object? Deserialize([StringSyntax(StringSyntaxAttribute.Json)] ReadOnlySpan json, Type returnType, JsonSerializerOptions? options = null) { - if (returnType is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(returnType)); - } + ArgumentNullException.ThrowIfNull(returnType); // default/null span is treated as empty @@ -202,14 +190,8 @@ public static partial class JsonSerializer /// public static TValue? Deserialize([StringSyntax(StringSyntaxAttribute.Json)] string json, JsonTypeInfo jsonTypeInfo) { - if (json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(json)); - } - if (jsonTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); - } + ArgumentNullException.ThrowIfNull(json); + ArgumentNullException.ThrowIfNull(jsonTypeInfo); jsonTypeInfo.EnsureConfigured(); return ReadFromSpan(json.AsSpan(), jsonTypeInfo); @@ -244,10 +226,7 @@ public static partial class JsonSerializer /// public static TValue? Deserialize([StringSyntax(StringSyntaxAttribute.Json)] ReadOnlySpan json, JsonTypeInfo jsonTypeInfo) { - if (jsonTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); - } + ArgumentNullException.ThrowIfNull(jsonTypeInfo); jsonTypeInfo.EnsureConfigured(); return ReadFromSpan(json, jsonTypeInfo); @@ -277,14 +256,8 @@ public static partial class JsonSerializer /// public static object? Deserialize([StringSyntax(StringSyntaxAttribute.Json)] string json, JsonTypeInfo jsonTypeInfo) { - if (json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(json)); - } - if (jsonTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); - } + ArgumentNullException.ThrowIfNull(json); + ArgumentNullException.ThrowIfNull(jsonTypeInfo); jsonTypeInfo.EnsureConfigured(); return ReadFromSpanAsObject(json.AsSpan(), jsonTypeInfo); @@ -310,10 +283,7 @@ public static partial class JsonSerializer /// public static object? Deserialize([StringSyntax(StringSyntaxAttribute.Json)] ReadOnlySpan json, JsonTypeInfo jsonTypeInfo) { - if (jsonTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); - } + ArgumentNullException.ThrowIfNull(jsonTypeInfo); jsonTypeInfo.EnsureConfigured(); return ReadFromSpanAsObject(json, jsonTypeInfo); @@ -356,18 +326,9 @@ public static partial class JsonSerializer /// public static object? Deserialize([StringSyntax(StringSyntaxAttribute.Json)] string json, Type returnType, JsonSerializerContext context) { - if (json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(json)); - } - if (returnType is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(returnType)); - } - if (context is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(json); + ArgumentNullException.ThrowIfNull(returnType); + ArgumentNullException.ThrowIfNull(context); JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, returnType); return ReadFromSpanAsObject(json.AsSpan(), jsonTypeInfo); @@ -410,14 +371,8 @@ public static partial class JsonSerializer /// public static object? Deserialize([StringSyntax(StringSyntaxAttribute.Json)] ReadOnlySpan json, Type returnType, JsonSerializerContext context) { - if (returnType is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(returnType)); - } - if (context is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(returnType); + ArgumentNullException.ThrowIfNull(context); JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, returnType); return ReadFromSpanAsObject(json, jsonTypeInfo); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Utf8JsonReader.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Utf8JsonReader.cs index fd424c0606cb81..e84888c90087fa 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Utf8JsonReader.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Utf8JsonReader.cs @@ -111,10 +111,7 @@ public static partial class JsonSerializer [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)] public static object? Deserialize(ref Utf8JsonReader reader, Type returnType, JsonSerializerOptions? options = null) { - if (returnType is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(returnType)); - } + ArgumentNullException.ThrowIfNull(returnType); JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType); return ReadAsObject(ref reader, jsonTypeInfo); @@ -161,10 +158,7 @@ public static partial class JsonSerializer /// public static TValue? Deserialize(ref Utf8JsonReader reader, JsonTypeInfo jsonTypeInfo) { - if (jsonTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); - } + ArgumentNullException.ThrowIfNull(jsonTypeInfo); jsonTypeInfo.EnsureConfigured(); return Read(ref reader, jsonTypeInfo); @@ -210,10 +204,7 @@ public static partial class JsonSerializer /// public static object? Deserialize(ref Utf8JsonReader reader, JsonTypeInfo jsonTypeInfo) { - if (jsonTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); - } + ArgumentNullException.ThrowIfNull(jsonTypeInfo); jsonTypeInfo.EnsureConfigured(); return ReadAsObject(ref reader, jsonTypeInfo); @@ -270,14 +261,8 @@ public static partial class JsonSerializer /// public static object? Deserialize(ref Utf8JsonReader reader, Type returnType, JsonSerializerContext context) { - if (returnType is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(returnType)); - } - if (context is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(returnType); + ArgumentNullException.ThrowIfNull(context); return ReadAsObject(ref reader, GetTypeInfo(context, returnType)); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.ByteArray.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.ByteArray.cs index b2287d6ea8cc45..c902e07e93d182 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.ByteArray.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.ByteArray.cs @@ -70,10 +70,7 @@ public static byte[] SerializeToUtf8Bytes( /// public static byte[] SerializeToUtf8Bytes(TValue value, JsonTypeInfo jsonTypeInfo) { - if (jsonTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); - } + ArgumentNullException.ThrowIfNull(jsonTypeInfo); jsonTypeInfo.EnsureConfigured(); return WriteBytes(value, jsonTypeInfo); @@ -93,10 +90,7 @@ public static byte[] SerializeToUtf8Bytes(TValue value, JsonTypeInfo public static byte[] SerializeToUtf8Bytes(object? value, JsonTypeInfo jsonTypeInfo) { - if (jsonTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); - } + ArgumentNullException.ThrowIfNull(jsonTypeInfo); jsonTypeInfo.EnsureConfigured(); return WriteBytesAsObject(value, jsonTypeInfo); @@ -125,10 +119,7 @@ public static byte[] SerializeToUtf8Bytes(object? value, JsonTypeInfo jsonTypeIn /// public static byte[] SerializeToUtf8Bytes(object? value, Type inputType, JsonSerializerContext context) { - if (context is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); ValidateInputType(value, inputType); JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, inputType); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Document.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Document.cs index f12459b71b65bb..3f38451c949290 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Document.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Document.cs @@ -67,10 +67,7 @@ public static JsonDocument SerializeToDocument(object? value, Type inputType, Js /// public static JsonDocument SerializeToDocument(TValue value, JsonTypeInfo jsonTypeInfo) { - if (jsonTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); - } + ArgumentNullException.ThrowIfNull(jsonTypeInfo); jsonTypeInfo.EnsureConfigured(); return WriteDocument(value, jsonTypeInfo); @@ -90,10 +87,7 @@ public static JsonDocument SerializeToDocument(TValue value, JsonTypeInf /// public static JsonDocument SerializeToDocument(object? value, JsonTypeInfo jsonTypeInfo) { - if (jsonTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); - } + ArgumentNullException.ThrowIfNull(jsonTypeInfo); jsonTypeInfo.EnsureConfigured(); return WriteDocumentAsObject(value, jsonTypeInfo); @@ -119,10 +113,7 @@ public static JsonDocument SerializeToDocument(object? value, JsonTypeInfo jsonT /// public static JsonDocument SerializeToDocument(object? value, Type inputType, JsonSerializerContext context) { - if (context is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); ValidateInputType(value, inputType); return WriteDocumentAsObject(value, GetTypeInfo(context, inputType)); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Element.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Element.cs index 4057cd667beddc..5cd624a75e29e6 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Element.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Element.cs @@ -67,10 +67,7 @@ public static JsonElement SerializeToElement(object? value, Type inputType, Json /// public static JsonElement SerializeToElement(TValue value, JsonTypeInfo jsonTypeInfo) { - if (jsonTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); - } + ArgumentNullException.ThrowIfNull(jsonTypeInfo); jsonTypeInfo.EnsureConfigured(); return WriteElement(value, jsonTypeInfo); @@ -90,10 +87,7 @@ public static JsonElement SerializeToElement(TValue value, JsonTypeInfo< /// public static JsonElement SerializeToElement(object? value, JsonTypeInfo jsonTypeInfo) { - if (jsonTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); - } + ArgumentNullException.ThrowIfNull(jsonTypeInfo); jsonTypeInfo.EnsureConfigured(); return WriteElementAsObject(value, jsonTypeInfo); @@ -119,10 +113,7 @@ public static JsonElement SerializeToElement(object? value, JsonTypeInfo jsonTyp /// public static JsonElement SerializeToElement(object? value, Type inputType, JsonSerializerContext context) { - if (context is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); ValidateInputType(value, inputType); JsonTypeInfo typeInfo = GetTypeInfo(context, inputType); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Node.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Node.cs index 0051a6ad98bd53..59c7d2734df96c 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Node.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Node.cs @@ -68,10 +68,7 @@ public static partial class JsonSerializer /// public static JsonNode? SerializeToNode(TValue value, JsonTypeInfo jsonTypeInfo) { - if (jsonTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); - } + ArgumentNullException.ThrowIfNull(jsonTypeInfo); jsonTypeInfo.EnsureConfigured(); return WriteNode(value, jsonTypeInfo); @@ -91,10 +88,7 @@ public static partial class JsonSerializer /// public static JsonNode? SerializeToNode(object? value, JsonTypeInfo jsonTypeInfo) { - if (jsonTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); - } + ArgumentNullException.ThrowIfNull(jsonTypeInfo); jsonTypeInfo.EnsureConfigured(); return WriteNodeAsObject(value, jsonTypeInfo); @@ -120,10 +114,7 @@ public static partial class JsonSerializer /// public static JsonNode? SerializeToNode(object? value, Type inputType, JsonSerializerContext context) { - if (context is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); ValidateInputType(value, inputType); JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, inputType); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Pipe.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Pipe.cs index dbd8debe55f090..dc3c4a00d04efd 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Pipe.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Pipe.cs @@ -30,14 +30,8 @@ public static Task SerializeAsync( JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) { - if (utf8Json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); - } - if (jsonTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); - } + ArgumentNullException.ThrowIfNull(utf8Json); + ArgumentNullException.ThrowIfNull(jsonTypeInfo); jsonTypeInfo.EnsureConfigured(); return jsonTypeInfo.SerializeAsync(utf8Json, value, cancellationToken); @@ -67,10 +61,7 @@ public static Task SerializeAsync( JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { - if (utf8Json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); - } + ArgumentNullException.ThrowIfNull(utf8Json); JsonTypeInfo jsonTypeInfo = GetTypeInfo(options); return jsonTypeInfo.SerializeAsync(utf8Json, value, cancellationToken); @@ -96,15 +87,8 @@ public static Task SerializeAsync( JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) { - if (utf8Json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); - } - - if (jsonTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); - } + ArgumentNullException.ThrowIfNull(utf8Json); + ArgumentNullException.ThrowIfNull(jsonTypeInfo); jsonTypeInfo.EnsureConfigured(); return jsonTypeInfo.SerializeAsObjectAsync(utf8Json, value, cancellationToken); @@ -136,15 +120,8 @@ public static Task SerializeAsync( JsonSerializerContext context, CancellationToken cancellationToken = default) { - if (utf8Json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); - } - - if (context is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(utf8Json); + ArgumentNullException.ThrowIfNull(context); ValidateInputType(value, inputType); JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, inputType); @@ -180,10 +157,7 @@ public static Task SerializeAsync( JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { - if (utf8Json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); - } + ArgumentNullException.ThrowIfNull(utf8Json); ValidateInputType(value, inputType); JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, inputType); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Stream.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Stream.cs index 9c678e37ad3943..efa9bb0f357e5f 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Stream.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Stream.cs @@ -44,10 +44,7 @@ public static Task SerializeAsync( JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { - if (utf8Json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); - } + ArgumentNullException.ThrowIfNull(utf8Json); JsonTypeInfo jsonTypeInfo = GetTypeInfo(options); return jsonTypeInfo.SerializeAsync(utf8Json, value, cancellationToken); @@ -74,10 +71,7 @@ public static void Serialize( TValue value, JsonSerializerOptions? options = null) { - if (utf8Json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); - } + ArgumentNullException.ThrowIfNull(utf8Json); JsonTypeInfo jsonTypeInfo = GetTypeInfo(options); jsonTypeInfo.Serialize(utf8Json, value); @@ -111,10 +105,7 @@ public static Task SerializeAsync( JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { - if (utf8Json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); - } + ArgumentNullException.ThrowIfNull(utf8Json); ValidateInputType(value, inputType); JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, inputType); @@ -146,10 +137,7 @@ public static void Serialize( Type inputType, JsonSerializerOptions? options = null) { - if (utf8Json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); - } + ArgumentNullException.ThrowIfNull(utf8Json); ValidateInputType(value, inputType); JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, inputType); @@ -174,14 +162,8 @@ public static Task SerializeAsync( JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) { - if (utf8Json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); - } - if (jsonTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); - } + ArgumentNullException.ThrowIfNull(utf8Json); + ArgumentNullException.ThrowIfNull(jsonTypeInfo); jsonTypeInfo.EnsureConfigured(); return jsonTypeInfo.SerializeAsync(utf8Json, value, cancellationToken); @@ -202,14 +184,8 @@ public static void Serialize( TValue value, JsonTypeInfo jsonTypeInfo) { - if (utf8Json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); - } - if (jsonTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); - } + ArgumentNullException.ThrowIfNull(utf8Json); + ArgumentNullException.ThrowIfNull(jsonTypeInfo); jsonTypeInfo.EnsureConfigured(); jsonTypeInfo.Serialize(utf8Json, value); @@ -235,14 +211,8 @@ public static Task SerializeAsync( JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) { - if (utf8Json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); - } - if (jsonTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); - } + ArgumentNullException.ThrowIfNull(utf8Json); + ArgumentNullException.ThrowIfNull(jsonTypeInfo); jsonTypeInfo.EnsureConfigured(); return jsonTypeInfo.SerializeAsObjectAsync(utf8Json, value, cancellationToken); @@ -265,14 +235,8 @@ public static void Serialize( object? value, JsonTypeInfo jsonTypeInfo) { - if (utf8Json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); - } - if (jsonTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); - } + ArgumentNullException.ThrowIfNull(utf8Json); + ArgumentNullException.ThrowIfNull(jsonTypeInfo); jsonTypeInfo.EnsureConfigured(); jsonTypeInfo.SerializeAsObject(utf8Json, value); @@ -304,14 +268,8 @@ public static Task SerializeAsync( JsonSerializerContext context, CancellationToken cancellationToken = default) { - if (utf8Json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); - } - if (context is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(utf8Json); + ArgumentNullException.ThrowIfNull(context); ValidateInputType(value, inputType); JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, inputType); @@ -341,14 +299,8 @@ public static void Serialize( Type inputType, JsonSerializerContext context) { - if (utf8Json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); - } - if (context is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(utf8Json); + ArgumentNullException.ThrowIfNull(context); ValidateInputType(value, inputType); JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, inputType); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.String.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.String.cs index 65cf70119bf6b8..34ce1c5e8d0fc3 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.String.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.String.cs @@ -82,10 +82,7 @@ public static string Serialize( /// public static string Serialize(TValue value, JsonTypeInfo jsonTypeInfo) { - if (jsonTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); - } + ArgumentNullException.ThrowIfNull(jsonTypeInfo); jsonTypeInfo.EnsureConfigured(); return WriteString(value, jsonTypeInfo); @@ -109,10 +106,7 @@ public static string Serialize(TValue value, JsonTypeInfo jsonTy /// public static string Serialize(object? value, JsonTypeInfo jsonTypeInfo) { - if (jsonTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); - } + ArgumentNullException.ThrowIfNull(jsonTypeInfo); jsonTypeInfo.EnsureConfigured(); return WriteStringAsObject(value, jsonTypeInfo); @@ -142,10 +136,7 @@ public static string Serialize(object? value, JsonTypeInfo jsonTypeInfo) /// public static string Serialize(object? value, Type inputType, JsonSerializerContext context) { - if (context is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); ValidateInputType(value, inputType); JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, inputType); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Utf8JsonWriter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Utf8JsonWriter.cs index e62931f4faf61c..8c4fed9d2a328c 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Utf8JsonWriter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Utf8JsonWriter.cs @@ -30,10 +30,7 @@ public static void Serialize( TValue value, JsonSerializerOptions? options = null) { - if (writer is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(writer)); - } + ArgumentNullException.ThrowIfNull(writer); JsonTypeInfo jsonTypeInfo = GetTypeInfo(options); jsonTypeInfo.Serialize(writer, value); @@ -64,10 +61,7 @@ public static void Serialize( Type inputType, JsonSerializerOptions? options = null) { - if (writer is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(writer)); - } + ArgumentNullException.ThrowIfNull(writer); ValidateInputType(value, inputType); JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, inputType); @@ -86,14 +80,8 @@ public static void Serialize( /// public static void Serialize(Utf8JsonWriter writer, TValue value, JsonTypeInfo jsonTypeInfo) { - if (writer is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(writer)); - } - if (jsonTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); - } + ArgumentNullException.ThrowIfNull(writer); + ArgumentNullException.ThrowIfNull(jsonTypeInfo); jsonTypeInfo.EnsureConfigured(); jsonTypeInfo.Serialize(writer, value); @@ -113,14 +101,8 @@ public static void Serialize(Utf8JsonWriter writer, TValue value, JsonTy /// public static void Serialize(Utf8JsonWriter writer, object? value, JsonTypeInfo jsonTypeInfo) { - if (writer is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(writer)); - } - if (jsonTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); - } + ArgumentNullException.ThrowIfNull(writer); + ArgumentNullException.ThrowIfNull(jsonTypeInfo); jsonTypeInfo.EnsureConfigured(); jsonTypeInfo.SerializeAsObject(writer, value); @@ -149,14 +131,8 @@ public static void Serialize(Utf8JsonWriter writer, object? value, JsonTypeInfo /// public static void Serialize(Utf8JsonWriter writer, object? value, Type inputType, JsonSerializerContext context) { - if (writer is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(writer)); - } - if (context is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(writer); + ArgumentNullException.ThrowIfNull(context); ValidateInputType(value, inputType); JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, inputType); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Caching.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Caching.cs index a9633d439bcaed..b96decb395ae7a 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Caching.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Caching.cs @@ -54,10 +54,7 @@ CachingContext GetOrCreate() /// public JsonTypeInfo GetTypeInfo(Type type) { - if (type is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(type)); - } + ArgumentNullException.ThrowIfNull(type); if (JsonTypeInfo.IsInvalidForSerialization(type)) { @@ -82,10 +79,7 @@ public JsonTypeInfo GetTypeInfo(Type type) /// public bool TryGetTypeInfo(Type type, [NotNullWhen(true)] out JsonTypeInfo? typeInfo) { - if (type is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(type)); - } + ArgumentNullException.ThrowIfNull(type); if (JsonTypeInfo.IsInvalidForSerialization(type)) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Converters.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Converters.cs index 8f088a85f4f211..c3321ad04e2e60 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Converters.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Converters.cs @@ -40,10 +40,7 @@ public sealed partial class JsonSerializerOptions [RequiresDynamicCode("Getting a converter for a type may require reflection which depends on runtime code generation.")] public JsonConverter GetConverter(Type typeToConvert) { - if (typeToConvert is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(typeToConvert)); - } + ArgumentNullException.ThrowIfNull(typeToConvert); if (JsonSerializer.IsReflectionEnabledByDefault) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.cs index 1616bba9316a62..27dcd9b34cb009 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.cs @@ -115,10 +115,7 @@ public JsonSerializerOptions() /// public JsonSerializerOptions(JsonSerializerOptions options) { - if (options is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); // The following fields are not copied intentionally: // 1. _cachingContext can only be set in immutable options instances. diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/DefaultJsonTypeInfoResolver.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/DefaultJsonTypeInfoResolver.cs index 2180df43653071..724399929685c1 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/DefaultJsonTypeInfoResolver.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/DefaultJsonTypeInfoResolver.cs @@ -50,15 +50,8 @@ private DefaultJsonTypeInfoResolver(bool mutable) Justification = "The ctor is marked RequiresDynamicCode.")] public virtual JsonTypeInfo GetTypeInfo(Type type, JsonSerializerOptions options) { - if (type == null) - { - ThrowHelper.ThrowArgumentNullException(nameof(type)); - } - - if (options == null) - { - ThrowHelper.ThrowArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(options); _mutable = false; diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.Collections.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.Collections.cs index 36faca300dcc6b..6e423c6ff7357f 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.Collections.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.Collections.cs @@ -84,10 +84,7 @@ public static JsonTypeInfo CreateImmutableDictionaryInfo where TKey : notnull { - if (createRangeFunc is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(createRangeFunc)); - } + ArgumentNullException.ThrowIfNull(createRangeFunc); return CreateCore( options, @@ -152,10 +149,7 @@ public static JsonTypeInfo CreateImmutableEnumerableInfo, TCollection> createRangeFunc) where TCollection : IEnumerable { - if (createRangeFunc is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(createRangeFunc)); - } + ArgumentNullException.ThrowIfNull(createRangeFunc); return CreateCore( options, @@ -402,10 +396,7 @@ private static JsonTypeInfo CreateStackOrQueueInfo( Action addFunc) where TCollection : IEnumerable { - if (addFunc is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(addFunc)); - } + ArgumentNullException.ThrowIfNull(addFunc); return CreateCore( options, diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.Converters.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.Converters.cs index 511583d3226ad8..bcd0fd42b4d30d 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.Converters.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.Converters.cs @@ -282,10 +282,7 @@ public static JsonConverter GetUnsupportedTypeConverter() /// This API is for use by the output of the System.Text.Json source generator and should not be called directly. public static JsonConverter GetEnumConverter(JsonSerializerOptions options) where T : struct, Enum { - if (options is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); return EnumConverterFactory.Helpers.Create(EnumConverterOptions.AllowNumbers, options); } @@ -299,10 +296,7 @@ public static JsonConverter GetEnumConverter(JsonSerializerOptions options /// This API is for use by the output of the System.Text.Json source generator and should not be called directly. public static JsonConverter GetNullableConverter(JsonTypeInfo underlyingTypeInfo) where T : struct { - if (underlyingTypeInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(underlyingTypeInfo)); - } + ArgumentNullException.ThrowIfNull(underlyingTypeInfo); JsonConverter underlyingConverter = GetTypedConverter(underlyingTypeInfo.Converter); @@ -318,10 +312,7 @@ public static JsonConverter GetEnumConverter(JsonSerializerOptions options /// This API is for use by the output of the System.Text.Json source generator and should not be called directly. public static JsonConverter GetNullableConverter(JsonSerializerOptions options) where T : struct { - if (options is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); JsonConverter underlyingConverter = GetTypedConverter(options.GetConverterInternal(typeof(T))); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.Helpers.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.Helpers.cs index 3b5648eddd0246..f1464024ba44ac 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.Helpers.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.Helpers.cs @@ -75,10 +75,7 @@ private static JsonTypeInfo CreateCore( object? createObjectWithArgs = null, object? addFunc = null) { - if (collectionInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(collectionInfo)); - } + ArgumentNullException.ThrowIfNull(collectionInfo); converter = collectionInfo.SerializeHandler != null ? new JsonMetadataServicesConverter(converter) diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.cs index 26ee932d563404..bfe42cff4c49b9 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.cs @@ -22,14 +22,8 @@ public static partial class JsonMetadataServices /// This API is for use by the output of the System.Text.Json source generator and should not be called directly. public static JsonPropertyInfo CreatePropertyInfo(JsonSerializerOptions options, JsonPropertyInfoValues propertyInfo) { - if (options is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(options)); - } - if (propertyInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(propertyInfo)); - } + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(propertyInfo); Type? declaringType = propertyInfo.DeclaringType; if (declaringType == null) @@ -62,14 +56,8 @@ public static JsonPropertyInfo CreatePropertyInfo(JsonSerializerOptions optio /// This API is for use by the output of the System.Text.Json source generator and should not be called directly. public static JsonTypeInfo CreateObjectInfo(JsonSerializerOptions options, JsonObjectInfoValues objectInfo) where T : notnull { - if (options is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(options)); - } - if (objectInfo is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(objectInfo)); - } + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(objectInfo); return CreateCore(options, objectInfo); } @@ -82,14 +70,8 @@ public static JsonTypeInfo CreateObjectInfo(JsonSerializerOptions options, /// This API is for use by the output of the System.Text.Json source generator and should not be called directly. public static JsonTypeInfo CreateValueInfo(JsonSerializerOptions options, JsonConverter converter) { - if (options is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(options)); - } - if (converter is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(converter)); - } + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(converter); JsonTypeInfo info = CreateCore(converter, options); return info; diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonPropertyInfo.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonPropertyInfo.cs index e21e205d715926..2dcf18a91cfae8 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonPropertyInfo.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonPropertyInfo.cs @@ -797,10 +797,7 @@ public string Name { VerifyMutable(); - if (value == null) - { - ThrowHelper.ThrowArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _name = value; } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfo.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfo.cs index bd3e3d9241f857..a11d3634aa623b 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfo.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfo.cs @@ -906,10 +906,7 @@ internal bool DetermineUsesParameterizedConstructor() [RequiresDynamicCode(MetadataFactoryRequiresUnreferencedCode)] public static JsonTypeInfo CreateJsonTypeInfo(JsonSerializerOptions options) { - if (options == null) - { - ThrowHelper.ThrowArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); JsonConverter converter = DefaultJsonTypeInfoResolver.GetConverterForType(typeof(T), options, resolveJsonConverterAttribute: false); return new JsonTypeInfo(converter, options); @@ -937,15 +934,8 @@ public static JsonTypeInfo CreateJsonTypeInfo(JsonSerializerOptions option [RequiresDynamicCode(MetadataFactoryRequiresUnreferencedCode)] public static JsonTypeInfo CreateJsonTypeInfo(Type type, JsonSerializerOptions options) { - if (type == null) - { - ThrowHelper.ThrowArgumentNullException(nameof(type)); - } - - if (options == null) - { - ThrowHelper.ThrowArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(options); if (IsInvalidForSerialization(type)) { @@ -993,15 +983,8 @@ internal static JsonTypeInfo CreateJsonTypeInfo(Type type, JsonConverter convert [RequiresDynamicCode(MetadataFactoryRequiresUnreferencedCode)] public JsonPropertyInfo CreateJsonPropertyInfo(Type propertyType, string name) { - if (propertyType == null) - { - ThrowHelper.ThrowArgumentNullException(nameof(propertyType)); - } - - if (name == null) - { - ThrowHelper.ThrowArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(propertyType); + ArgumentNullException.ThrowIfNull(name); if (IsInvalidForSerialization(propertyType)) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfoResolver.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfoResolver.cs index 58cc32c795e45e..02bf38ff57bab6 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfoResolver.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfoResolver.cs @@ -25,10 +25,7 @@ public static class JsonTypeInfoResolver /// public static IJsonTypeInfoResolver Combine(params IJsonTypeInfoResolver?[] resolvers) { - if (resolvers is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(resolvers)); - } + ArgumentNullException.ThrowIfNull(resolvers); return Combine((ReadOnlySpan)resolvers); } @@ -70,14 +67,8 @@ public static IJsonTypeInfoResolver Combine(params ReadOnlySpan public static IJsonTypeInfoResolver WithAddedModifier(this IJsonTypeInfoResolver resolver, Action modifier) { - if (resolver is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(resolver)); - } - if (modifier is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(modifier)); - } + ArgumentNullException.ThrowIfNull(resolver); + ArgumentNullException.ThrowIfNull(modifier); return resolver is JsonTypeInfoResolverWithAddedModifiers resolverWithModifiers ? resolverWithModifiers.WithAddedModifier(modifier) diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Bytes.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Bytes.cs index c97d1cb1546211..cb087dd147c161 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Bytes.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Bytes.cs @@ -47,10 +47,7 @@ public void WriteBase64String(JsonEncodedText propertyName, ReadOnlySpan b /// public void WriteBase64String(string propertyName, ReadOnlySpan bytes) { - if (propertyName is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); - } + ArgumentNullException.ThrowIfNull(propertyName); WriteBase64String(propertyName.AsSpan(), bytes); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.DateTime.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.DateTime.cs index 9e1f07e25e019a..807ba878c37110 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.DateTime.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.DateTime.cs @@ -52,10 +52,7 @@ public void WriteString(JsonEncodedText propertyName, DateTime value) /// public void WriteString(string propertyName, DateTime value) { - if (propertyName is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); - } + ArgumentNullException.ThrowIfNull(propertyName); WriteString(propertyName.AsSpan(), value); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.DateTimeOffset.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.DateTimeOffset.cs index 38809447b91b09..48a687ac3df3a1 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.DateTimeOffset.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.DateTimeOffset.cs @@ -51,10 +51,7 @@ public void WriteString(JsonEncodedText propertyName, DateTimeOffset value) /// public void WriteString(string propertyName, DateTimeOffset value) { - if (propertyName is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); - } + ArgumentNullException.ThrowIfNull(propertyName); WriteString(propertyName.AsSpan(), value); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Decimal.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Decimal.cs index aadc70a39b5f04..0dab8b94375b54 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Decimal.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Decimal.cs @@ -51,10 +51,7 @@ public void WriteNumber(JsonEncodedText propertyName, decimal value) /// public void WriteNumber(string propertyName, decimal value) { - if (propertyName is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); - } + ArgumentNullException.ThrowIfNull(propertyName); WriteNumber(propertyName.AsSpan(), value); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Double.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Double.cs index 4a58e3057ac6cb..791281f4d7eda2 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Double.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Double.cs @@ -53,10 +53,7 @@ public void WriteNumber(JsonEncodedText propertyName, double value) /// public void WriteNumber(string propertyName, double value) { - if (propertyName is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); - } + ArgumentNullException.ThrowIfNull(propertyName); WriteNumber(propertyName.AsSpan(), value); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Float.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Float.cs index f3b6b4847f2ddd..782311a72b7158 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Float.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Float.cs @@ -53,10 +53,7 @@ public void WriteNumber(JsonEncodedText propertyName, float value) /// public void WriteNumber(string propertyName, float value) { - if (propertyName is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); - } + ArgumentNullException.ThrowIfNull(propertyName); WriteNumber(propertyName.AsSpan(), value); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Guid.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Guid.cs index 004a0d228eea8a..088f61202fed9c 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Guid.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Guid.cs @@ -51,10 +51,7 @@ public void WriteString(JsonEncodedText propertyName, Guid value) /// public void WriteString(string propertyName, Guid value) { - if (propertyName is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); - } + ArgumentNullException.ThrowIfNull(propertyName); WriteString(propertyName.AsSpan(), value); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Literal.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Literal.cs index bf41ed2e526482..f75feb6345fcfb 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Literal.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Literal.cs @@ -73,10 +73,7 @@ private void WriteLiteralHelper(ReadOnlySpan utf8PropertyName, ReadOnlySpa /// public void WriteNull(string propertyName) { - if (propertyName is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); - } + ArgumentNullException.ThrowIfNull(propertyName); WriteNull(propertyName.AsSpan()); } @@ -171,10 +168,7 @@ public void WriteBoolean(JsonEncodedText propertyName, bool value) /// public void WriteBoolean(string propertyName, bool value) { - if (propertyName is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); - } + ArgumentNullException.ThrowIfNull(propertyName); WriteBoolean(propertyName.AsSpan(), value); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.SignedNumber.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.SignedNumber.cs index 633d0e1c86aaee..06552071d33569 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.SignedNumber.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.SignedNumber.cs @@ -51,10 +51,7 @@ public void WriteNumber(JsonEncodedText propertyName, long value) /// public void WriteNumber(string propertyName, long value) { - if (propertyName is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); - } + ArgumentNullException.ThrowIfNull(propertyName); WriteNumber(propertyName.AsSpan(), value); } @@ -142,10 +139,7 @@ public void WriteNumber(JsonEncodedText propertyName, int value) /// public void WriteNumber(string propertyName, int value) { - if (propertyName is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); - } + ArgumentNullException.ThrowIfNull(propertyName); WriteNumber(propertyName.AsSpan(), (long)value); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.String.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.String.cs index 3c4179d5906ebd..ae8796a1be99b4 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.String.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.String.cs @@ -69,10 +69,7 @@ private void WritePropertyNameHelper(ReadOnlySpan utf8PropertyName) /// public void WritePropertyName(string propertyName) { - if (propertyName is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); - } + ArgumentNullException.ThrowIfNull(propertyName); WritePropertyName(propertyName.AsSpan()); } @@ -455,10 +452,7 @@ private void WriteStringHelper(ReadOnlySpan utf8PropertyName, ReadOnlySpan /// public void WriteString(string propertyName, JsonEncodedText value) { - if (propertyName is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); - } + ArgumentNullException.ThrowIfNull(propertyName); WriteString(propertyName.AsSpan(), value); } @@ -487,10 +481,7 @@ public void WriteString(string propertyName, JsonEncodedText value) /// public void WriteString(string propertyName, string? value) { - if (propertyName is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); - } + ArgumentNullException.ThrowIfNull(propertyName); if (value == null) { @@ -641,10 +632,7 @@ private void WriteStringHelperEscapeValue(ReadOnlySpan utf8PropertyName, R /// public void WriteString(string propertyName, ReadOnlySpan value) { - if (propertyName is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); - } + ArgumentNullException.ThrowIfNull(propertyName); WriteString(propertyName.AsSpan(), value); } @@ -731,10 +719,7 @@ private void WriteStringHelperEscapeValue(ReadOnlySpan utf8PropertyName, R /// public void WriteString(string propertyName, ReadOnlySpan utf8Value) { - if (propertyName is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); - } + ArgumentNullException.ThrowIfNull(propertyName); WriteString(propertyName.AsSpan(), utf8Value); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.UnsignedNumber.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.UnsignedNumber.cs index 68536e35cc5d66..728fb2d1f71abc 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.UnsignedNumber.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.UnsignedNumber.cs @@ -53,10 +53,7 @@ public void WriteNumber(JsonEncodedText propertyName, ulong value) [CLSCompliant(false)] public void WriteNumber(string propertyName, ulong value) { - if (propertyName is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); - } + ArgumentNullException.ThrowIfNull(propertyName); WriteNumber(propertyName.AsSpan(), value); } @@ -148,10 +145,7 @@ public void WriteNumber(JsonEncodedText propertyName, uint value) [CLSCompliant(false)] public void WriteNumber(string propertyName, uint value) { - if (propertyName is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); - } + ArgumentNullException.ThrowIfNull(propertyName); WriteNumber(propertyName.AsSpan(), (ulong)value); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Comment.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Comment.cs index e0fa3e91cb1ad8..0660197eeb1391 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Comment.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Comment.cs @@ -26,10 +26,7 @@ public sealed partial class Utf8JsonWriter /// public void WriteCommentValue(string value) { - if (value is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); WriteCommentValue(value.AsSpan()); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Raw.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Raw.cs index f876c1b77021ff..9c1bb2a99f077d 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Raw.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Raw.cs @@ -38,10 +38,7 @@ public void WriteRawValue([StringSyntax(StringSyntaxAttribute.Json)] string json ValidateWritingValue(); } - if (json == null) - { - throw new ArgumentNullException(nameof(json)); - } + ArgumentNullException.ThrowIfNull(json); TranscodeAndWriteRawValue(json.AsSpan(), skipInputValidation); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.cs index 4ce8f41e44f545..6409daf43381d0 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.cs @@ -216,10 +216,7 @@ private Utf8JsonWriter() /// public Utf8JsonWriter(IBufferWriter bufferWriter, JsonWriterOptions options = default) { - if (bufferWriter is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(bufferWriter)); - } + ArgumentNullException.ThrowIfNull(bufferWriter); _output = bufferWriter; SetOptions(options); @@ -237,10 +234,7 @@ public Utf8JsonWriter(IBufferWriter bufferWriter, JsonWriterOptions option /// public Utf8JsonWriter(Stream utf8Json, JsonWriterOptions options = default) { - if (utf8Json is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); - } + ArgumentNullException.ThrowIfNull(utf8Json); if (!utf8Json.CanWrite) throw new ArgumentException(SR.StreamNotWritable); @@ -857,10 +851,7 @@ private void WriteStartEscapeProperty(ReadOnlySpan utf8PropertyName, byte /// public void WriteStartArray(string propertyName) { - if (propertyName is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); - } + ArgumentNullException.ThrowIfNull(propertyName); WriteStartArray(propertyName.AsSpan()); } @@ -883,10 +874,7 @@ public void WriteStartArray(string propertyName) /// public void WriteStartObject(string propertyName) { - if (propertyName is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); - } + ArgumentNullException.ThrowIfNull(propertyName); WriteStartObject(propertyName.AsSpan()); } diff --git a/src/libraries/System.Threading.Channels/src/System/Threading/Channels/Channel.cs b/src/libraries/System.Threading.Channels/src/System/Threading/Channels/Channel.cs index 317636579a05fd..554a60d10724a3 100644 --- a/src/libraries/System.Threading.Channels/src/System/Threading/Channels/Channel.cs +++ b/src/libraries/System.Threading.Channels/src/System/Threading/Channels/Channel.cs @@ -17,10 +17,7 @@ public static Channel CreateUnbounded() => /// The created channel. public static Channel CreateUnbounded(UnboundedChannelOptions options) { - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); if (options.SingleReader) { @@ -64,10 +61,7 @@ public static Channel CreateBounded(BoundedChannelOptions options) /// The created channel. public static Channel CreateBounded(BoundedChannelOptions options, Action? itemDropped) { - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); return new BoundedChannel(options.Capacity, options.FullMode, !options.AllowSynchronousContinuations, itemDropped); } diff --git a/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/ConcurrencyLimiter.cs b/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/ConcurrencyLimiter.cs index 6c19821cf462bf..a4030f8985e8b8 100644 --- a/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/ConcurrencyLimiter.cs +++ b/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/ConcurrencyLimiter.cs @@ -39,10 +39,7 @@ public sealed class ConcurrencyLimiter : RateLimiter /// Options to specify the behavior of the . public ConcurrencyLimiter(ConcurrencyLimiterOptions options) { - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); if (options.PermitLimit <= 0) { throw new ArgumentException(SR.Format(SR.ShouldBeGreaterThan0, nameof(options.PermitLimit)), nameof(options)); diff --git a/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/FixedWindowRateLimiter.cs b/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/FixedWindowRateLimiter.cs index d4b4b2f61867f7..7fc28191aae547 100644 --- a/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/FixedWindowRateLimiter.cs +++ b/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/FixedWindowRateLimiter.cs @@ -46,10 +46,7 @@ public sealed class FixedWindowRateLimiter : ReplenishingRateLimiter /// Options to specify the behavior of the . public FixedWindowRateLimiter(FixedWindowRateLimiterOptions options) { - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); if (options.PermitLimit <= 0) { throw new ArgumentException(SR.Format(SR.ShouldBeGreaterThan0, nameof(options.PermitLimit)), nameof(options)); diff --git a/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/PartitionedRateLimiter.cs b/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/PartitionedRateLimiter.cs index a2f592c5ea3b5d..560ed4b63bafe8 100644 --- a/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/PartitionedRateLimiter.cs +++ b/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/PartitionedRateLimiter.cs @@ -54,10 +54,7 @@ public static PartitionedRateLimiter Create public static PartitionedRateLimiter CreateChained( params PartitionedRateLimiter[] limiters) { - if (limiters is null) - { - throw new ArgumentNullException(nameof(limiters)); - } + ArgumentNullException.ThrowIfNull(limiters); if (limiters.Length == 0) { throw new ArgumentException("Must pass in at least 1 limiter.", nameof(limiters)); diff --git a/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/RateLimiter.cs b/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/RateLimiter.cs index fab50530ccabe7..428c92504f9325 100644 --- a/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/RateLimiter.cs +++ b/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/RateLimiter.cs @@ -32,10 +32,7 @@ public abstract class RateLimiter : IAsyncDisposable, IDisposable /// is an empty array. public static RateLimiter CreateChained(params RateLimiter[] limiters) { - if (limiters is null) - { - throw new ArgumentNullException(nameof(limiters)); - } + ArgumentNullException.ThrowIfNull(limiters); if (limiters.Length == 0) { diff --git a/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/SlidingWindowRateLimiter.cs b/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/SlidingWindowRateLimiter.cs index ac0a59748f22a4..29b16440cd8e03 100644 --- a/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/SlidingWindowRateLimiter.cs +++ b/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/SlidingWindowRateLimiter.cs @@ -50,10 +50,7 @@ public sealed class SlidingWindowRateLimiter : ReplenishingRateLimiter /// Options to specify the behavior of the . public SlidingWindowRateLimiter(SlidingWindowRateLimiterOptions options) { - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); if (options.PermitLimit <= 0) { throw new ArgumentException(SR.Format(SR.ShouldBeGreaterThan0, nameof(options.PermitLimit)), nameof(options)); diff --git a/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/TokenBucketRateLimiter.cs b/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/TokenBucketRateLimiter.cs index f0b979b9adea92..430a87978e6f2f 100644 --- a/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/TokenBucketRateLimiter.cs +++ b/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/TokenBucketRateLimiter.cs @@ -48,10 +48,7 @@ public sealed class TokenBucketRateLimiter : ReplenishingRateLimiter /// Options to specify the behavior of the . public TokenBucketRateLimiter(TokenBucketRateLimiterOptions options) { - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); if (options.TokenLimit <= 0) { throw new ArgumentException(SR.Format(SR.ShouldBeGreaterThan0, nameof(options.TokenLimit)), nameof(options)); diff --git a/src/libraries/System.Threading.Tasks.Dataflow/src/Base/DataflowBlock.IAsyncEnumerable.cs b/src/libraries/System.Threading.Tasks.Dataflow/src/Base/DataflowBlock.IAsyncEnumerable.cs index c14ce2dc090f7c..07dcd2a41e3a9b 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Base/DataflowBlock.IAsyncEnumerable.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Base/DataflowBlock.IAsyncEnumerable.cs @@ -16,10 +16,7 @@ public static partial class DataflowBlock /// The is null (Nothing in Visual Basic). public static IAsyncEnumerable ReceiveAllAsync(this IReceivableSourceBlock source, CancellationToken cancellationToken = default) { - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } + ArgumentNullException.ThrowIfNull(source); return Core(source, cancellationToken); diff --git a/src/libraries/System.Threading.Tasks.Dataflow/src/Base/DataflowBlock.cs b/src/libraries/System.Threading.Tasks.Dataflow/src/Base/DataflowBlock.cs index 6568f2b267d0d0..934533c4c1a256 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Base/DataflowBlock.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Base/DataflowBlock.cs @@ -34,14 +34,8 @@ public static IDisposable LinkTo( this ISourceBlock source, ITargetBlock target) { - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } - if (target is null) - { - throw new ArgumentNullException(nameof(target)); - } + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(target); // This method exists purely to pass default DataflowLinkOptions // to increase usability of the "90%" case. @@ -81,22 +75,10 @@ public static IDisposable LinkTo( DataflowLinkOptions linkOptions, Predicate predicate) { - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } - if (target is null) - { - throw new ArgumentNullException(nameof(target)); - } - if (linkOptions is null) - { - throw new ArgumentNullException(nameof(linkOptions)); - } - if (predicate is null) - { - throw new ArgumentNullException(nameof(predicate)); - } + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(target); + ArgumentNullException.ThrowIfNull(linkOptions); + ArgumentNullException.ThrowIfNull(predicate); // Create the filter, which links to the real target, and then // link the real source to this intermediate filter. @@ -254,10 +236,7 @@ public DebugView(FilteredLinkPropagator filter) /// public static bool Post(this ITargetBlock target, TInput item) { - if (target is null) - { - throw new ArgumentNullException(nameof(target)); - } + ArgumentNullException.ThrowIfNull(target); return target.OfferMessage(Common.SingleMessageHeader, item, source: null, consumeToAccept: false) == DataflowMessageStatus.Accepted; } @@ -306,10 +285,7 @@ public static Task SendAsync(this ITargetBlock target, TIn /// The is null (Nothing in Visual Basic). public static Task SendAsync(this ITargetBlock target, TInput item, CancellationToken cancellationToken) { - if (target is null) - { - throw new ArgumentNullException(nameof(target)); - } + ArgumentNullException.ThrowIfNull(target); // Fast path check for cancellation if (cancellationToken.IsCancellationRequested) @@ -789,10 +765,7 @@ public DebugView(SendAsyncSource source) /// public static bool TryReceive(this IReceivableSourceBlock source, [MaybeNullWhen(false)] out TOutput item) { - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } + ArgumentNullException.ThrowIfNull(source); return source.TryReceive(null, out item); } @@ -869,10 +842,7 @@ public static Task ReceiveAsync( public static Task ReceiveAsync( this ISourceBlock source, TimeSpan timeout, CancellationToken cancellationToken) { - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } + ArgumentNullException.ThrowIfNull(source); // Validate arguments if (!Common.IsValidTimeout(timeout)) throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); @@ -954,10 +924,7 @@ public static TOutput Receive( public static TOutput Receive( this ISourceBlock source, TimeSpan timeout, CancellationToken cancellationToken) { - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } + ArgumentNullException.ThrowIfNull(source); // Validate arguments if (!Common.IsValidTimeout(timeout)) throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); @@ -1506,10 +1473,7 @@ DataflowMessageStatus ITargetBlock.OfferMessage(DataflowMessageHeader message /// void IDataflowBlock.Fault(Exception exception) { - if (exception is null) - { - throw new ArgumentNullException(nameof(exception)); - } + ArgumentNullException.ThrowIfNull(exception); TrySetResult(false); } @@ -1542,14 +1506,8 @@ void IDataflowBlock.Fault(Exception exception) public static IPropagatorBlock Encapsulate( ITargetBlock target, ISourceBlock source) { - if (target is null) - { - throw new ArgumentNullException(nameof(target)); - } - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } + ArgumentNullException.ThrowIfNull(target); + ArgumentNullException.ThrowIfNull(source); return new EncapsulatingPropagator(target, source); } @@ -1581,10 +1539,7 @@ public void Complete() /// void IDataflowBlock.Fault(Exception exception) { - if (exception is null) - { - throw new ArgumentNullException(nameof(exception)); - } + ArgumentNullException.ThrowIfNull(exception); _target.Fault(exception); } @@ -1746,26 +1701,11 @@ public static Task Choose( ISourceBlock source2, Action action2, DataflowBlockOptions dataflowBlockOptions) { - if (source1 is null) - { - throw new ArgumentNullException(nameof(source1)); - } - if (action1 is null) - { - throw new ArgumentNullException(nameof(action1)); - } - if (source2 is null) - { - throw new ArgumentNullException(nameof(source2)); - } - if (action2 is null) - { - throw new ArgumentNullException(nameof(action2)); - } - if (dataflowBlockOptions is null) - { - throw new ArgumentNullException(nameof(dataflowBlockOptions)); - } + ArgumentNullException.ThrowIfNull(source1); + ArgumentNullException.ThrowIfNull(action1); + ArgumentNullException.ThrowIfNull(source2); + ArgumentNullException.ThrowIfNull(action2); + ArgumentNullException.ThrowIfNull(dataflowBlockOptions); // Delegate to the shared implementation return ChooseCore(source1, action1, source2, action2, null, null, dataflowBlockOptions); @@ -1851,34 +1791,13 @@ public static Task Choose( ISourceBlock source3, Action action3, DataflowBlockOptions dataflowBlockOptions) { - if (source1 is null) - { - throw new ArgumentNullException(nameof(source1)); - } - if (action1 is null) - { - throw new ArgumentNullException(nameof(action1)); - } - if (source2 is null) - { - throw new ArgumentNullException(nameof(source2)); - } - if (action2 is null) - { - throw new ArgumentNullException(nameof(action2)); - } - if (source3 is null) - { - throw new ArgumentNullException(nameof(source3)); - } - if (action3 is null) - { - throw new ArgumentNullException(nameof(action3)); - } - if (dataflowBlockOptions is null) - { - throw new ArgumentNullException(nameof(dataflowBlockOptions)); - } + ArgumentNullException.ThrowIfNull(source1); + ArgumentNullException.ThrowIfNull(action1); + ArgumentNullException.ThrowIfNull(source2); + ArgumentNullException.ThrowIfNull(action2); + ArgumentNullException.ThrowIfNull(source3); + ArgumentNullException.ThrowIfNull(action3); + ArgumentNullException.ThrowIfNull(dataflowBlockOptions); // Delegate to the shared implementation return ChooseCore(source1, action1, source2, action2, source3, action3, dataflowBlockOptions); @@ -2232,10 +2151,7 @@ void IDataflowBlock.Complete() /// The is null (Nothing in Visual Basic). public static IObservable AsObservable(this ISourceBlock source) { - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } + ArgumentNullException.ThrowIfNull(source); return SourceObservable.From(source); } @@ -2300,10 +2216,7 @@ internal SourceObservable(ISourceBlock source) /// An IDisposable that may be used to unsubscribe the source. IDisposable IObservable.Subscribe(IObserver observer) { - if (observer is null) - { - throw new ArgumentNullException(nameof(observer)); - } + ArgumentNullException.ThrowIfNull(observer); // Validate arguments Common.ContractAssertMonitorStatus(_SubscriptionLock, held: false); @@ -2605,10 +2518,7 @@ private void NotifyObserversOfCompletion(Exception? targetException = null) /// An observer that wraps the target block. public static IObserver AsObserver(this ITargetBlock target) { - if (target is null) - { - throw new ArgumentNullException(nameof(target)); - } + ArgumentNullException.ThrowIfNull(target); return new TargetObserver(target); } diff --git a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/ActionBlock.cs b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/ActionBlock.cs index 77fda4a62cf3aa..45f8bbeb0ec2fc 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/ActionBlock.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/ActionBlock.cs @@ -68,14 +68,8 @@ public ActionBlock(Func action, ExecutionDataflowBlockOptions data /// The is null (Nothing in Visual Basic). private ActionBlock(Delegate action, ExecutionDataflowBlockOptions dataflowBlockOptions) { - if (action is null) - { - throw new ArgumentNullException(nameof(action)); - } - if (dataflowBlockOptions is null) - { - throw new ArgumentNullException(nameof(dataflowBlockOptions)); - } + ArgumentNullException.ThrowIfNull(action); + ArgumentNullException.ThrowIfNull(dataflowBlockOptions); // Ensure we have options that can't be changed by the caller dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone(); @@ -237,10 +231,7 @@ public void Complete() /// void IDataflowBlock.Fault(Exception exception) { - if (exception is null) - { - throw new ArgumentNullException(nameof(exception)); - } + ArgumentNullException.ThrowIfNull(exception); if (_defaultTarget != null) { diff --git a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BatchBlock.cs b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BatchBlock.cs index 3afb6f1a5e4322..db265298ffbbb4 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BatchBlock.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BatchBlock.cs @@ -101,10 +101,7 @@ public BatchBlock(int batchSize, GroupingDataflowBlockOptions dataflowBlockOptio /// void IDataflowBlock.Fault(Exception exception) { - if (exception is null) - { - throw new ArgumentNullException(nameof(exception)); - } + ArgumentNullException.ThrowIfNull(exception); _target.Complete(exception, dropPendingMessages: true, releaseReservedMessages: false); } diff --git a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BatchedJoinBlock.cs b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BatchedJoinBlock.cs index 91feebf19789ce..559edd480d94d5 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BatchedJoinBlock.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BatchedJoinBlock.cs @@ -156,10 +156,7 @@ public void Complete() /// void IDataflowBlock.Fault(Exception exception) { - if (exception is null) - { - throw new ArgumentNullException(nameof(exception)); - } + ArgumentNullException.ThrowIfNull(exception); Debug.Assert(_sharedResources != null, "_sharedResources not initialized"); Debug.Assert(_sharedResources._incomingLock != null, "_sharedResources._incomingLock not initialized"); @@ -413,10 +410,7 @@ public void Complete() /// void IDataflowBlock.Fault(Exception exception) { - if (exception is null) - { - throw new ArgumentNullException(nameof(exception)); - } + ArgumentNullException.ThrowIfNull(exception); Debug.Assert(_sharedResources != null, "_sharedResources not initialized"); Debug.Assert(_sharedResources._incomingLock != null, "_sharedResources._incomingLock not initialized"); @@ -616,10 +610,7 @@ public void Complete() /// void IDataflowBlock.Fault(Exception exception) { - if (exception is null) - { - throw new ArgumentNullException(nameof(exception)); - } + ArgumentNullException.ThrowIfNull(exception); lock (_sharedResources._incomingLock) { diff --git a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BroadcastBlock.cs b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BroadcastBlock.cs index 79c951a79e3d01..a900995c99cfba 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BroadcastBlock.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BroadcastBlock.cs @@ -64,10 +64,7 @@ public BroadcastBlock(Func? cloningFunction) : /// The is null (Nothing in Visual Basic). public BroadcastBlock(Func? cloningFunction, DataflowBlockOptions dataflowBlockOptions) { - if (dataflowBlockOptions is null) - { - throw new ArgumentNullException(nameof(dataflowBlockOptions)); - } + ArgumentNullException.ThrowIfNull(dataflowBlockOptions); // Ensure we have options that can't be changed by the caller dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone(); @@ -114,10 +111,7 @@ public void Complete() /// void IDataflowBlock.Fault(Exception exception) { - if (exception is null) - { - throw new ArgumentNullException(nameof(exception)); - } + ArgumentNullException.ThrowIfNull(exception); CompleteCore(exception, storeExceptionEvenIfAlreadyCompleting: false); } @@ -1008,14 +1002,8 @@ private void CompleteBlockOncePossible() /// internal IDisposable LinkTo(ITargetBlock target, DataflowLinkOptions linkOptions) { - if (target is null) - { - throw new ArgumentNullException(nameof(target)); - } - if (linkOptions is null) - { - throw new ArgumentNullException(nameof(linkOptions)); - } + ArgumentNullException.ThrowIfNull(target); + ArgumentNullException.ThrowIfNull(linkOptions); lock (OutgoingLock) { diff --git a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BufferBlock.cs b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BufferBlock.cs index 48cab170796ab8..844b8c9b753422 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BufferBlock.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BufferBlock.cs @@ -45,10 +45,7 @@ public BufferBlock() : /// The is null (Nothing in Visual Basic). public BufferBlock(DataflowBlockOptions dataflowBlockOptions) { - if (dataflowBlockOptions is null) - { - throw new ArgumentNullException(nameof(dataflowBlockOptions)); - } + ArgumentNullException.ThrowIfNull(dataflowBlockOptions); // Ensure we have options that can't be changed by the caller dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone(); @@ -149,10 +146,7 @@ DataflowMessageStatus ITargetBlock.OfferMessage(DataflowMessageHeader message /// void IDataflowBlock.Fault(Exception exception) { - if (exception is null) - { - throw new ArgumentNullException(nameof(exception)); - } + ArgumentNullException.ThrowIfNull(exception); CompleteCore(exception, storeExceptionEvenIfAlreadyCompleting: false); } diff --git a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/JoinBlock.cs b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/JoinBlock.cs index ecf01fcf3afa26..7c02abc701a2be 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/JoinBlock.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/JoinBlock.cs @@ -49,10 +49,7 @@ public JoinBlock() : /// The is null (Nothing in Visual Basic). public JoinBlock(GroupingDataflowBlockOptions dataflowBlockOptions) { - if (dataflowBlockOptions is null) - { - throw new ArgumentNullException(nameof(dataflowBlockOptions)); - } + ArgumentNullException.ThrowIfNull(dataflowBlockOptions); // Ensure we have options that can't be changed by the caller dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone(); @@ -143,10 +140,7 @@ public void Complete() /// void IDataflowBlock.Fault(Exception exception) { - if (exception is null) - { - throw new ArgumentNullException(nameof(exception)); - } + ArgumentNullException.ThrowIfNull(exception); Debug.Assert(_sharedResources != null, "_sharedResources not initialized"); Debug.Assert(_sharedResources._exceptionAction != null, "_sharedResources._exceptionAction not initialized"); @@ -276,10 +270,7 @@ public JoinBlock() : /// The is null (Nothing in Visual Basic). public JoinBlock(GroupingDataflowBlockOptions dataflowBlockOptions) { - if (dataflowBlockOptions is null) - { - throw new ArgumentNullException(nameof(dataflowBlockOptions)); - } + ArgumentNullException.ThrowIfNull(dataflowBlockOptions); // Ensure we have options that can't be changed by the caller dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone(); @@ -370,10 +361,7 @@ public void Complete() /// void IDataflowBlock.Fault(Exception exception) { - if (exception is null) - { - throw new ArgumentNullException(nameof(exception)); - } + ArgumentNullException.ThrowIfNull(exception); Debug.Assert(_sharedResources != null, "_sharedResources not initialized"); Debug.Assert(_sharedResources._exceptionAction != null, "_sharedResources._exceptionAction not initialized"); @@ -936,10 +924,7 @@ internal override void CompleteCore(Exception? exception, bool dropPendingMessag /// void IDataflowBlock.Fault(Exception exception) { - if (exception is null) - { - throw new ArgumentNullException(nameof(exception)); - } + ArgumentNullException.ThrowIfNull(exception); CompleteCore(exception, dropPendingMessages: true, releaseReservedMessages: false); } diff --git a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/TransformBlock.cs b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/TransformBlock.cs index a95127de9e7fdf..6e0f341b9b1512 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/TransformBlock.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/TransformBlock.cs @@ -90,10 +90,7 @@ public TransformBlock(Func> transform, ExecutionDataflowBl /// The is null (Nothing in Visual Basic). private TransformBlock(Func? transformSync, Func>? transformAsync, ExecutionDataflowBlockOptions dataflowBlockOptions) { - if (dataflowBlockOptions is null) - { - throw new ArgumentNullException(nameof(dataflowBlockOptions)); - } + ArgumentNullException.ThrowIfNull(dataflowBlockOptions); if (transformSync == null && transformAsync == null) throw new ArgumentNullException("transform"); if (dataflowBlockOptions == null) throw new ArgumentNullException(nameof(dataflowBlockOptions)); @@ -335,10 +332,7 @@ private void AsyncCompleteProcessMessageWithTask(Task completed, KeyVal /// void IDataflowBlock.Fault(Exception exception) { - if (exception is null) - { - throw new ArgumentNullException(nameof(exception)); - } + ArgumentNullException.ThrowIfNull(exception); _target.Complete(exception, dropPendingMessages: true); } diff --git a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/TransformManyBlock.IAsyncEnumerable.cs b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/TransformManyBlock.IAsyncEnumerable.cs index d667d9a069e23a..393b7f2fb8e8c9 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/TransformManyBlock.IAsyncEnumerable.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/TransformManyBlock.IAsyncEnumerable.cs @@ -29,10 +29,7 @@ public TransformManyBlock(Func> transform) : /// The or is . public TransformManyBlock(Func> transform, ExecutionDataflowBlockOptions dataflowBlockOptions) { - if (transform is null) - { - throw new ArgumentNullException(nameof(transform)); - } + ArgumentNullException.ThrowIfNull(transform); Initialize(messageWithId => { diff --git a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/TransformManyBlock.cs b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/TransformManyBlock.cs index 13f762163f3c02..2247521340fe06 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/TransformManyBlock.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/TransformManyBlock.cs @@ -547,10 +547,7 @@ private void UpdateBoundingCountWithOutputCount(int count) /// void IDataflowBlock.Fault(Exception exception) { - if (exception is null) - { - throw new ArgumentNullException(nameof(exception)); - } + ArgumentNullException.ThrowIfNull(exception); _target.Complete(exception, dropPendingMessages: true); } diff --git a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/WriteOnceBlock.cs b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/WriteOnceBlock.cs index 8f9a25f24fe062..2d0c5597a2a780 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/WriteOnceBlock.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/WriteOnceBlock.cs @@ -62,10 +62,7 @@ public WriteOnceBlock(Func? cloningFunction) : /// The is null (Nothing in Visual Basic). public WriteOnceBlock(Func? cloningFunction, DataflowBlockOptions dataflowBlockOptions) { - if (dataflowBlockOptions is null) - { - throw new ArgumentNullException(nameof(dataflowBlockOptions)); - } + ArgumentNullException.ThrowIfNull(dataflowBlockOptions); // Store the option _cloningFunction = cloningFunction; @@ -208,10 +205,7 @@ private void CompleteBlock(IList? exceptions) /// void IDataflowBlock.Fault(Exception exception) { - if (exception is null) - { - throw new ArgumentNullException(nameof(exception)); - } + ArgumentNullException.ThrowIfNull(exception); CompleteCore(exception, storeExceptionEvenIfAlreadyCompleting: false); } @@ -302,14 +296,8 @@ bool IReceivableSourceBlock.TryReceiveAll([NotNullWhen(true)] out IList? i /// public IDisposable LinkTo(ITargetBlock target, DataflowLinkOptions linkOptions) { - if (target is null) - { - throw new ArgumentNullException(nameof(target)); - } - if (linkOptions is null) - { - throw new ArgumentNullException(nameof(linkOptions)); - } + ArgumentNullException.ThrowIfNull(target); + ArgumentNullException.ThrowIfNull(linkOptions); bool hasValue; bool isCompleted; diff --git a/src/libraries/System.Threading.Tasks.Dataflow/src/Internal/SourceCore.cs b/src/libraries/System.Threading.Tasks.Dataflow/src/Internal/SourceCore.cs index 05506218c3a0a2..128111df5c2d8d 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Internal/SourceCore.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Internal/SourceCore.cs @@ -123,14 +123,8 @@ internal SourceCore( /// internal IDisposable LinkTo(ITargetBlock target, DataflowLinkOptions linkOptions) { - if (target is null) - { - throw new ArgumentNullException(nameof(target)); - } - if (linkOptions is null) - { - throw new ArgumentNullException(nameof(linkOptions)); - } + ArgumentNullException.ThrowIfNull(target); + ArgumentNullException.ThrowIfNull(linkOptions); // If the block is already completed, there is not much to do - // we have to propagate completion if that was requested, and diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionInterop.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionInterop.cs index 2298caba54fd9d..4ba33af2aa28a8 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionInterop.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionInterop.cs @@ -322,7 +322,7 @@ internal static IDtcTransaction GetDtcTransaction(ITransaction transaction) public static Transaction GetTransactionFromDtcTransaction(IDtcTransaction transactionNative) { - ArgumentNullException.ThrowIfNull(transactionNative, nameof(transactionNative)); + ArgumentNullException.ThrowIfNull(transactionNative); TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) diff --git a/src/tools/illink/src/linker/Linker.Steps/ProcessLinkerXmlBase.cs b/src/tools/illink/src/linker/Linker.Steps/ProcessLinkerXmlBase.cs index e96ce5a22f5250..59035b2eaf2cad 100644 --- a/src/tools/illink/src/linker/Linker.Steps/ProcessLinkerXmlBase.cs +++ b/src/tools/illink/src/linker/Linker.Steps/ProcessLinkerXmlBase.cs @@ -55,10 +55,10 @@ protected ProcessLinkerXmlBase (LinkContext context, Stream documentStream, stri protected ProcessLinkerXmlBase (LinkContext context, Stream documentStream, EmbeddedResource resource, AssemblyDefinition resourceAssembly, string xmlDocumentLocation) : this (context, documentStream, xmlDocumentLocation) { - _resource = ( - resource ?? throw new ArgumentNullException (nameof (resource)), - resourceAssembly ?? throw new ArgumentNullException (nameof (resourceAssembly)) - ); + ArgumentNullException.ThrowIfNull(resource); + ArgumentNullException.ThrowIfNull(resourceAssembly); + + _resource = (resource, resourceAssembly); } protected virtual bool ShouldProcessElement (XPathNavigator nav) => FeatureSettings.ShouldProcessElement (nav, _context, _xmlDocumentLocation); diff --git a/src/tools/illink/src/linker/Linker/LinkContext.cs b/src/tools/illink/src/linker/Linker/LinkContext.cs index c8282d4e40e009..9e01ab75652757 100644 --- a/src/tools/illink/src/linker/Linker/LinkContext.cs +++ b/src/tools/illink/src/linker/Linker/LinkContext.cs @@ -200,8 +200,10 @@ public LinkContext (Pipeline pipeline, ILogger logger, string outputDirectory) protected LinkContext (Pipeline pipeline, ILogger logger, string outputDirectory, UnintializedContextFactory factory) { + ArgumentNullException.ThrowIfNull (logger); + _pipeline = pipeline; - _logger = logger ?? throw new ArgumentNullException (nameof (logger)); + _logger = logger; _resolver = factory.CreateResolver (this); _actions = new Dictionary ();