From e55c908229e36f99a52745d4ee85316a0e8bb6a2 Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Tue, 28 Jun 2022 14:47:36 -0400 Subject: [PATCH] Use null coalescing in many more places (#71361) --- .../src/System/Reflection/Emit/ILGenerator.cs | 4 + .../src/System/Reflection/Emit/SignatureHelper.cs | 10 +- .../src/System/Reflection/Emit/TypeBuilder.cs | 5 +- .../Common/src/System/CodeDom/CodeTypeReference.cs | 7 +- .../Common/src/System/Net/ContextAwareResult.cs | 5 +- .../Common/src/System/Net/CookieParser.cs | 5 +- .../System/Net/Logging/NetEventSource.Common.cs | 36 +++--- .../src/System/Net/NTAuthentication.Common.cs | 13 +- .../System/Net/Security/NegotiateStreamPal.Unix.cs | 5 +- .../Common/src/System/Resources/ResourceWriter.cs | 3 +- .../Runtime/InteropServices/ComEventsMethod.cs | 5 +- .../Common/src/System/Text/OSEncoding.Windows.cs | 12 +- .../ComInterop/ComEventsSink.Extended.cs | 6 +- .../RuntimeBinder/ComInterop/ComInvokeBinder.cs | 17 +-- .../RuntimeBinder/ComInterop/ComTypeClassDesc.cs | 16 +-- .../RuntimeBinder/ComInterop/IDispatchComObject.cs | 5 +- .../RuntimeBinder/ComInterop/SplatCallSite.cs | 5 +- .../CSharp/RuntimeBinder/ComInterop/TypeUtils.cs | 8 +- .../RuntimeBinder/Errors/UserStringBuilder.cs | 5 +- .../RuntimeBinder/Semantics/GroupToArgsBinder.cs | 15 +-- .../CSharp/RuntimeBinder/Semantics/MemberLookup.cs | 5 +- .../CSharp/RuntimeBinder/Semantics/Operators.cs | 8 +- .../RuntimeBinder/Semantics/PredefinedMembers.cs | 4 +- .../Semantics/Types/PredefinedTypes.cs | 2 +- .../RuntimeBinder/Semantics/Types/TypeManager.cs | 5 +- .../src/ServiceLookup/CallSiteValidator.cs | 10 +- .../ServiceLookup/ILEmit/ILEmitResolverBuilder.cs | 10 +- .../src/DependencyContextJsonReader.cs | 5 +- .../src/DependencyContextLoader.cs | 5 +- .../src/Internal/Patterns/PatternBuilder.cs | 5 +- .../src/DefaultHttpClientFactory.cs | 5 +- .../Microsoft.Extensions.Logging/src/Logger.cs | 18 +-- .../src/LoggerFactory.cs | 5 +- .../src/System/CodeDom/CodeMemberMethod.cs | 5 +- .../src/System/CodeDom/Compiler/CompilerInfo.cs | 5 +- .../Collections/Concurrent/BlockingCollection.cs | 4 +- .../Collections/Concurrent/PartitionerStatic.cs | 5 +- .../Immutable/AllocFreeConcurrentStack.cs | 15 +-- .../Collections/Immutable/ImmutableArray_1.cs | 10 +- .../Immutable/ImmutableDictionary_2.Builder.cs | 20 +-- .../Collections/Immutable/ImmutableDictionary_2.cs | 11 +- .../Collections/Immutable/ImmutableExtensions.cs | 5 +- .../Immutable/ImmutableHashSet_1.Builder.cs | 7 +- .../Collections/Immutable/ImmutableHashSet_1.cs | 5 +- .../Immutable/ImmutableList_1.Builder.cs | 20 +-- .../Collections/Immutable/ImmutableList_1.Node.cs | 5 +- .../Collections/Immutable/ImmutableQueue_1.cs | 5 +- .../ImmutableSortedDictionary_2.Builder.cs | 20 +-- .../Immutable/ImmutableSortedDictionary_2.cs | 11 +- .../Immutable/ImmutableSortedSet_1.Builder.cs | 7 +- .../Collections/Immutable/ImmutableSortedSet_1.cs | 5 +- .../src/System/Linq/ImmutableArrayExtensions.cs | 10 +- .../System/Collections/CaseInsensitiveComparer.cs | 13 +- .../src/System/Collections/DictionaryBase.cs | 10 +- .../System/Collections/ReadOnlyCollectionBase.cs | 10 +- .../src/System/Collections/SortedList.cs | 12 +- .../Collections/Specialized/HybridDictionary.cs | 18 +-- .../Specialized/NameObjectCollectionBase.cs | 16 +-- .../Collections/Specialized/NameValueCollection.cs | 10 +- .../System/Collections/Generic/SortedDictionary.cs | 27 +--- .../src/System/Collections/Generic/SortedList.cs | 14 +- .../System/Collections/StructuralComparisons.cs | 28 +--- .../DataAnnotations/CompareAttribute.cs | 5 +- .../DataAnnotations/CustomValidationAttribute.cs | 13 +- .../DataAnnotations/ValidationAttributeStore.cs | 5 +- .../Composition/Registration/ExportBuilder.cs | 15 +-- .../Composition/Registration/ImportBuilder.cs | 5 +- .../Composition/Registration/PartBuilder.cs | 20 +-- .../Composition/Registration/PartBuilderOfT.cs | 5 +- .../Internal/Collections/CollectionServices.cs | 5 +- .../AttributedModel/AttributedPartCreationInfo.cs | 5 +- .../Composition/Hosting/AtomicComposition.cs | 10 +- .../Hosting/CatalogExportProvider.FactoryExport.cs | 10 +- .../Composition/Hosting/CatalogExportProvider.cs | 5 +- .../Hosting/ComposablePartExportProvider.cs | 5 +- .../Composition/Hosting/CompositionServices.cs | 5 +- .../Hosting/ExportProvider.GetExportOverrides.cs | 5 +- .../Composition/Hosting/ExportProvider.cs | 5 +- .../Composition/Hosting/ExportsChangeEventArgs.cs | 21 +-- .../FilteredCatalog.DependenciesTraversal.cs | 5 +- .../Hosting/FilteredCatalog.DependentsTraversal.cs | 5 +- .../Hosting/ImportEngine.PartManager.cs | 22 +--- .../Primitives/ContractBasedImportDefinition.cs | 14 +- .../Composition/Primitives/ImportDefinition.cs | 5 +- .../GenericSpecializationPartCreationInfo.cs | 5 +- .../ReflectionModel/ReflectionComposablePart.cs | 5 +- .../ReflectionComposablePartDefinition.cs | 20 +-- .../ReflectionMemberExportDefinition.cs | 12 +- .../System/ComponentModel/AttributeCollection.cs | 15 +-- .../System/ComponentModel/BaseNumberConverter.cs | 10 +- .../src/System/ComponentModel/BindingList.cs | 12 +- .../ComponentModel/ComponentResourceManager.cs | 5 +- .../src/System/ComponentModel/DateOnlyConverter.cs | 5 +- .../src/System/ComponentModel/DateTimeConverter.cs | 5 +- .../ComponentModel/DateTimeOffsetConverter.cs | 5 +- .../ComponentModel/Design/DesignerOptionService.cs | 10 +- .../Design/DesigntimeLicenseContext.cs | 11 +- .../Design/Serialization/ContextStack.cs | 10 +- .../Serialization/MemberRelationshipService.cs | 12 +- .../ComponentModel/LicFileLicenseProvider.cs | 5 +- .../LicenseManager.LicenseInteropHelper.cs | 5 +- .../src/System/ComponentModel/LicenseManager.cs | 5 +- .../System/ComponentModel/MaskedTextProvider.cs | 10 +- .../System/ComponentModel/PropertyDescriptor.cs | 10 +- .../ComponentModel/ReflectPropertyDescriptor.cs | 5 +- ...ectTypeDescriptionProvider.ReflectedTypeData.cs | 10 +- .../ReflectTypeDescriptionProvider.cs | 15 +-- .../src/System/ComponentModel/TimeOnlyConverter.cs | 9 +- .../src/System/ComponentModel/TypeConverter.cs | 5 +- .../src/System/ComponentModel/TypeDescriptor.cs | 18 +-- .../src/System/ComponentModel/WeakHashtable.cs | 6 +- .../src/System/Drawing/ColorConverter.cs | 5 +- .../src/System/Drawing/PointConverter.cs | 10 +- .../src/System/Drawing/RectangleConverter.cs | 10 +- .../src/System/Drawing/SizeConverter.cs | 10 +- .../src/System/Drawing/SizeFConverter.cs | 10 +- .../Convention/ExportConventionBuilder.cs | 16 +-- .../Convention/ImportConventionBuilder.cs | 18 +-- .../Convention/PartConventionBuilder.cs | 31 +---- .../Convention/PartConventionBuilderOfT.cs | 5 +- .../Hosting/Core/CompositionOperation.cs | 6 +- .../Hosting/Util/SmallSparseInitonlyArray.cs | 6 +- .../TypedParts/Discovery/DiscoveredPart.cs | 4 +- .../Configuration/ApplicationSettingsBase.cs | 16 +-- .../Configuration/BaseConfigurationRecord.cs | 36 +++--- .../src/System/Configuration/ClientConfigPaths.cs | 2 +- .../System/Configuration/ClientSettingsStore.cs | 13 +- .../System/Configuration/ConfigurationElement.cs | 54 +++----- .../ConfigurationManagerInternalFactory.cs | 13 +- .../Configuration/DictionarySectionHandler.cs | 13 +- .../src/System/Configuration/ErrorsHelper.cs | 2 +- .../Configuration/LocalFileSettingsProvider.cs | 18 +-- .../Configuration/MgmtConfigurationRecord.cs | 4 +- .../src/System/Configuration/ProviderSettings.cs | 3 +- .../System/Configuration/SettingValueElement.cs | 14 +- .../src/System/Configuration/TypeUtil.cs | 14 +- .../src/System/Configuration/UpdateConfigHost.cs | 2 +- .../src/System/Configuration/XmlUtil.cs | 7 +- .../System.Console/src/System/IO/StdInReader.cs | 5 +- .../System.Console/src/System/TermInfo.cs | 12 +- .../src/System/Data/Common/DataRecordInternal.cs | 10 +- .../src/System/Data/Constraint.cs | 5 +- .../src/System/Data/DataColumn.cs | 46 ++----- .../src/System/Data/DataError.cs | 5 +- .../src/System/Data/DataRelation.cs | 5 +- .../System.Data.Common/src/System/Data/DataRow.cs | 4 +- .../System.Data.Common/src/System/Data/DataSet.cs | 34 ++--- .../src/System/Data/DataTable.cs | 51 ++------ .../src/System/Data/DataTableReader.cs | 12 +- .../System.Data.Common/src/System/Data/DataView.cs | 11 +- .../src/System/Data/DataViewSetting.cs | 10 +- .../src/System/Data/ProviderBase/SchemaMapping.cs | 5 +- .../src/System/Data/SQLTypes/SQLBytes.cs | 7 +- .../src/System/Data/SQLTypes/SQLChars.cs | 7 +- .../src/System/Data/SQLTypes/SQLString.cs | 9 +- .../src/System/Data/SQLTypes/SqlXml.cs | 19 +-- .../src/System/Data/XMLSchema.cs | 8 +- .../src/System/Data/XmlDataLoader.cs | 24 +--- .../src/System/Data/XmlToDatasetMap.cs | 48 +++---- .../src/System/Xml/XmlDataDocument.cs | 25 ++-- .../src/System/Data/Odbc/DbDataRecord.cs | 10 +- .../src/System/Data/Odbc/OdbcCommand.cs | 5 +- .../src/System/Data/Odbc/OdbcConnection.cs | 7 +- .../src/System/Data/Odbc/OdbcDataReader.cs | 42 +----- .../System.Data.Odbc/tests/OdbcParameterTests.cs | 5 +- .../System.Data.OleDb/src/OleDbCommandBuilder.cs | 10 +- .../System.Data.OleDb/src/OleDbMetaDataFactory.cs | 5 +- .../Diagnostics/DiagnosticSourceEventSource.cs | 11 +- .../System/Diagnostics/Metrics/MeterListener.cs | 6 +- .../System/Diagnostics/RandomNumberGenerator.cs | 12 +- .../src/System/Diagnostics/EventLog.cs | 3 +- .../Diagnostics/Reader/EventLogConfiguration.cs | 3 +- .../System/Diagnostics/Reader/EventLogRecord.cs | 18 +-- .../System/Diagnostics/Reader/EventLogSession.cs | 3 +- .../System/Diagnostics/Reader/ProviderMetadata.cs | 19 +-- .../src/System/Diagnostics/PerformanceCounter.cs | 3 +- .../Diagnostics/PerformanceCounterCategory.cs | 3 +- .../System/Diagnostics/PerformanceCounterLib.cs | 71 ++++------ .../System/Diagnostics/PerformanceCounterLib.cs | 10 +- .../src/System/Diagnostics/Process.Win32.cs | 13 +- .../System/Diagnostics/ProcessWaitState.Unix.cs | 5 +- .../src/System/Diagnostics/DefaultTraceListener.cs | 5 +- .../src/System/Diagnostics/Switch.cs | 7 +- .../src/System/Diagnostics/TraceEventCache.cs | 13 +- .../src/System/Diagnostics/TraceInternal.cs | 12 +- .../src/System/Diagnostics/TraceListener.cs | 10 +- .../src/System/Diagnostics/TraceSource.cs | 5 +- .../AccountManagement/AD/ADAMStoreCtx.cs | 3 +- .../AccountManagement/AD/ADStoreCtx.cs | 9 +- .../AccountManagement/AD/ADStoreCtx_Query.cs | 7 +- .../AccountManagement/AuthenticablePrincipal.cs | 6 +- .../DirectoryServices/AccountManagement/Context.cs | 5 +- .../AccountManagement/SAM/SAMStoreCtx.cs | 6 +- .../tests/AccountManagementTests.cs | 13 +- .../Protocols/common/BerConverter.cs | 3 +- .../ActiveDirectory/ActiveDirectorySchema.cs | 11 +- .../ActiveDirectory/ActiveDirectorySchemaClass.cs | 20 +-- .../ActiveDirectorySchemaClassCollection.cs | 15 +-- .../ActiveDirectorySchemaProperty.cs | 15 +-- .../ActiveDirectorySchemaPropertyCollection.cs | 15 +-- .../DirectoryServices/ActiveDirectory/ConfigSet.cs | 30 +---- .../ActiveDirectory/DirectoryEntryManager.cs | 5 +- .../ActiveDirectory/DirectoryServer.cs | 6 +- .../DirectoryServices/ActiveDirectory/Domain.cs | 24 +--- .../ActiveDirectory/DomainController.cs | 11 +- .../DirectoryServices/ActiveDirectory/Forest.cs | 36 +----- .../ActiveDirectory/ReadOnlyStringCollection.cs | 7 +- .../Design/DirectoryEntryConverter.cs | 10 +- .../System/DirectoryServices/DirectoryEntries.cs | 5 +- .../src/System/DirectoryServices/DirectoryEntry.cs | 22 +--- .../System/DirectoryServices/DirectorySearcher.cs | 16 +-- .../DirectoryServices/SearchResultCollection.cs | 18 +-- .../src/System/Drawing/ColorConverter.cs | 8 +- .../src/System/Drawing/FontConverter.cs | 13 +- .../src/System/Drawing/Image.cs | 5 +- .../src/System/Drawing/ImageAnimator.cs | 5 +- .../System/Drawing/Internal/SystemColorTracker.cs | 2 + .../src/System/Drawing/PointConverter.cs | 8 +- .../System/Drawing/Printing/MarginsConverter.cs | 10 +- .../src/System/Drawing/Printing/PageSettings.cs | 9 +- .../src/System/Drawing/Printing/PrintDocument.cs | 31 +---- .../src/System/Drawing/Printing/PrinterSettings.cs | 3 +- .../Drawing/Printing/QueryPageSettingsEventArgs.cs | 5 +- .../src/System/Drawing/RectangleConverter.cs | 8 +- .../src/System/Drawing/SizeConverter.cs | 16 +-- .../src/System/Drawing/SystemBrushes.cs | 7 +- .../src/System/Drawing/SystemFonts.cs | 5 +- .../src/System/Drawing/SystemPens.cs | 7 +- .../src/System/Drawing/ToolboxBitmapAttribute.cs | 16 +-- .../src/misc/GDI/DeviceContext.cs | 5 +- .../src/misc/GDI/DeviceContexts.cs | 13 +- .../System/Formats/Asn1/AsnDecoder.BitString.cs | 5 +- .../System/Formats/Asn1/AsnDecoder.OctetString.cs | 5 +- .../src/System/Formats/Asn1/AsnWriter.cs | 5 +- .../IO/Packaging/InternalRelationshipCollection.cs | 4 + .../src/System/IO/Packaging/PackUriHelper.cs | 22 +--- .../src/System/IO/Packaging/Package.cs | 9 +- .../src/System/IO/Packaging/PackagePart.cs | 7 +- .../System/IO/Packaging/XmlCompatibilityReader.cs | 138 ++------------------ .../src/System/IO/Packaging/ZipPackage.cs | 3 +- .../System/IO/Pipelines/PipeCompletionCallbacks.cs | 6 +- .../src/System/IO/Pipelines/StreamPipeReader.cs | 6 +- .../src/System/IO/Pipelines/StreamPipeWriter.cs | 6 +- .../src/System/Dynamic/DynamicObject.cs | 3 +- .../src/System/Dynamic/ExpandoClass.cs | 5 +- .../Compiler/DelegateHelpers.Generated.cs | 5 +- .../System/Linq/Expressions/Compiler/LabelInfo.cs | 5 +- .../Compiler/LambdaCompiler.ControlFlow.cs | 5 +- .../Compiler/LambdaCompiler.Expressions.cs | 5 +- .../Compiler/LambdaCompiler.Statements.cs | 4 +- .../Compiler/StackSpiller.ChildRewriter.cs | 5 +- .../Expressions/Compiler/StackSpiller.Temps.cs | 10 +- .../Linq/Expressions/Compiler/StackSpiller.cs | 10 +- .../Linq/Expressions/Compiler/VariableBinder.cs | 10 +- .../src/System/Linq/Expressions/DebugViewWriter.cs | 5 +- .../Linq/Expressions/ExpressionStringBuilder.cs | 5 +- .../Linq/Expressions/Interpreter/BranchLabel.cs | 5 +- .../Interpreter/ControlFlowInstructions.cs | 53 ++------ .../Expressions/Interpreter/InstructionList.cs | 82 ++++-------- .../Expressions/Interpreter/InterpretedFrame.cs | 5 +- .../Linq/Expressions/Interpreter/LabelInfo.cs | 10 +- .../Linq/Expressions/Interpreter/LightCompiler.cs | 15 +-- .../Linq/Expressions/Interpreter/LocalVariables.cs | 5 +- .../System/Linq/Expressions/LambdaExpression.cs | 7 +- .../Linq/Expressions/MethodCallExpression.cs | 11 +- .../Runtime/CompilerServices/CallSiteBinder.cs | 12 +- .../Linq/Parallel/Enumerables/RangeEnumerable.cs | 3 +- .../Linq/Parallel/Enumerables/RepeatEnumerable.cs | 3 +- .../Partitioning/HashRepartitionEnumerator.cs | 4 +- .../OrderedHashRepartitionEnumerator.cs | 4 +- .../Parallel/Partitioning/PartitionedDataSource.cs | 28 +--- .../QueryOperators/Binary/UnionQueryOperator.cs | 7 +- .../Linq/Parallel/QueryOperators/QueryOperator.cs | 6 +- .../Linq/Parallel/QueryOperators/QuerySettings.cs | 23 +--- .../QueryOperators/Unary/ContainsSearchOperator.cs | 10 +- .../QueryOperators/Unary/DistinctQueryOperator.cs | 3 +- .../Unary/IndexedWhereQueryOperator.cs | 3 +- .../QueryOperators/Unary/SortQueryOperator.cs | 10 +- .../QueryOperators/Unary/WhereQueryOperator.cs | 3 +- .../src/System/Linq/Parallel/Utils/Sorting.cs | 5 +- .../Linq/Parallel/Utils/WrapperEqualityComparer.cs | 13 +- .../src/System/Linq/EnumerableRewriter.cs | 5 + .../src/System/Management/ManagementBaseObject.cs | 15 +-- .../src/System/Management/ManagementClass.cs | 5 +- .../src/System/Management/ManagementObject.cs | 20 +-- .../src/System/Management/ManagementOptions.cs | 5 +- .../src/System/Management/ManagementPath.cs | 8 ++ .../src/System/Management/ManagementScope.cs | 10 +- .../src/System/Management/Method.cs | 10 +- .../src/System/Management/Property.cs | 10 +- .../src/System/Management/WMIGenerator.cs | 5 +- .../src/System/Net/Http/WinHttpHandler.cs | 20 +-- .../Net/Http/Headers/CacheControlHeaderValue.cs | 6 +- .../src/System/Net/Http/HttpContent.cs | 12 +- .../src/System/Net/Http/HttpTelemetry.cs | 6 +- .../src/System/Net/Http/NetEventSource.Http.cs | 4 +- .../Net/Http/SocketsHttpHandler/Http3Connection.cs | 5 +- .../Http/SocketsHttpHandler/HttpConnectionPool.cs | 5 +- .../HttpEnvironmentProxy.Unix.cs | 11 +- .../HttpEnvironmentProxy.Windows.cs | 11 +- .../src/System/Net/HttpListenerContext.cs | 13 +- .../src/System/Net/HttpListenerRequest.cs | 13 +- .../src/System/Net/HttpListenerResponse.cs | 14 +- .../src/System/Net/Managed/HttpConnection.cs | 14 +- .../Net/Managed/HttpListenerResponse.Managed.cs | 5 +- .../System/Net/Managed/HttpStreamAsyncResult.cs | 3 +- .../Net/Managed/ListenerAsyncResult.Managed.cs | 3 +- .../src/System/Net/ServiceNameStore.cs | 12 +- .../src/System/Net/Windows/HttpListener.Windows.cs | 17 +-- .../Net/Windows/HttpListenerRequest.Windows.cs | 34 +---- .../Net/Windows/HttpListenerResponse.Windows.cs | 22 ++-- .../System/Net/Windows/WebSockets/WebSocketBase.cs | 10 +- .../src/System/Net/Mail/MailPriority.cs | 14 +- .../src/System/Net/Mail/SmtpClient.cs | 5 +- .../src/System/Net/Mail/SmtpReplyReaderFactory.cs | 15 +-- .../src/System/Net/Mime/MimeBasePart.cs | 15 +-- .../src/System/Net/Mime/MimeMultiPart.cs | 17 +-- .../src/System/Net/Mime/MimePart.cs | 5 +- .../Net/TrackingValidationObjectDictionary.cs | 10 +- .../Net/NetworkInformation/BsdNetworkInterface.cs | 5 +- .../NetworkInformation/UnixIPGlobalProperties.cs | 5 +- .../System/Net/NetworkInformation/Ping.Windows.cs | 5 +- .../src/System/Net/CookieContainer.cs | 11 +- .../src/System/Net/CredentialCache.cs | 12 +- .../src/System/Net/IPAddress.cs | 15 +-- .../src/System/Net/FtpControlStream.cs | 5 +- .../src/System/Net/FtpWebRequest.cs | 37 +----- .../src/System/Net/FtpWebResponse.cs | 5 +- .../System/Net/Security/NetEventSource.Security.cs | 5 +- .../src/System/Net/Security/SslStream.IO.cs | 5 +- .../src/System/Net/Security/SslStream.Protocol.cs | 11 +- .../Net/Sockets/SocketAsyncEventArgs.Windows.cs | 10 +- .../src/System/Net/Sockets/TCPClient.cs | 7 +- .../src/System/Net/WebClient.cs | 5 +- .../src/System/Net/WebHeaderCollection.cs | 22 +--- .../src/System/Diagnostics/Tracing/EventSource.cs | 11 +- .../Tracing/TraceLogging/DataCollector.cs | 5 +- .../Tracing/TraceLogging/TypeAnalysis.cs | 5 +- .../src/System/Globalization/DateTimeFormatInfo.cs | 42 ++---- .../src/System/Globalization/OrdinalCasing.Icu.cs | 5 +- .../src/System/Globalization/TextInfo.cs | 10 +- .../src/System/IO/BufferedStream.cs | 15 ++- .../IO/Enumeration/FileSystemEnumerator.Unix.cs | 3 +- .../IO/Enumeration/FileSystemEnumerator.Windows.cs | 3 +- .../src/System/IO/FileSystem.Windows.cs | 3 +- .../src/System/IO/StreamReader.cs | 8 +- .../src/System/IO/StreamWriter.cs | 8 +- .../src/System/IO/StringWriter.cs | 12 +- .../src/System/IO/TextWriter.cs | 5 +- .../src/System/Net/WebUtility.cs | 9 +- .../src/System/Runtime/Versioning/FrameworkName.cs | 9 +- .../src/System/Text/StringBuilder.cs | 11 +- .../Threading/PortableThreadPool.WaitThread.cs | 6 +- .../System/Threading/Tasks/TaskExceptionHolder.cs | 4 +- .../src/System/Threading/TimerQueue.Portable.cs | 6 +- .../Runtime/Serialization/ClassDataContract.cs | 23 +--- .../System/Runtime/Serialization/CodeGenerator.cs | 16 +-- .../Serialization/CollectionDataContract.cs | 43 ++---- .../System/Runtime/Serialization/DataContract.cs | 67 ++++------ .../Serialization/DataContractSerializer.cs | 11 +- .../Runtime/Serialization/DataContractSet.cs | 37 +----- .../src/System/Runtime/Serialization/DataMember.cs | 26 +--- .../System/Runtime/Serialization/ExportOptions.cs | 12 +- .../Runtime/Serialization/ExtensionDataReader.cs | 8 +- .../Runtime/Serialization/HybridObjectCache.cs | 17 +-- .../Json/DataContractJsonSerializer.cs | 5 +- .../Runtime/Serialization/Json/JsonDataContract.cs | 5 +- .../Json/JsonEncodingStreamWrapper.cs | 5 +- .../Json/JsonFormatGeneratorStatics.cs | 12 +- .../Json/JsonFormatWriterGenerator.cs | 17 +-- .../Serialization/Json/JsonReaderDelegator.cs | 28 +--- .../Json/ReflectionJsonFormatWriter.cs | 5 +- .../Runtime/Serialization/Json/XmlJsonReader.cs | 5 +- .../Runtime/Serialization/Json/XmlJsonWriter.cs | 30 +---- .../XmlObjectSerializerReadContextComplexJson.cs | 3 +- .../Runtime/Serialization/ObjectReferenceStack.cs | 3 +- .../Runtime/Serialization/PrimitiveDataContract.cs | 13 +- .../Runtime/Serialization/ReflectionReader.cs | 13 +- .../Serialization/ReflectionXmlFormatWriter.cs | 5 +- .../System/Runtime/Serialization/SchemaExporter.cs | 104 ++------------- .../System/Runtime/Serialization/SchemaHelper.cs | 2 +- .../Runtime/Serialization/ScopedKnownTypes.cs | 5 + .../Runtime/Serialization/SurrogateDataContract.cs | 4 +- .../Serialization/XmlFormatGeneratorStatics.cs | 9 +- .../Serialization/XmlFormatWriterGenerator.cs | 17 +-- .../Runtime/Serialization/XmlObjectSerializer.cs | 13 +- .../Serialization/XmlObjectSerializerContext.cs | 30 +---- .../XmlObjectSerializerReadContext.cs | 45 ++----- .../XmlObjectSerializerWriteContext.cs | 18 +-- .../src/System/Xml/EncodingStreamWrapper.cs | 3 +- .../src/System/Xml/UniqueId.cs | 1 - .../src/System/Xml/XmlBaseReader.cs | 78 +++-------- .../src/System/Xml/XmlBaseWriter.cs | 44 ++----- .../src/System/Xml/XmlBinaryReaderSession.cs | 3 +- .../src/System/Xml/XmlBinaryWriter.cs | 16 +-- .../src/System/Xml/XmlBinaryWriterSession.cs | 5 +- .../src/System/Xml/XmlBufferReader.cs | 13 +- .../src/System/Xml/XmlCanonicalWriter.cs | 16 +-- .../src/System/Xml/XmlConverter.cs | 30 +---- .../src/System/Xml/XmlDictionary.cs | 10 +- .../src/System/Xml/XmlDictionaryReader.cs | 15 +-- .../src/System/Xml/XmlDictionaryString.cs | 4 +- .../src/System/Xml/XmlDictionaryWriter.cs | 13 +- .../src/System/Xml/XmlNodeWriter.cs | 10 +- .../src/System/Xml/XmlSigningNodeWriter.cs | 6 +- .../src/System/Xml/XmlUTF8TextReader.cs | 5 +- .../src/System/Xml/XmlUTF8TextWriter.cs | 14 +- .../src/System/DomainNameHelper.cs | 5 +- .../System.Private.Uri/src/System/UriExt.cs | 3 +- .../src/System/Xml/Linq/XContainer.cs | 20 +-- .../src/System/Xml/Linq/XNode.cs | 18 +-- .../src/System/Xml/Linq/XNodeBuilder.cs | 5 +- .../src/System/Xml/Linq/XNodeReader.cs | 20 +-- .../src/System/Xml/Schema/XNodeValidator.cs | 5 +- .../src/System/Xml/XPath/XNodeNavigator.cs | 7 +- .../src/System/Xml/XPath/XObjectExtensions.cs | 6 +- .../src/System/Xml/Base64Encoder.cs | 5 +- .../src/System/Xml/Base64EncoderAsync.cs | 5 +- .../src/System/Xml/BinaryXml/XmlBinaryReader.cs | 6 +- .../System.Private.Xml/src/System/Xml/BitStack.cs | 5 +- .../src/System/Xml/Cache/XPathDocumentBuilder.cs | 5 +- .../src/System/Xml/Cache/XPathDocumentNavigator.cs | 6 +- .../System/Xml/Core/HtmlEncodedRawTextWriter.cs | 5 +- .../src/System/Xml/Core/HtmlUtf8RawTextWriter.cs | 5 +- .../src/System/Xml/Core/XmlCharCheckingWriter.cs | 16 +-- .../System/Xml/Core/XmlCharCheckingWriterAsync.cs | 5 +- .../src/System/Xml/Core/XmlRawWriter.cs | 5 +- .../src/System/Xml/Core/XmlRawWriterAsync.cs | 6 +- .../src/System/Xml/Core/XmlReader.cs | 6 +- .../src/System/Xml/Core/XmlReaderAsync.cs | 6 +- .../src/System/Xml/Core/XmlSubtreeReader.cs | 5 +- .../src/System/Xml/Core/XmlTextReaderImpl.cs | 48 ++----- .../src/System/Xml/Core/XmlTextReaderImplAsync.cs | 5 +- .../src/System/Xml/Core/XmlTextWriter.cs | 5 +- .../src/System/Xml/Core/XmlValidatingReaderImpl.cs | 4 +- .../src/System/Xml/Core/XmlWellFormedWriter.cs | 30 +---- .../System/Xml/Core/XmlWellFormedWriterAsync.cs | 25 +--- .../src/System/Xml/Core/XsdCachingReader.cs | 20 +-- .../src/System/Xml/Core/XsdValidatingReader.cs | 9 +- .../src/System/Xml/DiagnosticsSwitches.cs | 28 +--- .../src/System/Xml/Dom/DocumentSchemaValidator.cs | 32 ++--- .../src/System/Xml/Dom/DomNameTable.cs | 20 +-- .../src/System/Xml/Dom/XmlDocument.cs | 36 ++---- .../src/System/Xml/Dom/XmlDocumentType.cs | 22 +--- .../src/System/Xml/Dom/XmlElement.cs | 5 +- .../src/System/Xml/Dom/XmlElementList.cs | 7 +- .../src/System/Xml/Dom/XmlName.cs | 5 +- .../src/System/Xml/Dom/XmlNode.cs | 6 +- .../src/System/Xml/Dom/XmlNodeReader.cs | 11 +- .../src/System/Xml/Schema/BaseProcessor.cs | 12 +- .../src/System/Xml/Schema/ContentValidator.cs | 25 +--- .../System/Xml/Schema/DataTypeImplementation.cs | 19 +-- .../src/System/Xml/Schema/DtdParser.cs | 10 +- .../src/System/Xml/Schema/DtdValidator.cs | 11 +- .../src/System/Xml/Schema/FacetChecker.cs | 15 +-- .../src/System/Xml/Schema/Inference/Infer.cs | 18 +-- .../src/System/Xml/Schema/Preprocessor.cs | 26 +--- .../System/Xml/Schema/SchemaCollectionCompiler.cs | 5 +- .../src/System/Xml/Schema/SchemaDeclBase.cs | 5 +- .../src/System/Xml/Schema/SchemaElementDecl.cs | 5 +- .../src/System/Xml/Schema/SchemaInfo.cs | 39 +----- .../src/System/Xml/Schema/SchemaSetCompiler.cs | 29 +---- .../src/System/Xml/Schema/XdrBuilder.cs | 3 +- .../src/System/Xml/Schema/XdrValidator.cs | 5 +- .../src/System/Xml/Schema/XmlSchema.cs | 82 ++---------- .../System/Xml/Schema/XmlSchemaAttributeGroup.cs | 12 +- .../src/System/Xml/Schema/XmlSchemaCollection.cs | 6 +- .../src/System/Xml/Schema/XmlSchemaComplexType.cs | 39 +----- .../src/System/Xml/Schema/XmlSchemaElement.cs | 13 +- .../src/System/Xml/Schema/XmlSchemaObject.cs | 9 +- .../src/System/Xml/Schema/XmlSchemaSet.cs | 144 ++++----------------- .../src/System/Xml/Schema/XmlSchemaValidator.cs | 28 +--- .../src/System/Xml/Schema/XmlValueConverter.cs | 5 +- .../src/System/Xml/Schema/XsdBuilder.cs | 18 +-- .../src/System/Xml/Schema/XsdValidator.cs | 10 +- .../src/System/Xml/Serialization/CodeGenerator.cs | 31 +---- .../src/System/Xml/Serialization/Compilation.cs | 19 +-- .../src/System/Xml/Serialization/ImportContext.cs | 84 ++---------- .../src/System/Xml/Serialization/Mappings.cs | 32 +---- .../ReflectionXmlSerializationReader.cs | 10 +- .../ReflectionXmlSerializationWriter.cs | 8 +- .../src/System/Xml/Serialization/SchemaImporter.cs | 57 +------- .../Xml/Serialization/SoapReflectionImporter.cs | 19 +-- .../src/System/Xml/Serialization/Types.cs | 56 ++------ .../src/System/Xml/Serialization/XmlMapping.cs | 5 +- .../Xml/Serialization/XmlReflectionImporter.cs | 68 +++------- .../System/Xml/Serialization/XmlSchemaExporter.cs | 12 +- .../System/Xml/Serialization/XmlSchemaImporter.cs | 10 +- .../src/System/Xml/Serialization/XmlSchemas.cs | 56 +------- .../Xml/Serialization/XmlSerializationReader.cs | 38 ++---- .../Serialization/XmlSerializationReaderILGen.cs | 12 +- .../Xml/Serialization/XmlSerializationWriter.cs | 10 +- .../Serialization/XmlSerializationWriterILGen.cs | 8 +- .../src/System/Xml/Serialization/XmlSerializer.cs | 11 +- .../Xml/Serialization/XmlSerializerNamespaces.cs | 10 +- .../System/Xml/XPath/Internal/CompiledXPathExpr.cs | 5 +- .../System/Xml/XPath/Internal/FollSiblingQuery.cs | 5 +- .../src/System/Xml/XPath/Internal/QueryBuilder.cs | 5 +- .../src/System/Xml/XPath/XPathDocument.cs | 6 +- .../src/System/Xml/XPath/XPathException.cs | 14 +- .../src/System/Xml/XPath/XPathNavigator.cs | 58 ++------- .../src/System/Xml/XPath/XPathNavigatorReader.cs | 10 +- .../src/System/Xml/XmlComplianceUtil.cs | 10 +- .../src/System/Xml/XmlConvert.cs | 10 +- .../src/System/Xml/Xsl/IlGen/GenerateHelper.cs | 3 +- .../src/System/Xml/Xsl/IlGen/StaticDataManager.cs | 32 ++--- .../System/Xml/Xsl/IlGen/XmlILConstructAnalyzer.cs | 11 +- .../System/Xml/Xsl/IlGen/XmlILOptimizerVisitor.cs | 5 +- .../src/System/Xml/Xsl/QIL/QilCloneVisitor.cs | 6 +- .../src/System/Xml/Xsl/QIL/QilXmlWriter.cs | 4 +- .../Xml/Xsl/Runtime/DocumentOrderComparer.cs | 6 +- .../System/Xml/Xsl/Runtime/WhitespaceRuleReader.cs | 7 +- .../System/Xml/Xsl/Runtime/XmlExtensionFunction.cs | 3 +- .../src/System/Xml/Xsl/Runtime/XmlQueryContext.cs | 3 +- .../src/System/Xml/Xsl/Runtime/XmlQueryOutput.cs | 9 +- .../src/System/Xml/Xsl/Runtime/XmlQueryRuntime.cs | 13 +- .../Xml/Xsl/Runtime/XmlSortKeyAccumulator.cs | 3 +- .../src/System/Xml/Xsl/Runtime/XsltFunctions.cs | 9 +- .../src/System/Xml/Xsl/Runtime/XsltLibrary.cs | 10 +- .../src/System/Xml/Xsl/XmlILCommand.cs | 3 +- .../src/System/Xml/Xsl/Xslt/QilGenerator.cs | 5 +- .../src/System/Xml/Xsl/Xslt/QilGeneratorEnv.cs | 5 +- .../src/System/Xml/Xsl/Xslt/QilStrConcatenator.cs | 5 +- .../src/System/Xml/Xsl/Xslt/XslAst.cs | 5 +- .../src/System/Xml/Xsl/Xslt/XsltLoader.cs | 36 +----- .../src/System/Xml/Xsl/XsltOld/ActionFrame.cs | 14 +- .../src/System/Xml/Xsl/XsltOld/Compiler.cs | 5 +- .../src/System/Xml/Xsl/XsltOld/ContainerAction.cs | 10 +- .../src/System/Xml/Xsl/XsltOld/ForEachAction.cs | 5 +- .../src/System/Xml/Xsl/XsltOld/InputScope.cs | 15 +-- .../src/System/Xml/Xsl/XsltOld/Processor.cs | 45 +------ .../src/System/Xml/Xsl/XsltOld/ReaderOutput.cs | 20 +-- .../src/System/Xml/Xsl/XsltOld/RecordBuilder.cs | 4 + .../src/System/Xml/Xsl/XsltOld/RootAction.cs | 22 +--- .../src/System/Xml/Xsl/XsltOld/SequentialOutput.cs | 5 +- .../src/System/Xml/Xsl/XsltOld/Stylesheet.cs | 25 +--- .../System/Xml/Xsl/XsltOld/TemplateLookupAction.cs | 10 +- .../src/System/Xml/Xsl/XsltOld/TemplateManager.cs | 5 +- .../src/System/Xml/Xsl/XsltOld/XsltOutput.cs | 5 +- .../System/Reflection/Context/Custom/CustomType.cs | 19 +-- .../System/Reflection/DispatchProxyGenerator.cs | 14 +- .../Ecma335/Encoding/ControlFlowBuilder.cs | 5 +- .../Reflection/Metadata/Internal/NamespaceCache.cs | 5 +- .../System/Reflection/Metadata/MetadataReader.cs | 5 +- .../Metadata/TypeSystem/EventDefinition.cs | 3 +- .../Metadata/TypeSystem/PropertyDefinition.cs | 3 +- .../Runtime/BindingFlagSupport/PropertyPolicies.cs | 12 +- .../Assemblies/RoAssembly.GetForwardedTypes.cs | 5 +- .../Reflection/TypeLoading/General/Helpers.cs | 3 +- .../MethodBase/Ecma/EcmaMethodDecoder.cs | 3 +- .../TypeLoading/RuntimeTypeInfo.BindingFlags.cs | 9 +- .../Extensions/DeserializingResourceReader.cs | 9 +- .../src/System/Runtime/Caching/CacheItemPolicy.cs | 12 +- .../src/System/Runtime/Caching/MemoryCache.cs | 15 +-- .../src/System/Runtime/Caching/MemoryCacheEntry.cs | 21 +-- .../AddDisableRuntimeMarshallingAttributeFixer.cs | 9 +- .../LibraryImportGenerator.cs | 9 +- .../ManualTypeMarshallingHelper.cs | 18 +-- .../Serialization/SerializationEventsCache.cs | 2 +- .../src/System/Security/Claims/Claim.cs | 12 +- .../src/System/Security/Claims/ClaimsIdentity.cs | 12 +- .../Security/Cryptography/Pkcs/Pkcs12Builder.cs | 15 +-- .../Security/Cryptography/Pkcs/Pkcs12CertBag.cs | 5 +- .../Security/Cryptography/Pkcs/Pkcs12SafeBag.cs | 10 +- .../Cryptography/Pkcs/Pkcs12SafeContents.cs | 10 +- .../Security/Cryptography/Pkcs/Pkcs12SecretBag.cs | 5 +- .../Security/Cryptography/Pkcs/SignerInfo.cs | 42 +----- .../Security/Cryptography/Xml/EncryptedKey.cs | 18 +-- .../Cryptography/Xml/EncryptedReference.cs | 7 +- .../Security/Cryptography/Xml/EncryptedType.cs | 27 +--- .../Security/Cryptography/Xml/EncryptedXml.cs | 10 +- .../System/Security/Cryptography/Xml/KeyInfo.cs | 3 +- .../Security/Cryptography/Xml/KeyInfoX509Data.cs | 18 +-- .../System/Security/Cryptography/Xml/Reference.cs | 7 +- .../System/Security/Cryptography/Xml/Signature.cs | 9 +- .../System/Security/Cryptography/Xml/SignedXml.cs | 61 ++++----- .../Cryptography/Xml/XmlDecryptionTransform.cs | 10 +- .../Xml/XmlDsigEnvelopedSignatureTransform.cs | 5 +- .../Security/Cryptography/CapiHelper.Windows.cs | 4 +- .../System/Security/Cryptography/CngKey.Create.cs | 3 +- .../src/System/Security/Cryptography/Oid.cs | 7 +- .../System/Security/Cryptography/OidCollection.cs | 6 +- .../Cryptography/PasswordDeriveBytes.Windows.cs | 5 +- .../SHAHashProvider.Browser.Managed.cs | 5 +- .../CertificateData.ManagedDecode.cs | 6 +- .../X509Certificates/ChainPal.Android.cs | 5 +- .../X509Certificates/OpenSslX509ChainProcessor.cs | 10 +- .../X509Certificates/UnixPkcs12Reader.cs | 5 +- .../X509Certificates/X500DistinguishedName.cs | 13 +- .../X509Certificates/X509Certificate2.cs | 21 ++- .../Cryptography/X509Certificates/X509Chain.cs | 22 +--- .../X509Certificates/X509SignatureGenerator.cs | 13 +- .../System/Security/Cryptography/XmlKeyHelper.cs | 5 +- .../Security/Permissions/PrincipalPermission.cs | 3 +- .../Principal/IdentityNotMappedException.cs | 12 +- .../System/Security/Principal/WindowsIdentity.cs | 45 +++---- .../Syndication/Atom10FeedFormatter.cs | 5 +- .../AtomPub10ServiceDocumentFormatter.cs | 5 +- .../Syndication/ResourceCollectionInfo.cs | 11 +- .../ServiceModel/Syndication/Rss20FeedFormatter.cs | 5 +- .../Syndication/SyndicationElementExtension.cs | 10 +- .../SyndicationElementExtensionCollection.cs | 15 +-- .../Syndication/XmlSyndicationContent.cs | 10 +- .../src/System/ServiceProcess/ServiceBase.cs | 18 +-- .../src/System/ServiceProcess/ServiceController.cs | 5 +- .../System.Speech/src/Recognition/Grammar.cs | 10 +- .../src/Recognition/RecognizerBase.cs | 4 +- .../System.Speech/src/Synthesis/VoiceInfo.cs | 11 +- .../src/System/Text/DecoderBestFitFallback.cs | 3 +- .../src/System/Text/EncoderBestFitFallback.cs | 3 +- .../src/System/Text/Json/BitStack.cs | 5 +- .../src/System/Text/Json/Nodes/JsonArray.cs | 6 +- .../Json/Serialization/IgnoreReferenceResolver.cs | 5 +- .../JsonSerializerOptions.Converters.cs | 5 +- .../Serialization/Metadata/JsonTypeInfo.Cache.cs | 10 +- .../src/Base/DataflowBlock.cs | 6 +- .../src/Blocks/BatchBlock.cs | 2 +- .../src/Blocks/TransformManyBlock.cs | 3 +- .../src/System/Threading/Tasks/Parallel.cs | 3 +- .../System/Transactions/DurableEnlistmentState.cs | 20 +-- .../src/System/Transactions/Transaction.cs | 12 +- .../src/System/Transactions/TransactionManager.cs | 26 +--- .../src/System/Transactions/TransactionScope.cs | 17 +-- .../src/System/Transactions/TransactionState.cs | 85 +++--------- .../System/Transactions/VolatileEnlistmentState.cs | 5 +- .../src/System/Web/Util/HttpEncoder.cs | 10 +- .../src/System/Media/SoundPlayer.cs | 5 +- .../src/System/Delegate.Mono.cs | 3 +- .../src/System/Reflection/CustomAttribute.cs | 7 +- .../src/System/Reflection/Emit/DynamicMethod.cs | 16 +-- .../src/System/Reflection/Emit/ILGenerator.Mono.cs | 6 + .../System/Reflection/Emit/MethodBuilder.Mono.cs | 3 +- .../System/Reflection/Emit/ModuleBuilder.Mono.cs | 10 +- .../src/System/Reflection/Emit/SignatureHelper.cs | 3 +- .../src/System/Reflection/Emit/TypeBuilder.Mono.cs | 3 +- .../Reflection/Emit/TypeBuilderInstantiation.cs | 33 ++--- .../src/System/Reflection/RuntimeEventInfo.cs | 6 +- .../src/System/Reflection/RuntimeFieldInfo.cs | 14 +- .../src/System/RuntimeType.Mono.cs | 20 +-- .../src/System/TypeNameParser.cs | 9 +- .../System.Private.CoreLib/src/System/TypeSpec.cs | 20 +-- 641 files changed, 1768 insertions(+), 6410 deletions(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/ILGenerator.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/ILGenerator.cs index f87435f..6498a25 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/ILGenerator.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/ILGenerator.cs @@ -104,9 +104,13 @@ namespace System.Reflection.Emit internal virtual void RecordTokenFixup() { if (m_RelocFixupList == null) + { m_RelocFixupList = new int[DefaultFixupArraySize]; + } else if (m_RelocFixupList.Length <= m_RelocFixupCount) + { m_RelocFixupList = EnlargeArray(m_RelocFixupList); + } m_RelocFixupList[m_RelocFixupCount++] = m_length; } diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/SignatureHelper.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/SignatureHelper.cs index a1f913b..93c80fc 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/SignatureHelper.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/SignatureHelper.cs @@ -52,10 +52,7 @@ namespace System.Reflection.Emit SignatureHelper sigHelp; MdSigCallingConvention intCall; - if (returnType == null) - { - returnType = typeof(void); - } + returnType ??= typeof(void); intCall = MdSigCallingConvention.Default; @@ -150,10 +147,7 @@ namespace System.Reflection.Emit { SignatureHelper sigHelp; - if (returnType == null) - { - returnType = typeof(void); - } + returnType ??= typeof(void); MdSigCallingConvention intCall = MdSigCallingConvention.Property; diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.cs index cc0c86e..3310d40 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.cs @@ -1430,10 +1430,7 @@ namespace System.Reflection.Emit BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, EmptyTypes, null); } - if (con == null) - { - con = m_typeParent!.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, EmptyTypes, null); - } + con ??= m_typeParent!.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, EmptyTypes, null); if (con == null) throw new NotSupportedException(SR.NotSupported_NoParentDefaultConstructor); diff --git a/src/libraries/Common/src/System/CodeDom/CodeTypeReference.cs b/src/libraries/Common/src/System/CodeDom/CodeTypeReference.cs index 63d6e61..ec93522 100644 --- a/src/libraries/Common/src/System/CodeDom/CodeTypeReference.cs +++ b/src/libraries/Common/src/System/CodeDom/CodeTypeReference.cs @@ -348,12 +348,7 @@ namespace System.Runtime.Serialization return ArrayElementType.TypeArguments; } - if (_typeArguments == null) - { - _typeArguments = new CodeTypeReferenceCollection(); - } - - return _typeArguments; + return _typeArguments ??= new CodeTypeReferenceCollection(); } } diff --git a/src/libraries/Common/src/System/Net/ContextAwareResult.cs b/src/libraries/Common/src/System/Net/ContextAwareResult.cs index 87d936a..fdfc440 100644 --- a/src/libraries/Common/src/System/Net/ContextAwareResult.cs +++ b/src/libraries/Common/src/System/Net/ContextAwareResult.cs @@ -287,10 +287,7 @@ namespace System.Net { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "starting capture"); - if (cachedContext == null) - { - cachedContext = ExecutionContext.Capture(); - } + cachedContext ??= ExecutionContext.Capture(); if (cachedContext != null) { diff --git a/src/libraries/Common/src/System/Net/CookieParser.cs b/src/libraries/Common/src/System/Net/CookieParser.cs index 1e0ee27..b87c74d 100644 --- a/src/libraries/Common/src/System/Net/CookieParser.cs +++ b/src/libraries/Common/src/System/Net/CookieParser.cs @@ -775,10 +775,7 @@ namespace System.Net if (first && (token == CookieToken.NameValuePair || token == CookieToken.Attribute)) { - if (cookie == null) - { - cookie = new Cookie(); - } + cookie ??= new Cookie(); InternalSetNameMethod(cookie, _tokenizer.Name); cookie.Value = _tokenizer.Value; } diff --git a/src/libraries/Common/src/System/Net/Logging/NetEventSource.Common.cs b/src/libraries/Common/src/System/Net/Logging/NetEventSource.Common.cs index ffbbc20..a292310 100644 --- a/src/libraries/Common/src/System/Net/Logging/NetEventSource.Common.cs +++ b/src/libraries/Common/src/System/Net/Logging/NetEventSource.Common.cs @@ -382,10 +382,10 @@ namespace System.Net { if (Log.IsEnabled()) { - if (arg1 == null) arg1 = ""; - if (arg2 == null) arg2 = ""; - if (arg3 == null) arg3 = ""; - if (arg4 == null) arg4 = ""; + arg1 ??= ""; + arg2 ??= ""; + arg3 ??= ""; + arg4 ??= ""; fixed (char* string1Bytes = arg1) fixed (char* string2Bytes = arg2) @@ -430,9 +430,9 @@ namespace System.Net { if (Log.IsEnabled()) { - if (arg1 == null) arg1 = ""; - if (arg2 == null) arg2 = ""; - if (arg3 == null) arg3 = Array.Empty(); + arg1 ??= ""; + arg2 ??= ""; + arg3 ??= Array.Empty(); fixed (char* arg1Ptr = arg1) fixed (char* arg2Ptr = arg2) @@ -477,7 +477,7 @@ namespace System.Net { if (Log.IsEnabled()) { - if (arg1 == null) arg1 = ""; + arg1 ??= ""; fixed (char* arg1Ptr = arg1) { @@ -519,8 +519,8 @@ namespace System.Net { if (Log.IsEnabled()) { - if (arg1 == null) arg1 = ""; - if (arg3 == null) arg3 = ""; + arg1 ??= ""; + arg3 ??= ""; fixed (char* arg1Ptr = arg1) fixed (char* arg3Ptr = arg3) @@ -558,8 +558,8 @@ namespace System.Net { if (Log.IsEnabled()) { - if (arg1 == null) arg1 = ""; - if (arg2 == null) arg2 = ""; + arg1 ??= ""; + arg2 ??= ""; fixed (char* arg1Ptr = arg1) fixed (char* arg2Ptr = arg2) @@ -597,9 +597,9 @@ namespace System.Net { if (Log.IsEnabled()) { - if (arg1 == null) arg1 = ""; - if (arg2 == null) arg2 = ""; - if (arg3 == null) arg3 = ""; + arg1 ??= ""; + arg2 ??= ""; + arg3 ??= ""; fixed (char* arg1Ptr = arg1) fixed (char* arg2Ptr = arg2) @@ -643,7 +643,7 @@ namespace System.Net { if (Log.IsEnabled()) { - if (arg1 == null) arg1 = ""; + arg1 ??= ""; fixed (char* arg1Ptr = arg1) { @@ -705,8 +705,8 @@ namespace System.Net { if (Log.IsEnabled()) { - if (arg1 == null) arg1 = ""; - if (arg2 == null) arg2 = ""; + arg1 ??= ""; + arg2 ??= ""; fixed (char* arg1Ptr = arg1) fixed (char* arg2Ptr = arg2) diff --git a/src/libraries/Common/src/System/Net/NTAuthentication.Common.cs b/src/libraries/Common/src/System/Net/NTAuthentication.Common.cs index cdb7103..8dae80d 100644 --- a/src/libraries/Common/src/System/Net/NTAuthentication.Common.cs +++ b/src/libraries/Common/src/System/Net/NTAuthentication.Common.cs @@ -39,18 +39,7 @@ namespace System.Net // True indicates this instance is for Server and will use AcceptSecurityContext SSPI API. internal bool IsServer => _isServer; - internal string? ClientSpecifiedSpn - { - get - { - if (_clientSpecifiedSpn == null) - { - _clientSpecifiedSpn = GetClientSpecifiedSpn(); - } - - return _clientSpecifiedSpn; - } - } + internal string? ClientSpecifiedSpn => _clientSpecifiedSpn ??= GetClientSpecifiedSpn(); internal string ProtocolName { diff --git a/src/libraries/Common/src/System/Net/Security/NegotiateStreamPal.Unix.cs b/src/libraries/Common/src/System/Net/Security/NegotiateStreamPal.Unix.cs index 47daaaf9..89fb18d 100644 --- a/src/libraries/Common/src/System/Net/Security/NegotiateStreamPal.Unix.cs +++ b/src/libraries/Common/src/System/Net/Security/NegotiateStreamPal.Unix.cs @@ -385,10 +385,7 @@ namespace System.Net.Security ref byte[] resultBlob, ref ContextFlagsPal contextFlags) { - if (securityContext == null) - { - securityContext = new SafeDeleteNegoContext((SafeFreeNegoCredentials)credentialsHandle!); - } + securityContext ??= new SafeDeleteNegoContext((SafeFreeNegoCredentials)credentialsHandle!); SafeDeleteNegoContext negoContext = (SafeDeleteNegoContext)securityContext; try diff --git a/src/libraries/Common/src/System/Resources/ResourceWriter.cs b/src/libraries/Common/src/System/Resources/ResourceWriter.cs index 01768ac..c64aff3 100644 --- a/src/libraries/Common/src/System/Resources/ResourceWriter.cs +++ b/src/libraries/Common/src/System/Resources/ResourceWriter.cs @@ -196,8 +196,7 @@ namespace System.Resources // Check for duplicate resources whose names vary only by case. _caseInsensitiveDups.Add(name, null); - if (_preserializedData == null) - _preserializedData = new Dictionary(FastResourceComparer.Default); + _preserializedData ??= new Dictionary(FastResourceComparer.Default); _preserializedData.Add(name, new PrecannedResource(typeName, data)); } diff --git a/src/libraries/Common/src/System/Runtime/InteropServices/ComEventsMethod.cs b/src/libraries/Common/src/System/Runtime/InteropServices/ComEventsMethod.cs index 73a12ea..9da0795 100644 --- a/src/libraries/Common/src/System/Runtime/InteropServices/ComEventsMethod.cs +++ b/src/libraries/Common/src/System/Runtime/InteropServices/ComEventsMethod.cs @@ -81,10 +81,7 @@ namespace System.Runtime.InteropServices && pi.ParameterType.HasElementType && pi.ParameterType.GetElementType()!.IsEnum) { - if (targetTypes == null) - { - targetTypes = new Type?[_expectedParamsCount]; - } + targetTypes ??= new Type?[_expectedParamsCount]; targetTypes[i] = pi.ParameterType.GetElementType(); } diff --git a/src/libraries/Common/src/System/Text/OSEncoding.Windows.cs b/src/libraries/Common/src/System/Text/OSEncoding.Windows.cs index b1ddcdd..4b1c520 100644 --- a/src/libraries/Common/src/System/Text/OSEncoding.Windows.cs +++ b/src/libraries/Common/src/System/Text/OSEncoding.Windows.cs @@ -178,17 +178,7 @@ namespace System.Text return (int)charCount; } - public override string EncodingName - { - get - { - if (_encodingName == null) - { - _encodingName = "Codepage - " + _codePage.ToString(); - } - return _encodingName; - } - } + public override string EncodingName => _encodingName ??= $"Codepage - {_codePage}"; public override string WebName { diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComEventsSink.Extended.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComEventsSink.Extended.cs index b68929a..7c000b1 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComEventsSink.Extended.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComEventsSink.Extended.cs @@ -20,11 +20,7 @@ namespace System.Runtime.InteropServices [RequiresUnreferencedCode(Binder.TrimmerWarning)] public void AddHandler(int dispid, object func) { - ComEventsMethod method = FindMethod(dispid); - if (method == null) - { - method = AddMethod(dispid); - } + ComEventsMethod method = FindMethod(dispid) ?? AddMethod(dispid); if (func is Delegate d) { diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComInvokeBinder.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComInvokeBinder.cs index 343684e..9052ad6 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComInvokeBinder.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComInvokeBinder.cs @@ -110,17 +110,7 @@ namespace Microsoft.CSharp.RuntimeBinder.ComInterop get { return EnsureVariable(ref _propertyPutDispId, typeof(int), "propertyPutDispId"); } } - private ParameterExpression ParamVariantsVariable - { - get - { - if (_paramVariants == null) - { - _paramVariants = Expression.Variable(VariantArray.GetStructType(_args.Length), "paramVariants"); - } - return _paramVariants; - } - } + private ParameterExpression ParamVariantsVariable => _paramVariants ??= Expression.Variable(VariantArray.GetStructType(_args.Length), "paramVariants"); private static ParameterExpression EnsureVariable(ref ParameterExpression var, Type type, string name) { @@ -140,10 +130,7 @@ namespace Microsoft.CSharp.RuntimeBinder.ComInterop if (isByRef) { // Null just means that null was supplied. - if (marshalType == null) - { - marshalType = mo.Expression.Type; - } + marshalType ??= mo.Expression.Type; marshalType = marshalType.MakeByRefType(); } return marshalType; diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComTypeClassDesc.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComTypeClassDesc.cs index 6b71421..3422730 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComTypeClassDesc.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComTypeClassDesc.cs @@ -19,10 +19,7 @@ namespace Microsoft.CSharp.RuntimeBinder.ComInterop [RequiresUnreferencedCode(Binder.TrimmerWarning)] public object CreateInstance() { - if (_typeObj == null) - { - _typeObj = Type.GetTypeFromCLSID(Guid); - } + _typeObj ??= Type.GetTypeFromCLSID(Guid); return Activator.CreateInstance(Type.GetTypeFromCLSID(Guid)); } @@ -50,19 +47,12 @@ namespace Microsoft.CSharp.RuntimeBinder.ComInterop if (isSourceItf) { - if (_sourceItfs == null) - { - _sourceItfs = new LinkedList(); - } + _sourceItfs ??= new LinkedList(); _sourceItfs.AddLast(itfName); } else { - if (_itfs == null) - { - _itfs = new LinkedList(); - } - + _itfs ??= new LinkedList(); _itfs.AddLast(itfName); } } diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/IDispatchComObject.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/IDispatchComObject.cs index 1c0bd12..7776fe9 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/IDispatchComObject.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/IDispatchComObject.cs @@ -282,10 +282,7 @@ namespace Microsoft.CSharp.RuntimeBinder.ComInterop [RequiresUnreferencedCode(Binder.TrimmerWarning)] internal override IList> GetMembers(IEnumerable names) { - if (names == null) - { - names = GetMemberNames(true); - } + names ??= GetMemberNames(true); Type comType = RuntimeCallableWrapper.GetType(); diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/SplatCallSite.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/SplatCallSite.cs index 2a0c30a..354da7b 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/SplatCallSite.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/SplatCallSite.cs @@ -32,10 +32,7 @@ namespace Microsoft.CSharp.RuntimeBinder.ComInterop Debug.Assert(args != null); // Create a CallSite and invoke it. - if (_site == null) - { - _site = CallSite>.Create(SplatInvokeBinder.Instance); - } + _site ??= CallSite>.Create(SplatInvokeBinder.Instance); return _site.Target(_site, _callable, args); } diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/TypeUtils.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/TypeUtils.cs index 6bd081d..11c4133 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/TypeUtils.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/TypeUtils.cs @@ -104,11 +104,9 @@ namespace Microsoft.CSharp.RuntimeBinder.ComInterop // try lifted conversion if (nnExprType != convertFrom || nnConvType != convertToType) { - method = FindConversionOperator(eMethods, nnExprType, nnConvType, implicitOnly); - if (method == null) - { - method = FindConversionOperator(cMethods, nnExprType, nnConvType, implicitOnly); - } + method = + FindConversionOperator(eMethods, nnExprType, nnConvType, implicitOnly) ?? + FindConversionOperator(cMethods, nnExprType, nnConvType, implicitOnly); if (method != null) { return method; diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Errors/UserStringBuilder.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Errors/UserStringBuilder.cs index a30b08e..3a0e6ae 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Errors/UserStringBuilder.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Errors/UserStringBuilder.cs @@ -16,10 +16,7 @@ namespace Microsoft.CSharp.RuntimeBinder.Errors private void BeginString() { Debug.Assert(_strBuilder == null || _strBuilder.Length == 0); - if (_strBuilder == null) - { - _strBuilder = new StringBuilder(); - } + _strBuilder ??= new StringBuilder(); } private string EndString() diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/GroupToArgsBinder.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/GroupToArgsBinder.cs index 5092e2a..5941f74 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/GroupToArgsBinder.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/GroupToArgsBinder.cs @@ -755,27 +755,18 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics Name name = named.Name; if (!methprop.ParameterNames.Contains(name)) { - if (_pInvalidSpecifiedName == null) - { - _pInvalidSpecifiedName = name; - } + _pInvalidSpecifiedName ??= name; return false; } else if (!currentPosition.Contains(name)) { - if (_pNameUsedInPositionalArgument == null) - { - _pNameUsedInPositionalArgument = name; - } + _pNameUsedInPositionalArgument ??= name; return false; } if (!names.Add(name)) { - if (_pDuplicateSpecifiedName == null) - { - _pDuplicateSpecifiedName = name; - } + _pDuplicateSpecifiedName ??= name; return false; } } diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/MemberLookup.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/MemberLookup.cs index b27c38f..e060dee 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/MemberLookup.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/MemberLookup.cs @@ -426,10 +426,7 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics AggregateType typeCur = typeStart; int itypeNext = 0; - if (typeCur == null) - { - typeCur = (AggregateType)types[itypeNext++]; - } + typeCur ??= (AggregateType)types[itypeNext++]; Debug.Assert(typeCur != null); // Loop through the interfaces. diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Operators.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Operators.cs index f730892..36a9ff0 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Operators.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Operators.cs @@ -1283,11 +1283,9 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics } // Try the conversion - if it fails, do a cast without user defined casts. - Expr arg = tryConvert(pArgument, uofs.GetType()); - if (arg == null) - { - arg = mustCast(pArgument, uofs.GetType(), CONVERTTYPE.NOUDC); - } + Expr arg = + tryConvert(pArgument, uofs.GetType()) ?? + mustCast(pArgument, uofs.GetType(), CONVERTTYPE.NOUDC); return uofs.pfn(this, ek, flags, arg); } diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/PredefinedMembers.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/PredefinedMembers.cs index a6f8b26..6f6ad50 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/PredefinedMembers.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/PredefinedMembers.cs @@ -306,14 +306,14 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics public static PropertySymbol GetProperty(PREDEFPROP property) { Debug.Assert(property >= 0 && property < PREDEFPROP.PP_COUNT); - return _properties[(int)property] ?? (_properties[(int)property] = LoadProperty(property)); + return _properties[(int)property] ??= LoadProperty(property); } [RequiresUnreferencedCode(Binder.TrimmerWarning)] public static MethodSymbol GetMethod(PREDEFMETH method) { Debug.Assert(method >= 0 && method < PREDEFMETH.PM_COUNT); - return _methods[(int)method] ?? (_methods[(int)method] = LoadMethod(method)); + return _methods[(int)method] ??= LoadMethod(method); } [RequiresUnreferencedCode(Binder.TrimmerWarning)] diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/PredefinedTypes.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/PredefinedTypes.cs index 291a1fa..4e8750f 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/PredefinedTypes.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/PredefinedTypes.cs @@ -33,7 +33,7 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics [RequiresUnreferencedCode(Binder.TrimmerWarning)] public static AggregateSymbol GetPredefinedAggregate(PredefinedType pt) => - s_predefSymbols[(int)pt] ?? (s_predefSymbols[(int)pt] = DelayLoadPredefSym(pt)); + s_predefSymbols[(int)pt] ??= DelayLoadPredefSym(pt); //////////////////////////////////////////////////////////////////////////////// // Some of the predefined types have built-in names, like "int" or "string" or diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/TypeManager.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/TypeManager.cs index 539221a..df3805e 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/TypeManager.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/TypeManager.cs @@ -90,10 +90,7 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics { Debug.Assert(atsOuter == null || atsOuter.OwningAggregate == agg.Parent, ""); - if (typeArgs == null) - { - typeArgs = TypeArray.Empty; - } + typeArgs ??= TypeArray.Empty; Debug.Assert(agg.GetTypeVars().Count == typeArgs.Count); AggregateType pAggregate = TypeTable.LookupAggregate(agg, atsOuter, typeArgs); diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteValidator.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteValidator.cs index 9e0b4e3..17c5d34 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteValidator.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteValidator.cs @@ -47,10 +47,7 @@ namespace Microsoft.Extensions.DependencyInjection.ServiceLookup foreach (ServiceCallSite parameterCallSite in constructorCallSite.ParameterCallSites) { Type? scoped = VisitCallSite(parameterCallSite, state); - if (result == null) - { - result = scoped; - } + result ??= scoped; } return result; } @@ -62,10 +59,7 @@ namespace Microsoft.Extensions.DependencyInjection.ServiceLookup foreach (ServiceCallSite serviceCallSite in enumerableCallSite.ServiceCallSites) { Type? scoped = VisitCallSite(serviceCallSite, state); - if (result == null) - { - result = scoped; - } + result ??= scoped; } return result; } diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ILEmit/ILEmitResolverBuilder.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ILEmit/ILEmitResolverBuilder.cs index 73a8a86..8067a66 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ILEmit/ILEmitResolverBuilder.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ILEmit/ILEmitResolverBuilder.cs @@ -238,10 +238,7 @@ namespace Microsoft.Extensions.DependencyInjection.ServiceLookup protected override object? VisitFactory(FactoryCallSite factoryCallSite, ILEmitResolverBuilderContext argument) { - if (argument.Factories == null) - { - argument.Factories = new List>(); - } + argument.Factories ??= new List>(); // this.Factories[i](ProviderScope) argument.Generator.Emit(OpCodes.Ldarg_0); @@ -259,10 +256,7 @@ namespace Microsoft.Extensions.DependencyInjection.ServiceLookup private static void AddConstant(ILEmitResolverBuilderContext argument, object? value) { - if (argument.Constants == null) - { - argument.Constants = new List(); - } + argument.Constants ??= new List(); // this.Constants[i] argument.Generator.Emit(OpCodes.Ldarg_0); diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextJsonReader.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextJsonReader.cs index 4198379..26335fe 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextJsonReader.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextJsonReader.cs @@ -165,10 +165,7 @@ namespace Microsoft.Extensions.DependencyModel } } - if (compilationOptions == null) - { - compilationOptions = CompilationOptions.Default; - } + compilationOptions ??= CompilationOptions.Default; Target? runtimeTarget = SelectRuntimeTarget(targets, runtimeTargetName); runtimeTargetName = runtimeTarget?.Name; diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextLoader.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextLoader.cs index 6bcdd35..867fadd4 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextLoader.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextLoader.cs @@ -64,10 +64,7 @@ namespace Microsoft.Extensions.DependencyModel context = LoadEntryAssemblyContext(reader); } - if (context == null) - { - context = LoadAssemblyContext(assembly, reader); - } + context ??= LoadAssemblyContext(assembly, reader); if (context != null) { diff --git a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/Patterns/PatternBuilder.cs b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/Patterns/PatternBuilder.cs index 1800f36..12601f2 100644 --- a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/Patterns/PatternBuilder.cs +++ b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/Patterns/PatternBuilder.cs @@ -154,10 +154,7 @@ namespace Microsoft.Extensions.FileSystemGlobbing.Internal.Patterns scanSegment = endLiteral + 1; } - if (segment == null) - { - segment = new WildcardPathSegment(beginsWith, contains, endsWith, ComparisonType); - } + segment ??= new WildcardPathSegment(beginsWith, contains, endsWith, ComparisonType); } if (segment is not ParentPathSegment) diff --git a/src/libraries/Microsoft.Extensions.Http/src/DefaultHttpClientFactory.cs b/src/libraries/Microsoft.Extensions.Http/src/DefaultHttpClientFactory.cs index b51f570..7e2967a 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/DefaultHttpClientFactory.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/DefaultHttpClientFactory.cs @@ -214,10 +214,7 @@ namespace Microsoft.Extensions.Http { lock (_cleanupTimerLock) { - if (_cleanupTimer == null) - { - _cleanupTimer = NonCapturingTimer.Create(_cleanupCallback, this, DefaultCleanupInterval, Timeout.InfiniteTimeSpan); - } + _cleanupTimer ??= NonCapturingTimer.Create(_cleanupCallback, this, DefaultCleanupInterval, Timeout.InfiniteTimeSpan); } } diff --git a/src/libraries/Microsoft.Extensions.Logging/src/Logger.cs b/src/libraries/Microsoft.Extensions.Logging/src/Logger.cs index 8a069df..86524a2 100644 --- a/src/libraries/Microsoft.Extensions.Logging/src/Logger.cs +++ b/src/libraries/Microsoft.Extensions.Logging/src/Logger.cs @@ -47,11 +47,7 @@ namespace Microsoft.Extensions.Logging } catch (Exception ex) { - if (exceptions == null) - { - exceptions = new List(); - } - + exceptions ??= new List(); exceptions.Add(ex); } } @@ -99,11 +95,7 @@ namespace Microsoft.Extensions.Logging } catch (Exception ex) { - if (exceptions == null) - { - exceptions = new List(); - } - + exceptions ??= new List(); exceptions.Add(ex); } @@ -137,11 +129,7 @@ namespace Microsoft.Extensions.Logging } catch (Exception ex) { - if (exceptions == null) - { - exceptions = new List(); - } - + exceptions ??= new List(); exceptions.Add(ex); } } diff --git a/src/libraries/Microsoft.Extensions.Logging/src/LoggerFactory.cs b/src/libraries/Microsoft.Extensions.Logging/src/LoggerFactory.cs index 4f88f4a..315ea91 100644 --- a/src/libraries/Microsoft.Extensions.Logging/src/LoggerFactory.cs +++ b/src/libraries/Microsoft.Extensions.Logging/src/LoggerFactory.cs @@ -195,10 +195,7 @@ namespace Microsoft.Extensions.Logging if (provider is ISupportExternalScope supportsExternalScope) { - if (_scopeProvider == null) - { - _scopeProvider = new LoggerFactoryScopeProvider(_factoryOptions.ActivityTrackingOptions); - } + _scopeProvider ??= new LoggerFactoryScopeProvider(_factoryOptions.ActivityTrackingOptions); supportsExternalScope.SetScopeProvider(_scopeProvider); } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeMemberMethod.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeMemberMethod.cs index ca55c34..e1cd920 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeMemberMethod.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeMemberMethod.cs @@ -61,10 +61,7 @@ namespace System.CodeDom { get { - if (_implementationTypes == null) - { - _implementationTypes = new CodeTypeReferenceCollection(); - } + _implementationTypes ??= new CodeTypeReferenceCollection(); if ((_populated & ImplTypesCollection) == 0) { 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 0f0edfe..b2a08cf 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerInfo.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerInfo.cs @@ -30,10 +30,7 @@ namespace System.CodeDom.Compiler { lock (this) { - if (_type == null) - { - _type = Type.GetType(_codeDomProviderTypeName); - } + _type ??= Type.GetType(_codeDomProviderTypeName); } } diff --git a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/BlockingCollection.cs b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/BlockingCollection.cs index e4ec985..22cbad3 100644 --- a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/BlockingCollection.cs +++ b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/BlockingCollection.cs @@ -690,9 +690,7 @@ namespace System.Collections.Concurrent if (waitForSemaphoreWasSuccessful == false && millisecondsTimeout != 0) { // create the linked token if it is not created yet - if (linkedTokenSource == null) - linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, - _consumersCancellationTokenSource.Token); + linkedTokenSource ??= CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _consumersCancellationTokenSource.Token); waitForSemaphoreWasSuccessful = _occupiedNodes.Wait(millisecondsTimeout, linkedTokenSource.Token); } } diff --git a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/PartitionerStatic.cs b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/PartitionerStatic.cs index 22910ff..ac906d6 100644 --- a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/PartitionerStatic.cs +++ b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/PartitionerStatic.cs @@ -926,10 +926,7 @@ namespace System.Collections.Concurrent } // defer allocation to avoid false sharing - if (_localList == null) - { - _localList = new KeyValuePair[_maxChunkSize]; - } + _localList ??= new KeyValuePair[_maxChunkSize]; // make the actual call to the enumerable that grabs a chunk return _enumerable.GrabChunk(_localList, requestedChunkSize, ref _currentChunkSize!.Value); diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/AllocFreeConcurrentStack.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/AllocFreeConcurrentStack.cs index 503ea37..ad22b0b 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/AllocFreeConcurrentStack.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/AllocFreeConcurrentStack.cs @@ -19,14 +19,11 @@ namespace System.Collections.Immutable public static void TryAdd(T item) { + Stack> localStack = #if NETCOREAPP - Stack>? localStack = t_stack; // cache in a local to avoid unnecessary TLS hits on repeated accesses - if (localStack == null) - { - t_stack = localStack = new Stack>(MaxSize); - } + t_stack ??= new Stack>(MaxSize); #else - Stack> localStack = ThreadLocalStack; + ThreadLocalStack; #endif // Just in case we're in a scenario where an object is continually requested on one thread @@ -60,11 +57,7 @@ namespace System.Collections.Immutable get { // Ensure the [ThreadStatic] is initialized to a dictionary - Dictionary? typesToStacks = AllocFreeConcurrentStack.t_stacks; - if (typesToStacks == null) - { - AllocFreeConcurrentStack.t_stacks = typesToStacks = new Dictionary(); - } + Dictionary? typesToStacks = AllocFreeConcurrentStack.t_stacks ??= new Dictionary(); // Get the stack that corresponds to the T if (!typesToStacks.TryGetValue(s_typeOfT, out object? stackObj)) diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray_1.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray_1.cs index e1d6e00..73a0b69 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray_1.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray_1.cs @@ -735,10 +735,7 @@ namespace System.Collections.Immutable { if (match(self.array[i])) { - if (removeIndices == null) - { - removeIndices = new List(); - } + removeIndices ??= new List(); removeIndices.Add(i); } @@ -809,10 +806,7 @@ namespace System.Collections.Immutable // 0 and 1 element arrays don't need to be sorted. if (count > 1) { - if (comparer == null) - { - comparer = Comparer.Default; - } + comparer ??= Comparer.Default; // Avoid copying the entire array when the array is already sorted. bool outOfOrder = false; diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary_2.Builder.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary_2.Builder.cs index 1c89245..2dc5938 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary_2.Builder.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary_2.Builder.cs @@ -505,12 +505,7 @@ namespace System.Collections.Immutable // Creating an instance of ImmutableSortedMap with our root node automatically freezes our tree, // ensuring that the returned instance is immutable. Any further mutations made to this builder // will clone (and unfreeze) the spine of modified nodes until the next time this method is invoked. - if (_immutable == null) - { - _immutable = ImmutableDictionary.Wrap(_root, _comparers, _count); - } - - return _immutable; + return _immutable ??= ImmutableDictionary.Wrap(_root, _comparers, _count); } #endregion @@ -744,17 +739,6 @@ namespace System.Collections.Immutable /// Gets a simple debugger-viewable collection. /// [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] - public KeyValuePair[] Contents - { - get - { - if (_contents == null) - { - _contents = _map.ToArray(_map.Count); - } - - return _contents; - } - } + public KeyValuePair[] Contents => _contents ??= _map.ToArray(_map.Count); } } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary_2.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary_2.cs index 0fb3c5d..40340e6 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary_2.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary_2.cs @@ -424,15 +424,8 @@ namespace System.Collections.Immutable /// public ImmutableDictionary WithComparers(IEqualityComparer? keyComparer, IEqualityComparer? valueComparer) { - if (keyComparer == null) - { - keyComparer = EqualityComparer.Default; - } - - if (valueComparer == null) - { - valueComparer = EqualityComparer.Default; - } + keyComparer ??= EqualityComparer.Default; + valueComparer ??= EqualityComparer.Default; if (this.KeyComparer == keyComparer) { diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableExtensions.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableExtensions.cs index 006a26a..9c1f19b 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableExtensions.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableExtensions.cs @@ -219,10 +219,7 @@ namespace System.Collections.Immutable { get { - if (_collection == null) - { - _collection = _sequence.ToArray(); - } + _collection ??= _sequence.ToArray(); return _collection[index]; } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableHashSet_1.Builder.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableHashSet_1.Builder.cs index 2a83032..3faf07a 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableHashSet_1.Builder.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableHashSet_1.Builder.cs @@ -194,12 +194,7 @@ namespace System.Collections.Immutable // Creating an instance of ImmutableSortedMap with our root node automatically freezes our tree, // ensuring that the returned instance is immutable. Any further mutations made to this builder // will clone (and unfreeze) the spine of modified nodes until the next time this method is invoked. - if (_immutable == null) - { - _immutable = ImmutableHashSet.Wrap(_root, _equalityComparer, _count); - } - - return _immutable; + return _immutable ??= ImmutableHashSet.Wrap(_root, _equalityComparer, _count); } /// diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableHashSet_1.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableHashSet_1.cs index 92077a5..02dc0af 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableHashSet_1.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableHashSet_1.cs @@ -418,10 +418,7 @@ namespace System.Collections.Immutable /// public ImmutableHashSet WithComparer(IEqualityComparer? equalityComparer) { - if (equalityComparer == null) - { - equalityComparer = EqualityComparer.Default; - } + equalityComparer ??= EqualityComparer.Default; if (equalityComparer == _equalityComparer) { diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Builder.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Builder.cs index c10cfa1..1b4494e 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Builder.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Builder.cs @@ -1023,12 +1023,7 @@ namespace System.Collections.Immutable // Creating an instance of ImmutableList with our root node automatically freezes our tree, // ensuring that the returned instance is immutable. Any further mutations made to this builder // will clone (and unfreeze) the spine of modified nodes until the next time this method is invoked. - if (_immutable == null) - { - _immutable = ImmutableList.WrapNode(this.Root); - } - - return _immutable; + return _immutable ??= ImmutableList.WrapNode(this.Root); } #endregion @@ -1219,17 +1214,6 @@ namespace System.Collections.Immutable /// Gets a simple debugger-viewable list. /// [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] - public T[] Contents - { - get - { - if (_cachedContents == null) - { - _cachedContents = _list.ToArray(_list.Count); - } - - return _cachedContents; - } - } + public T[] Contents => _cachedContents ??= _list.ToArray(_list.Count); } } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Node.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Node.cs index bc64c46..2a2315f 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Node.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Node.cs @@ -1038,10 +1038,7 @@ namespace System.Collections.Immutable { if (match(item)) { - if (list == null) - { - list = new List(); - } + list ??= new List(); list.Add(item); } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableQueue_1.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableQueue_1.cs index 1f2ae3e..b7ee9d7 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableQueue_1.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableQueue_1.cs @@ -109,10 +109,7 @@ namespace System.Collections.Immutable // Although this is a lazy-init pattern, no lock is required because // this instance is immutable otherwise, and a double-assignment from multiple // threads is harmless. - if (_backwardsReversed == null) - { - _backwardsReversed = _backwards.Reverse(); - } + _backwardsReversed ??= _backwards.Reverse(); Debug.Assert(_backwardsReversed != null); return _backwardsReversed; diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary_2.Builder.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary_2.Builder.cs index 75bb852..dc203b5 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary_2.Builder.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary_2.Builder.cs @@ -640,12 +640,7 @@ namespace System.Collections.Immutable // Creating an instance of ImmutableSortedMap with our root node automatically freezes our tree, // ensuring that the returned instance is immutable. Any further mutations made to this builder // will clone (and unfreeze) the spine of modified nodes until the next time this method is invoked. - if (_immutable == null) - { - _immutable = Wrap(this.Root, _count, _keyComparer, _valueComparer); - } - - return _immutable; + return _immutable ??= Wrap(this.Root, _count, _keyComparer, _valueComparer); } #endregion } @@ -679,17 +674,6 @@ namespace System.Collections.Immutable /// Gets a simple debugger-viewable collection. /// [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] - public KeyValuePair[] Contents - { - get - { - if (_contents == null) - { - _contents = _map.ToArray(_map.Count); - } - - return _contents; - } - } + public KeyValuePair[] Contents => _contents ??= _map.ToArray(_map.Count); } } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary_2.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary_2.cs index 2648014..a997c93 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary_2.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary_2.cs @@ -328,15 +328,8 @@ namespace System.Collections.Immutable /// public ImmutableSortedDictionary WithComparers(IComparer? keyComparer, IEqualityComparer? valueComparer) { - if (keyComparer == null) - { - keyComparer = Comparer.Default; - } - - if (valueComparer == null) - { - valueComparer = EqualityComparer.Default; - } + keyComparer ??= Comparer.Default; + valueComparer ??= EqualityComparer.Default; if (keyComparer == _keyComparer) { diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.Builder.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.Builder.cs index fdb44bd..3771963 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.Builder.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.Builder.cs @@ -456,12 +456,7 @@ namespace System.Collections.Immutable // Creating an instance of ImmutableSortedSet with our root node automatically freezes our tree, // ensuring that the returned instance is immutable. Any further mutations made to this builder // will clone (and unfreeze) the spine of modified nodes until the next time this method is invoked. - if (_immutable == null) - { - _immutable = ImmutableSortedSet.Wrap(this.Root, _comparer); - } - - return _immutable; + return _immutable ??= ImmutableSortedSet.Wrap(this.Root, _comparer); } /// diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.cs index a1871e4..4ee94f6 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.cs @@ -340,10 +340,7 @@ namespace System.Collections.Immutable /// public ImmutableSortedSet WithComparer(IComparer? comparer) { - if (comparer == null) - { - comparer = Comparer.Default; - } + comparer ??= Comparer.Default; if (comparer == _comparer) { diff --git a/src/libraries/System.Collections.Immutable/src/System/Linq/ImmutableArrayExtensions.cs b/src/libraries/System.Collections.Immutable/src/System/Linq/ImmutableArrayExtensions.cs index 34f9e3b..5dc4019 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Linq/ImmutableArrayExtensions.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Linq/ImmutableArrayExtensions.cs @@ -167,10 +167,7 @@ namespace System.Linq return false; } - if (comparer == null) - { - comparer = EqualityComparer.Default; - } + comparer ??= EqualityComparer.Default; for (int i = 0; i < immutableArray.Length; i++) { @@ -192,10 +189,7 @@ namespace System.Linq { Requires.NotNull(items, nameof(items)); - if (comparer == null) - { - comparer = EqualityComparer.Default; - } + comparer ??= EqualityComparer.Default; int i = 0; int n = immutableArray.Length; diff --git a/src/libraries/System.Collections.NonGeneric/src/System/Collections/CaseInsensitiveComparer.cs b/src/libraries/System.Collections.NonGeneric/src/System/Collections/CaseInsensitiveComparer.cs index c385f1e..0c84d46 100644 --- a/src/libraries/System.Collections.NonGeneric/src/System/Collections/CaseInsensitiveComparer.cs +++ b/src/libraries/System.Collections.NonGeneric/src/System/Collections/CaseInsensitiveComparer.cs @@ -39,17 +39,8 @@ namespace System.Collections } } - public static CaseInsensitiveComparer DefaultInvariant - { - get - { - if (s_InvariantCaseInsensitiveComparer == null) - { - s_InvariantCaseInsensitiveComparer = new CaseInsensitiveComparer(CultureInfo.InvariantCulture); - } - return s_InvariantCaseInsensitiveComparer; - } - } + public static CaseInsensitiveComparer DefaultInvariant => + s_InvariantCaseInsensitiveComparer ??= new CaseInsensitiveComparer(CultureInfo.InvariantCulture); // Behaves exactly like Comparer.Default.Compare except that the comparison is case insensitive // Compares two Objects by calling CompareTo. diff --git a/src/libraries/System.Collections.NonGeneric/src/System/Collections/DictionaryBase.cs b/src/libraries/System.Collections.NonGeneric/src/System/Collections/DictionaryBase.cs index 151b361..658b63b 100644 --- a/src/libraries/System.Collections.NonGeneric/src/System/Collections/DictionaryBase.cs +++ b/src/libraries/System.Collections.NonGeneric/src/System/Collections/DictionaryBase.cs @@ -18,15 +18,7 @@ namespace System.Collections { private Hashtable? _hashtable; - protected Hashtable InnerHashtable - { - get - { - if (_hashtable == null) - _hashtable = new Hashtable(); - return _hashtable; - } - } + protected Hashtable InnerHashtable => _hashtable ??= new Hashtable(); protected IDictionary Dictionary { diff --git a/src/libraries/System.Collections.NonGeneric/src/System/Collections/ReadOnlyCollectionBase.cs b/src/libraries/System.Collections.NonGeneric/src/System/Collections/ReadOnlyCollectionBase.cs index 9947faf..3cf850e 100644 --- a/src/libraries/System.Collections.NonGeneric/src/System/Collections/ReadOnlyCollectionBase.cs +++ b/src/libraries/System.Collections.NonGeneric/src/System/Collections/ReadOnlyCollectionBase.cs @@ -18,15 +18,7 @@ namespace System.Collections { private ArrayList? _list; - protected ArrayList InnerList - { - get - { - if (_list == null) - _list = new ArrayList(); - return _list; - } - } + protected ArrayList InnerList => _list ??= new ArrayList(); public virtual int Count { diff --git a/src/libraries/System.Collections.NonGeneric/src/System/Collections/SortedList.cs b/src/libraries/System.Collections.NonGeneric/src/System/Collections/SortedList.cs index b1cae78..c047eac 100644 --- a/src/libraries/System.Collections.NonGeneric/src/System/Collections/SortedList.cs +++ b/src/libraries/System.Collections.NonGeneric/src/System/Collections/SortedList.cs @@ -426,11 +426,7 @@ namespace System.Collections // Remove and RemoveRange methods or through an enumerator). // Null is an invalid key value. // - public virtual IList GetKeyList() - { - if (keyList == null) keyList = new KeyList(this); - return keyList; - } + public virtual IList GetKeyList() => keyList ??= new KeyList(this); // Returns an IList representing the values of this sorted list. The // returned list is an alias for the values of this sorted list, so @@ -443,11 +439,7 @@ namespace System.Collections // elements (through the Remove, RemoveRange, Set and // SetRange methods or through an enumerator). // - public virtual IList GetValueList() - { - if (valueList == null) valueList = new ValueList(this); - return valueList; - } + public virtual IList GetValueList() => valueList ??= new ValueList(this); // Returns the value associated with the given key. If an entry with the // given key is not found, the returned value is null. diff --git a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/HybridDictionary.cs b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/HybridDictionary.cs index be3f840..86e27dc 100644 --- a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/HybridDictionary.cs +++ b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/HybridDictionary.cs @@ -114,17 +114,7 @@ namespace System.Collections.Specialized } } - private ListDictionary List - { - get - { - if (list == null) - { - list = new ListDictionary(caseInsensitive ? StringComparer.OrdinalIgnoreCase : null); - } - return list; - } - } + private ListDictionary List => list ??= new ListDictionary(caseInsensitive ? StringComparer.OrdinalIgnoreCase : null); private void ChangeOver() { @@ -325,10 +315,8 @@ namespace System.Collections.Specialized { return hashtable.GetEnumerator(); } - if (list == null) - { - list = new ListDictionary(caseInsensitive ? StringComparer.OrdinalIgnoreCase : null); - } + + list ??= new ListDictionary(caseInsensitive ? StringComparer.OrdinalIgnoreCase : null); return list.GetEnumerator(); } diff --git a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/NameObjectCollectionBase.cs b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/NameObjectCollectionBase.cs index 9c75a8e..82a136e 100644 --- a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/NameObjectCollectionBase.cs +++ b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/NameObjectCollectionBase.cs @@ -177,9 +177,9 @@ namespace System.Collections.Specialized _entriesTable.Add(name, entry); } else - { // null key -- special case -- hashtable doesn't like null keys - if (_nullKeyEntry == null) - _nullKeyEntry = entry; + { + // null key -- special case -- hashtable doesn't like null keys + _nullKeyEntry ??= entry; } // add entry to the list @@ -456,15 +456,7 @@ namespace System.Collections.Specialized /// Returns a instance containing /// all the keys in the instance. /// - public virtual KeysCollection Keys - { - get - { - if (_keys == null) - _keys = new KeysCollection(this); - return _keys; - } - } + public virtual KeysCollection Keys => _keys ??= new KeysCollection(this); // // Simple entry class to allow substitution of values and indexed access to keys diff --git a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/NameValueCollection.cs b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/NameValueCollection.cs index c567ede..5bb2723 100644 --- a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/NameValueCollection.cs +++ b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/NameValueCollection.cs @@ -387,14 +387,6 @@ namespace System.Collections.Specialized /// /// Gets all the keys in the . /// - public virtual string?[] AllKeys - { - get - { - if (_allKeys == null) - _allKeys = BaseGetAllKeys(); - return _allKeys; - } - } + public virtual string?[] AllKeys => _allKeys ??= BaseGetAllKeys(); } } diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/SortedDictionary.cs b/src/libraries/System.Collections/src/System/Collections/Generic/SortedDictionary.cs index ce5f346..8925d08 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/SortedDictionary.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/SortedDictionary.cs @@ -156,14 +156,7 @@ namespace System.Collections.Generic } } - public KeyCollection Keys - { - get - { - if (_keys == null) _keys = new KeyCollection(this); - return _keys; - } - } + public KeyCollection Keys => _keys ??= new KeyCollection(this); ICollection IDictionary.Keys { @@ -181,14 +174,7 @@ namespace System.Collections.Generic } } - public ValueCollection Values - { - get - { - if (_values == null) _values = new ValueCollection(this); - return _values; - } - } + public ValueCollection Values => _values ??= new ValueCollection(this); ICollection IDictionary.Values { @@ -899,14 +885,7 @@ namespace System.Collections.Generic public KeyValuePairComparer(IComparer? keyComparer) { - if (keyComparer == null) - { - this.keyComparer = Comparer.Default; - } - else - { - this.keyComparer = keyComparer; - } + this.keyComparer = keyComparer ?? Comparer.Default; } public override int Compare(KeyValuePair x, KeyValuePair y) diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/SortedList.cs b/src/libraries/System.Collections/src/System/Collections/Generic/SortedList.cs index da67926..3588586 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/SortedList.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/SortedList.cs @@ -359,19 +359,9 @@ namespace System.Collections.Generic } } - private KeyList GetKeyListHelper() - { - if (keyList == null) - keyList = new KeyList(this); - return keyList; - } + private KeyList GetKeyListHelper() => keyList ??= new KeyList(this); - private ValueList GetValueListHelper() - { - if (valueList == null) - valueList = new ValueList(this); - return valueList; - } + private ValueList GetValueListHelper() => valueList ??= new ValueList(this); bool ICollection>.IsReadOnly { diff --git a/src/libraries/System.Collections/src/System/Collections/StructuralComparisons.cs b/src/libraries/System.Collections/src/System/Collections/StructuralComparisons.cs index 792d495..988cc21 100644 --- a/src/libraries/System.Collections/src/System/Collections/StructuralComparisons.cs +++ b/src/libraries/System.Collections/src/System/Collections/StructuralComparisons.cs @@ -10,33 +10,9 @@ namespace System.Collections private static volatile IComparer? s_StructuralComparer; private static volatile IEqualityComparer? s_StructuralEqualityComparer; - public static IComparer StructuralComparer - { - get - { - IComparer? comparer = s_StructuralComparer; - if (comparer == null) - { - comparer = new StructuralComparer(); - s_StructuralComparer = comparer; - } - return comparer; - } - } + public static IComparer StructuralComparer => s_StructuralComparer ??= new StructuralComparer(); - public static IEqualityComparer StructuralEqualityComparer - { - get - { - IEqualityComparer? comparer = s_StructuralEqualityComparer; - if (comparer == null) - { - comparer = new StructuralEqualityComparer(); - s_StructuralEqualityComparer = comparer; - } - return comparer; - } - } + public static IEqualityComparer StructuralEqualityComparer => s_StructuralEqualityComparer ??= new StructuralEqualityComparer(); } internal sealed class StructuralEqualityComparer : IEqualityComparer diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CompareAttribute.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CompareAttribute.cs index 698b95b..a8f1458 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CompareAttribute.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CompareAttribute.cs @@ -46,10 +46,7 @@ namespace System.ComponentModel.DataAnnotations object? otherPropertyValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null); if (!Equals(value, otherPropertyValue)) { - if (OtherPropertyDisplayName == null) - { - OtherPropertyDisplayName = GetDisplayNameForProperty(otherPropertyInfo); - } + OtherPropertyDisplayName ??= GetDisplayNameForProperty(otherPropertyInfo); string[]? memberNames = validationContext.MemberName != null ? new[] { validationContext.MemberName } diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CustomValidationAttribute.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CustomValidationAttribute.cs index 73684d7..ffe523a 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CustomValidationAttribute.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CustomValidationAttribute.cs @@ -105,18 +105,7 @@ namespace System.ComponentModel.DataAnnotations /// /// Gets a unique identifier for this attribute. /// - public override object TypeId - { - get - { - if (_typeId is null) - { - _typeId = new Tuple(Method, ValidatorType); - } - - return _typeId; - } - } + public override object TypeId => _typeId ??= new Tuple(Method, ValidatorType); /// /// Gets the name of the method in to invoke to perform validation. diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttributeStore.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttributeStore.cs index d122453..93ac5eb 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttributeStore.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttributeStore.cs @@ -201,10 +201,7 @@ namespace System.ComponentModel.DataAnnotations { lock (_syncRoot) { - if (_propertyStoreItems == null) - { - _propertyStoreItems = CreatePropertyStoreItems(); - } + _propertyStoreItems ??= CreatePropertyStoreItems(); } } diff --git a/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/ExportBuilder.cs b/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/ExportBuilder.cs index 77b84b7..d12b928 100644 --- a/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/ExportBuilder.cs +++ b/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/ExportBuilder.cs @@ -40,10 +40,7 @@ namespace System.ComponentModel.Composition.Registration public ExportBuilder AddMetadata(string name, object value) { - if (_metadataItems == null) - { - _metadataItems = new List>(); - } + _metadataItems ??= new List>(); _metadataItems.Add(Tuple.Create(name, value)); return this; @@ -51,10 +48,7 @@ namespace System.ComponentModel.Composition.Registration public ExportBuilder AddMetadata(string name, Func itemFunc) { - if (_metadataItemFuncs == null) - { - _metadataItemFuncs = new List>>(); - } + _metadataItemFuncs ??= new List>>(); _metadataItemFuncs.Add(Tuple.Create(name, itemFunc)); return this; @@ -62,10 +56,7 @@ namespace System.ComponentModel.Composition.Registration internal void BuildAttributes(Type type, ref List attributes) { - if (attributes == null) - { - attributes = new List(); - } + attributes ??= new List(); if (_isInherited) { diff --git a/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/ImportBuilder.cs b/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/ImportBuilder.cs index 1b96998..d9bd476 100644 --- a/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/ImportBuilder.cs +++ b/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/ImportBuilder.cs @@ -94,10 +94,7 @@ namespace System.ComponentModel.Composition.Registration }; } - if (attributes == null) - { - attributes = new List(); - } + attributes ??= new List(); attributes.Add(importAttribute); } 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 8374779..5a07d74 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 @@ -212,10 +212,7 @@ namespace System.ComponentModel.Composition.Registration public PartBuilder AddMetadata(string name, object value) { - if (_metadataItems == null) - { - _metadataItems = new List>(); - } + _metadataItems ??= new List>(); _metadataItems.Add(Tuple.Create(name, value)); return this; @@ -223,10 +220,7 @@ namespace System.ComponentModel.Composition.Registration public PartBuilder AddMetadata(string name, Func itemFunc) { - if (_metadataItemFuncs == null) - { - _metadataItemFuncs = new List>>(); - } + _metadataItemFuncs ??= new List>>(); _metadataItemFuncs.Add(Tuple.Create(name, itemFunc)); return this; @@ -418,10 +412,7 @@ namespace System.ComponentModel.Composition.Registration private static void ConfigureConstructorAttributes(ConstructorInfo constructorInfo, ref List>> configuredMembers, Action configureConstuctorImports) { - if (configuredMembers == null) - { - configuredMembers = new List>>(); - } + configuredMembers ??= new List>>(); // Make its attribute configuredMembers.Add(Tuple.Create((object)constructorInfo, s_importingConstructorList)); @@ -536,10 +527,7 @@ namespace System.ComponentModel.Composition.Registration if (attributes != null) { - if (configuredMembers == null) - { - configuredMembers = new List>>(); - } + configuredMembers ??= new List>>(); configuredMembers.Add(Tuple.Create((object)declaredPi, attributes)); } 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 375d3fd..ace4c8b 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 @@ -126,10 +126,7 @@ namespace System.ComponentModel.Composition.Registration var lambdaExpression = (LambdaExpression)parameter; Delegate importDelegate = lambdaExpression.Compile(); - if (_importBuilders == null) - { - _importBuilders = new Dictionary>(); - } + _importBuilders ??= new Dictionary>(); _importBuilders.Add(parameterInfos[index], (Action)importDelegate); ++index; diff --git a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Collections/CollectionServices.cs b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Collections/CollectionServices.cs index b3f6096..339c3ae 100644 --- a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Collections/CollectionServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Collections/CollectionServices.cs @@ -131,10 +131,7 @@ namespace Microsoft.Internal.Collections private static List FastAppendToListAllowNulls(this List? source, T value) { - if (source == null) - { - source = new List(); - } + source ??= new List(); source.Add(value); return source; diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedPartCreationInfo.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedPartCreationInfo.cs index 4fe4123..d4de703 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedPartCreationInfo.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedPartCreationInfo.cs @@ -175,10 +175,7 @@ namespace System.ComponentModel.Composition.AttributedModel { get { - if (_partCreationPolicy == null) - { - _partCreationPolicy = _type.GetFirstAttribute() ?? PartCreationPolicyAttribute.Default; - } + _partCreationPolicy ??= _type.GetFirstAttribute() ?? PartCreationPolicyAttribute.Default; return _partCreationPolicy.CreationPolicy; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AtomicComposition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AtomicComposition.cs index 2ee4094..b747320 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AtomicComposition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AtomicComposition.cs @@ -93,10 +93,7 @@ namespace System.ComponentModel.Composition.Hosting Requires.NotNull(completeAction, nameof(completeAction)); - if (_completeActionList == null) - { - _completeActionList = new List(); - } + _completeActionList ??= new List(); _completeActionList.Add(completeAction); } @@ -108,10 +105,7 @@ namespace System.ComponentModel.Composition.Hosting Requires.NotNull(revertAction, nameof(revertAction)); - if (_revertActionList == null) - { - _revertActionList = new List(); - } + _revertActionList ??= new List(); _revertActionList.Add(revertAction); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.FactoryExport.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.FactoryExport.cs index 3b785e6..a2f6cbb 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.FactoryExport.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.FactoryExport.cs @@ -29,14 +29,8 @@ namespace System.ComponentModel.Composition.Hosting get { return _factoryExportDefinition; } } - protected override object GetExportedValueCore() - { - if (_factoryExportPartDefinition == null) - { - _factoryExportPartDefinition = new FactoryExportPartDefinition(this); - } - return _factoryExportPartDefinition; - } + protected override object GetExportedValueCore() => + _factoryExportPartDefinition ??= new FactoryExportPartDefinition(this); protected ComposablePartDefinition UnderlyingPartDefinition { 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 55c7455..5bbf40e 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 @@ -625,10 +625,7 @@ namespace System.ComponentModel.Composition.Hosting List? partList; ConditionalWeakTable>? gcRoots = _gcRoots; - if (gcRoots == null) - { - gcRoots = new ConditionalWeakTable>(); - } + gcRoots ??= new ConditionalWeakTable>(); if (!gcRoots.TryGetValue(exportedValue, out partList)) { diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartExportProvider.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartExportProvider.cs index de2d80b..d16314d 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartExportProvider.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartExportProvider.cs @@ -342,10 +342,7 @@ namespace System.ComponentModel.Composition.Hosting { if (parts.Remove(part)) { - if (partsToRemove == null) - { - partsToRemove = new List(); - } + partsToRemove ??= new List(); partsToRemove.Add(part); } } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionServices.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionServices.cs index c5c6b4b..8046b0b 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionServices.cs @@ -515,10 +515,7 @@ namespace System.ComponentModel.Composition.Hosting // Default value is ImportSource.Any if (attributedImport != null && attributedImport.Source != ImportSource.Any) { - if (metadata == null) - { - metadata = new Dictionary(); - } + metadata ??= new Dictionary(); metadata[CompositionConstants.ImportSourceMetadataName] = attributedImport.Source; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportProvider.GetExportOverrides.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportProvider.GetExportOverrides.cs index d7b452f..f527bef 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportProvider.GetExportOverrides.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportProvider.GetExportOverrides.cs @@ -780,10 +780,7 @@ namespace System.ComponentModel.Composition.Hosting contractName = AttributedModelServices.GetContractName(type); } - if (metadataViewType == null) - { - metadataViewType = ExportServices.DefaultMetadataViewType; - } + metadataViewType ??= ExportServices.DefaultMetadataViewType; if (!MetadataViewProvider.IsViewTypeValid(metadataViewType)) { diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportProvider.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportProvider.cs index 28ebe1f..30d0a2f 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportProvider.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportProvider.cs @@ -224,10 +224,7 @@ namespace System.ComponentModel.Composition.Hosting exports = null; } - if (exports == null) - { - exports = Array.Empty(); - } + exports ??= Array.Empty(); return checkResult; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportsChangeEventArgs.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportsChangeEventArgs.cs index 06ed592..0e0cbed 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportsChangeEventArgs.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportsChangeEventArgs.cs @@ -93,21 +93,12 @@ namespace System.ComponentModel.Composition.Hosting /// A of strings representing the contract names of /// the exports that have changed in the . /// - public IEnumerable ChangedContractNames - { - get - { - if (_changedContractNames == null) - { - _changedContractNames = AddedExports - .Concat(RemovedExports) - .Select(export => export.ContractName) - .Distinct() - .ToArray(); - } - return _changedContractNames; - } - } + public IEnumerable ChangedContractNames => + _changedContractNames ??= AddedExports + .Concat(RemovedExports) + .Select(export => export.ContractName) + .Distinct() + .ToArray(); /// /// Gets the atomicComposition, if any, that this change applies to. diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.DependenciesTraversal.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.DependenciesTraversal.cs index d0f2715..085cc7a 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.DependenciesTraversal.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.DependenciesTraversal.cs @@ -75,10 +75,7 @@ namespace System.ComponentModel.Composition.Hosting { if (import.IsImportDependentOnPart(candidateReachablePart, export, part.IsGeneric() != candidateReachablePart.IsGeneric())) { - if (reachablePartList == null) - { - reachablePartList = new List(); - } + reachablePartList ??= new List(); reachablePartList.Add(candidateReachablePart); } } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.DependentsTraversal.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.DependentsTraversal.cs index f14b829..9c456ec 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.DependentsTraversal.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.DependentsTraversal.cs @@ -82,10 +82,7 @@ namespace System.ComponentModel.Composition.Hosting { if (import.IsImportDependentOnPart(part, export, part.IsGeneric() != candidateReachablePart.IsGeneric())) { - if (reachablePartList == null) - { - reachablePartList = new List(); - } + reachablePartList ??= new List(); reachablePartList.Add(candidateReachablePart); } } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.PartManager.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.PartManager.cs index ad16329..64ba13f 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.PartManager.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.PartManager.cs @@ -65,11 +65,7 @@ namespace System.ComponentModel.Composition.Hosting return Enumerable.Empty(); } - if (_importedContractNames == null) - { - _importedContractNames = Part.ImportDefinitions.Select(import => import.ContractName ?? ImportDefinition.EmptyContractName).Distinct().ToArray(); - } - return _importedContractNames; + return _importedContractNames ??= Part.ImportDefinitions.Select(import => import.ContractName ?? ImportDefinition.EmptyContractName).Distinct().ToArray(); } public CompositionResult TrySetImport(ImportDefinition import, Export[] exports) @@ -106,11 +102,7 @@ namespace System.ComponentModel.Composition.Hosting SetSavedImport(import, savedExports, null)); } - if (_importCache == null) - { - _importCache = new Dictionary(); - } - + _importCache ??= new Dictionary(); _importCache[import] = exports; } @@ -154,10 +146,7 @@ namespace System.ComponentModel.Composition.Hosting { if (export is IDisposable disposableExport) { - if (disposableExports == null) - { - disposableExports = new List(); - } + disposableExports ??= new List(); disposableExports.Add(disposableExport); } } @@ -185,10 +174,7 @@ namespace System.ComponentModel.Composition.Hosting // Record the new collection if (disposableExports != null) { - if (_importedDisposableExports == null) - { - _importedDisposableExports = new Dictionary>(); - } + _importedDisposableExports ??= new Dictionary>(); _importedDisposableExports[import] = disposableExports; } } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ContractBasedImportDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ContractBasedImportDefinition.cs index e68780f..712f542 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ContractBasedImportDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ContractBasedImportDefinition.cs @@ -269,18 +269,8 @@ namespace System.ComponentModel.Composition.Primitives /// properties. /// /// - public override Expression> Constraint - { - get - { - if (_constraint == null) - { - _constraint = ConstraintServices.CreateConstraint(ContractName, RequiredTypeIdentity, RequiredMetadata, RequiredCreationPolicy); - } - - return _constraint; - } - } + public override Expression> Constraint => + _constraint ??= ConstraintServices.CreateConstraint(ContractName, RequiredTypeIdentity, RequiredMetadata, RequiredCreationPolicy); /// /// Executes an optimized version of the contraint given by the property diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ImportDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ImportDefinition.cs index 7a3be92..4b67121 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ImportDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ImportDefinition.cs @@ -263,10 +263,7 @@ namespace System.ComponentModel.Composition.Primitives { Requires.NotNull(exportDefinition, nameof(exportDefinition)); - if (_compiledConstraint == null) - { - _compiledConstraint = Constraint.Compile(); - } + _compiledConstraint ??= Constraint.Compile(); return _compiledConstraint.Invoke(exportDefinition); } 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 42c1e4c..c52e709c 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 @@ -88,10 +88,7 @@ namespace System.ComponentModel.Composition.ReflectionModel Thread.MemoryBarrier(); lock (_lock) { - if (_constructor == null) - { - _constructor = result; - } + _constructor ??= result; } } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePart.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePart.cs index e42af67..a7f7910 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePart.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePart.cs @@ -566,10 +566,7 @@ namespace System.ComponentModel.Composition.ReflectionModel } int exportIndex = reflectionExport.GetIndex(); - if (_exportsCache == null) - { - _exportsCache = new Dictionary(); - } + _exportsCache ??= new Dictionary(); if (!_exportsCache.TryGetValue(exportIndex, out ExportingMember? result)) { result = GetExportingMember(definition); diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePartDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePartDefinition.cs index 9ae0913..3fba07e 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePartDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePartDefinition.cs @@ -45,10 +45,7 @@ namespace System.ComponentModel.Composition.ReflectionModel ConstructorInfo? constructor = _creationInfo.GetConstructor(); lock (_lock) { - if (_constructor == null) - { - _constructor = constructor; - } + _constructor ??= constructor; } } @@ -64,10 +61,7 @@ namespace System.ComponentModel.Composition.ReflectionModel ExportDefinition[] exports = _creationInfo.GetExports().ToArray(); lock (_lock) { - if (_exports == null) - { - _exports = exports; - } + _exports ??= exports; } } return _exports; @@ -91,10 +85,7 @@ namespace System.ComponentModel.Composition.ReflectionModel ImportDefinition[] imports = _creationInfo.GetImports().ToArray(); lock (_lock) { - if (_imports == null) - { - _imports = imports; - } + _imports ??= imports; } } return _imports; @@ -110,10 +101,7 @@ namespace System.ComponentModel.Composition.ReflectionModel IDictionary metadata = _creationInfo.GetMetadata().AsReadOnly(); lock (_lock) { - if (_metadata == null) - { - _metadata = metadata; - } + _metadata ??= metadata; } } return _metadata; diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberExportDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberExportDefinition.cs index f2b73d7..58adef9 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberExportDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberExportDefinition.cs @@ -33,17 +33,7 @@ namespace System.ComponentModel.Composition.ReflectionModel get { return _member; } } - public override IDictionary Metadata - { - get - { - if (_metadata == null) - { - _metadata = _exportDefinition.Metadata.AsReadOnly(); - } - return _metadata; - } - } + public override IDictionary Metadata => _metadata ??= _exportDefinition.Metadata.AsReadOnly(); string ICompositionElement.DisplayName { diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/AttributeCollection.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/AttributeCollection.cs index 56e8178..07d7d9e 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/AttributeCollection.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/AttributeCollection.cs @@ -62,10 +62,7 @@ namespace System.ComponentModel { ArgumentNullException.ThrowIfNull(existing); - if (newAttributes == null) - { - newAttributes = Array.Empty(); - } + newAttributes ??= Array.Empty(); Attribute[] newArray = new Attribute[existing.Count + newAttributes.Length]; int actualCount = existing.Count; @@ -141,10 +138,7 @@ namespace System.ComponentModel // a relatively expensive call and we try to avoid it // since we rarely encounter derived attribute types // and this list is usually short. - if (_foundAttributeTypes == null) - { - _foundAttributeTypes = new AttributeEntry[FoundTypesLimit]; - } + _foundAttributeTypes ??= new AttributeEntry[FoundTypesLimit]; int ind = 0; @@ -252,10 +246,7 @@ namespace System.ComponentModel lock (s_internalSyncObject) { - if (s_defaultAttributes == null) - { - s_defaultAttributes = new Dictionary(); - } + s_defaultAttributes ??= new Dictionary(); // If we have already encountered this, use what's in the table. if (s_defaultAttributes.TryGetValue(attributeType, out Attribute? defaultAttribute)) diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/BaseNumberConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/BaseNumberConverter.cs index 3f3fc35..337ebe5 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/BaseNumberConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/BaseNumberConverter.cs @@ -69,10 +69,7 @@ namespace System.ComponentModel } else { - if (culture == null) - { - culture = CultureInfo.CurrentCulture; - } + culture ??= CultureInfo.CurrentCulture; NumberFormatInfo? formatInfo = (NumberFormatInfo?)culture.GetFormat(typeof(NumberFormatInfo)); return FromString(text, formatInfo); @@ -96,10 +93,7 @@ namespace System.ComponentModel if (destinationType == typeof(string) && value != null && TargetType.IsInstanceOfType(value)) { - if (culture == null) - { - culture = CultureInfo.CurrentCulture; - } + culture ??= CultureInfo.CurrentCulture; NumberFormatInfo? formatInfo = (NumberFormatInfo?)culture.GetFormat(typeof(NumberFormatInfo)); return ToString(value, formatInfo); diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/BindingList.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/BindingList.cs index b423375..e9bd9ad 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/BindingList.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/BindingList.cs @@ -313,13 +313,8 @@ namespace System.ComponentModel protected virtual object? AddNewCore() { // Allow event handler to supply the new item for us - object? newItem = FireAddingNew(); - // If event hander did not supply new item, create one ourselves - if (newItem == null) - { - newItem = Activator.CreateInstance(typeof(T)); - } + object? newItem = FireAddingNew() ?? Activator.CreateInstance(typeof(T)); // Add item to end of list. Note: If event handler returned an item not of type T, // the cast below will trigger an InvalidCastException. This is by design. @@ -457,10 +452,7 @@ namespace System.ComponentModel // Note: inpc may be null if item is null, so always check. if (item is INotifyPropertyChanged inpc) { - if (_propertyChangedEventHandler == null) - { - _propertyChangedEventHandler = new PropertyChangedEventHandler(Child_PropertyChanged); - } + _propertyChangedEventHandler ??= new PropertyChangedEventHandler(Child_PropertyChanged); inpc.PropertyChanged += _propertyChangedEventHandler; } } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ComponentResourceManager.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ComponentResourceManager.cs index 1a03f04..b35e0a1 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ComponentResourceManager.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ComponentResourceManager.cs @@ -68,10 +68,7 @@ namespace System.ComponentModel ArgumentNullException.ThrowIfNull(value); ArgumentNullException.ThrowIfNull(objectName); - if (culture == null) - { - culture = CultureInfo.CurrentUICulture; - } + culture ??= CultureInfo.CurrentUICulture; // The general case here will be to always use the same culture, so optimize for // that. The resourceSets hashtable uses culture as a key. It's value is diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/DateOnlyConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/DateOnlyConverter.cs index 1a118c4..8e7835b 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/DateOnlyConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/DateOnlyConverter.cs @@ -87,10 +87,7 @@ namespace System.ComponentModel return string.Empty; } - if (culture == null) - { - culture = CultureInfo.CurrentCulture; - } + culture ??= CultureInfo.CurrentCulture; DateTimeFormatInfo? formatInfo = (DateTimeFormatInfo?)culture.GetFormat(typeof(DateTimeFormatInfo)); diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/DateTimeConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/DateTimeConverter.cs index b5eb861..9eeffb9 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/DateTimeConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/DateTimeConverter.cs @@ -88,10 +88,7 @@ namespace System.ComponentModel return string.Empty; } - if (culture == null) - { - culture = CultureInfo.CurrentCulture; - } + culture ??= CultureInfo.CurrentCulture; DateTimeFormatInfo? formatInfo = (DateTimeFormatInfo?)culture.GetFormat(typeof(DateTimeFormatInfo)); diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/DateTimeOffsetConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/DateTimeOffsetConverter.cs index 2b0b4fc..7ac65b5 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/DateTimeOffsetConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/DateTimeOffsetConverter.cs @@ -90,10 +90,7 @@ namespace System.ComponentModel return string.Empty; } - if (culture == null) - { - culture = CultureInfo.CurrentCulture; - } + culture ??= CultureInfo.CurrentCulture; DateTimeFormatInfo? formatInfo; formatInfo = (DateTimeFormatInfo?)culture.GetFormat(typeof(DateTimeFormatInfo)); diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerOptionService.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerOptionService.cs index 62824c6..3188cf2 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerOptionService.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerOptionService.cs @@ -132,10 +132,7 @@ namespace System.ComponentModel.Design if (Parent != null) { parent!._properties = null; - if (Parent._children == null) - { - Parent._children = new ArrayList(1); - } + Parent._children ??= new ArrayList(1); Parent._children.Add(this); } } @@ -264,10 +261,7 @@ namespace System.ComponentModel.Design if (_children == null) { _service.PopulateOptionCollection(this); - if (_children == null) - { - _children = new ArrayList(1); - } + _children ??= new ArrayList(1); } } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesigntimeLicenseContext.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesigntimeLicenseContext.cs index e42bf8e..e5e4b48 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesigntimeLicenseContext.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesigntimeLicenseContext.cs @@ -61,15 +61,8 @@ namespace System.ComponentModel.Design { if (_savedLicenseKeys == null || _savedLicenseKeys[type.AssemblyQualifiedName!] == null) { - if (_savedLicenseKeys == null) - { - _savedLicenseKeys = new Hashtable(); - } - - if (resourceAssembly == null) - { - resourceAssembly = Assembly.GetEntryAssembly(); - } + _savedLicenseKeys ??= new Hashtable(); + resourceAssembly ??= Assembly.GetEntryAssembly(); if (resourceAssembly == null) { diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/ContextStack.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/ContextStack.cs index 26f2d87..dd62aa6 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/ContextStack.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/ContextStack.cs @@ -100,10 +100,7 @@ namespace System.ComponentModel.Design.Serialization { ArgumentNullException.ThrowIfNull(context); - if (_contextStack == null) - { - _contextStack = new List(); - } + _contextStack ??= new List(); _contextStack.Insert(0, context); } @@ -132,10 +129,7 @@ namespace System.ComponentModel.Design.Serialization { ArgumentNullException.ThrowIfNull(context); - if (_contextStack == null) - { - _contextStack = new List(); - } + _contextStack ??= new List(); _contextStack.Add(context); } } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/MemberRelationshipService.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/MemberRelationshipService.cs index 8f1d3ad..65c16f4 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/MemberRelationshipService.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/MemberRelationshipService.cs @@ -120,16 +120,8 @@ namespace System.ComponentModel.Design.Serialization Justification = "GetComponentName is only used to create a nice exception message, and has a fallback when null is returned.")] private static void ThrowRelationshipNotSupported(MemberRelationship source, MemberRelationship relationship) { - string? sourceName = TypeDescriptor.GetComponentName(source.Owner!); - string? relName = TypeDescriptor.GetComponentName(relationship.Owner!); - if (sourceName == null) - { - sourceName = source.Owner!.ToString(); - } - if (relName == null) - { - relName = relationship.Owner!.ToString(); - } + string? sourceName = TypeDescriptor.GetComponentName(source.Owner!) ?? source.Owner!.ToString(); + string? relName = TypeDescriptor.GetComponentName(relationship.Owner!) ?? relationship.Owner!.ToString(); throw new ArgumentException(SR.Format(SR.MemberRelationshipService_RelationshipNotSupported, sourceName, source.Member.Name, relName, relationship.Member.Name)); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicFileLicenseProvider.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicFileLicenseProvider.cs index e5ce14b..573e97e 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicFileLicenseProvider.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicFileLicenseProvider.cs @@ -76,10 +76,7 @@ namespace System.ComponentModel if (type.Assembly.Location.Length != 0) { - if (modulePath == null) - { - modulePath = type.Module.FullyQualifiedName; - } + modulePath ??= type.Module.FullyQualifiedName; string? moduleDir = Path.GetDirectoryName(modulePath); string licenseFile = moduleDir + "\\" + type.FullName + ".lic"; diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicenseManager.LicenseInteropHelper.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicenseManager.LicenseInteropHelper.cs index ddc88ef..31ad7d2 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicenseManager.LicenseInteropHelper.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicenseManager.LicenseInteropHelper.cs @@ -88,10 +88,7 @@ namespace System.ComponentModel out License? license, out string? licenseKey) { - if (context == null) - { - context = LicenseManager.CurrentContext; - } + context ??= LicenseManager.CurrentContext; return LicenseManager.ValidateInternalRecursive( context, diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicenseManager.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicenseManager.cs index 54beae0..45b85f0 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicenseManager.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicenseManager.cs @@ -42,10 +42,7 @@ namespace System.ComponentModel { lock (s_internalSyncObject) { - if (s_context == null) - { - s_context = new RuntimeLicenseContext(); - } + s_context ??= new RuntimeLicenseContext(); } } return s_context; diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MaskedTextProvider.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MaskedTextProvider.cs index 1de8d04..f82e2f2 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MaskedTextProvider.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MaskedTextProvider.cs @@ -237,10 +237,7 @@ namespace System.ComponentModel } } - if (culture == null) - { - culture = CultureInfo.CurrentCulture; - } + culture ??= CultureInfo.CurrentCulture; _flagState = default; @@ -264,10 +261,7 @@ namespace System.ComponentModel } // Last resort use invariant culture. - if (Culture == null) - { - Culture = CultureInfo.InvariantCulture; - } + Culture ??= CultureInfo.InvariantCulture; } else { diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/PropertyDescriptor.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/PropertyDescriptor.cs index 17611ac..c6a6111 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/PropertyDescriptor.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/PropertyDescriptor.cs @@ -79,10 +79,7 @@ namespace System.ComponentModel } } - if (_converter == null) - { - _converter = TypeDescriptor.GetConverter(PropertyType); - } + _converter ??= TypeDescriptor.GetConverter(PropertyType); } return _converter; } @@ -127,10 +124,7 @@ namespace System.ComponentModel ArgumentNullException.ThrowIfNull(component); ArgumentNullException.ThrowIfNull(handler); - if (_valueChangedHandlers == null) - { - _valueChangedHandlers = new Dictionary(); - } + _valueChangedHandlers ??= new Dictionary(); EventHandler? h = _valueChangedHandlers.GetValueOrDefault(component, defaultValue: null); _valueChangedHandlers[component] = (EventHandler?)Delegate.Combine(h, handler); diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectPropertyDescriptor.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectPropertyDescriptor.cs index 100beeb..9ce9f2a 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectPropertyDescriptor.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectPropertyDescriptor.cs @@ -910,10 +910,7 @@ namespace System.ComponentModel name = site.Name; } - if (name == null) - { - name = component.GetType().FullName; - } + name ??= component.GetType().FullName; if (t is TargetInvocationException) { diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.ReflectedTypeData.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.ReflectedTypeData.cs index 05241af..310c8e3 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.ReflectedTypeData.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.ReflectedTypeData.cs @@ -199,10 +199,7 @@ namespace System.ComponentModel // If we got here, we return our type-based converter. if (_converter == null) { - if (typeAttr == null) - { - typeAttr = (TypeConverterAttribute?)TypeDescriptor.GetAttributes(_type)[typeof(TypeConverterAttribute)]; - } + typeAttr ??= (TypeConverterAttribute?)TypeDescriptor.GetAttributes(_type)[typeof(TypeConverterAttribute)]; if (typeAttr != null) { @@ -509,10 +506,7 @@ namespace System.ComponentModel t = _type.Assembly.GetType(typeName); } - if (t == null) - { - t = Type.GetType(typeName); - } + t ??= Type.GetType(typeName); if (t == null && commaIndex != -1) { diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.cs index 00f8802..5f17e95 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.cs @@ -578,10 +578,7 @@ namespace System.ComponentModel { PropertyDescriptor[] propertyArray = ReflectGetExtendedProperties(extenders[idx]); - if (propertyList == null) - { - propertyList = new List(propertyArray.Length * extenders.Length); - } + propertyList ??= new List(propertyArray.Length * extenders.Length); for (int propIdx = 0; propIdx < propertyArray.Length; propIdx++) { @@ -916,10 +913,7 @@ namespace System.ComponentModel if (td == null && createIfNeeded) { td = new ReflectedTypeData(type); - if (_typeData == null) - { - _typeData = new Hashtable(); - } + _typeData ??= new Hashtable(); _typeData[type] = td; } } @@ -1423,10 +1417,7 @@ namespace System.ComponentModel // Interfaces do not derive from object, so we // must handle the case of no hash entry here. // - if (hashEntry == null) - { - hashEntry = table[typeof(object)]; - } + hashEntry ??= table[typeof(object)]; // If the entry is a type, create an instance of it and then // replace the entry. This way we only need to create once. diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TimeOnlyConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TimeOnlyConverter.cs index 050bb59..1cc9bf8 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TimeOnlyConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TimeOnlyConverter.cs @@ -87,14 +87,11 @@ namespace System.ComponentModel return string.Empty; } - if (culture == null) - { - culture = CultureInfo.CurrentCulture; - } + culture ??= CultureInfo.CurrentCulture; - DateTimeFormatInfo? formatInfo = (DateTimeFormatInfo?)culture.GetFormat(typeof(DateTimeFormatInfo)); + DateTimeFormatInfo formatInfo = (DateTimeFormatInfo)culture.GetFormat(typeof(DateTimeFormatInfo))!; - return timeOnly.ToString(formatInfo!.ShortTimePattern, CultureInfo.CurrentCulture); + return timeOnly.ToString(formatInfo.ShortTimePattern, CultureInfo.CurrentCulture); } if (destinationType == typeof(InstanceDescriptor) && value is TimeOnly time) diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeConverter.cs index b22befb..a91aac7 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeConverter.cs @@ -426,10 +426,7 @@ namespace System.ComponentModel /// public StandardValuesCollection(ICollection? values) { - if (values == null) - { - values = Array.Empty(); - } + values ??= Array.Empty(); if (values is Array a) { diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptor.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptor.cs index 4ac5a2f..9d965f4 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptor.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptor.cs @@ -2255,10 +2255,7 @@ namespace System.ComponentModel TypeDescriptionNode? node = (TypeDescriptionNode?)de.Value; while (node != null && !(node.Provider is ReflectTypeDescriptionProvider)) { - if (refreshedTypes == null) - { - refreshedTypes = new Hashtable(); - } + refreshedTypes ??= new Hashtable(); refreshedTypes[nodeType] = nodeType; node = node.Next; } @@ -2271,10 +2268,7 @@ namespace System.ComponentModel foreach (Type populatedType in populatedTypes) { provider.Refresh(populatedType); - if (refreshedTypes == null) - { - refreshedTypes = new Hashtable(); - } + refreshedTypes ??= new Hashtable(); refreshedTypes[populatedType] = populatedType; } } @@ -2974,11 +2968,9 @@ namespace System.ComponentModel [RequiresUnreferencedCode(PropertyDescriptor.PropertyDescriptorPropertyTypeMessage + " " + AttributeCollection.FilterRequiresUnreferencedCodeMessage)] PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[]? attributes) { - PropertyDescriptorCollection properties = _primary.GetProperties(attributes); - if (properties == null) - { - properties = _secondary.GetProperties(attributes); - } + PropertyDescriptorCollection properties = + _primary.GetProperties(attributes) ?? + _secondary.GetProperties(attributes); Debug.Assert(properties != null, "Someone should have handled this"); return properties; diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/WeakHashtable.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/WeakHashtable.cs index 1d8da04..35fc1c8 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/WeakHashtable.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/WeakHashtable.cs @@ -79,11 +79,7 @@ namespace System.ComponentModel { if (o is WeakReference wr && !wr.IsAlive) { - if (cleanupList == null) - { - cleanupList = new List(); - } - + cleanupList ??= new List(); cleanupList.Add(wr); } } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/ColorConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/ColorConverter.cs index 9a6117b..1e9f3a8 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/ColorConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/ColorConverter.cs @@ -69,10 +69,7 @@ namespace System.Drawing return "'" + c.Name + "'"; } - if (culture == null) - { - culture = CultureInfo.CurrentCulture; - } + culture ??= CultureInfo.CurrentCulture; string sep = culture.TextInfo.ListSeparator + " "; TypeConverter intConverter = TypeDescriptor.GetConverterTrimUnsafe(typeof(int)); diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/PointConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/PointConverter.cs index 0eee25d..c4f6f41 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/PointConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/PointConverter.cs @@ -33,10 +33,7 @@ namespace System.Drawing } // Parse 2 integer values. - if (culture == null) - { - culture = CultureInfo.CurrentCulture; - } + culture ??= CultureInfo.CurrentCulture; char sep = culture.TextInfo.ListSeparator[0]; string[] tokens = text.Split(sep); @@ -69,10 +66,7 @@ namespace System.Drawing { if (destinationType == typeof(string)) { - if (culture == null) - { - culture = CultureInfo.CurrentCulture; - } + culture ??= CultureInfo.CurrentCulture; string sep = culture.TextInfo.ListSeparator + " "; TypeConverter intConverter = TypeDescriptor.GetConverterTrimUnsafe(typeof(int)); diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/RectangleConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/RectangleConverter.cs index 93d6ae1..da85f29 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/RectangleConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/RectangleConverter.cs @@ -33,10 +33,7 @@ namespace System.Drawing } // Parse 4 integer values. - if (culture == null) - { - culture = CultureInfo.CurrentCulture; - } + culture ??= CultureInfo.CurrentCulture; char sep = culture.TextInfo.ListSeparator[0]; string[] tokens = text.Split(sep); @@ -67,10 +64,7 @@ namespace System.Drawing { if (destinationType == typeof(string)) { - if (culture == null) - { - culture = CultureInfo.CurrentCulture; - } + culture ??= CultureInfo.CurrentCulture; string sep = culture.TextInfo.ListSeparator + " "; TypeConverter intConverter = TypeDescriptor.GetConverterTrimUnsafe(typeof(int)); diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/SizeConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/SizeConverter.cs index 6bb0d10..a718bc8 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/SizeConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/SizeConverter.cs @@ -33,10 +33,7 @@ namespace System.Drawing } // Parse 2 integer values. - if (culture == null) - { - culture = CultureInfo.CurrentCulture; - } + culture ??= CultureInfo.CurrentCulture; char sep = culture.TextInfo.ListSeparator[0]; string[] tokens = text.Split(sep); @@ -67,10 +64,7 @@ namespace System.Drawing { if (destinationType == typeof(string)) { - if (culture == null) - { - culture = CultureInfo.CurrentCulture; - } + culture ??= CultureInfo.CurrentCulture; string sep = culture.TextInfo.ListSeparator + " "; TypeConverter intConverter = TypeDescriptor.GetConverterTrimUnsafe(typeof(int)); diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/SizeFConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/SizeFConverter.cs index 3e3cdb3..c825178 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/SizeFConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/SizeFConverter.cs @@ -33,10 +33,7 @@ namespace System.Drawing } // Parse 2 integer values. - if (culture == null) - { - culture = CultureInfo.CurrentCulture; - } + culture ??= CultureInfo.CurrentCulture; char sep = culture.TextInfo.ListSeparator[0]; string[] tokens = text.Split(sep); @@ -66,10 +63,7 @@ namespace System.Drawing { if (destinationType == typeof(string)) { - if (culture == null) - { - culture = CultureInfo.CurrentCulture; - } + culture ??= CultureInfo.CurrentCulture; string sep = culture.TextInfo.ListSeparator + " "; TypeConverter floatConverter = TypeDescriptor.GetConverterTrimUnsafe(typeof(float)); 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 abd5238..3ff26ac 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 @@ -102,10 +102,8 @@ namespace System.Composition.Convention { throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(name)), nameof(name)); } - if (_metadataItems == null) - { - _metadataItems = new List>(); - } + + _metadataItems ??= new List>(); _metadataItems.Add(Tuple.Create(name, value)); return this; } @@ -132,20 +130,14 @@ namespace System.Composition.Convention throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(name)), nameof(name)); } - if (_metadataItemFuncs == null) - { - _metadataItemFuncs = new List>>(); - } + _metadataItemFuncs ??= new List>>(); _metadataItemFuncs.Add(Tuple.Create(name, getValueFromPartType)); return this; } internal void BuildAttributes(Type type, ref List attributes) { - if (attributes == null) - { - attributes = new List(); - } + attributes ??= new List(); var contractName = (_getContractNameFromPartType != null) ? _getContractNameFromPartType(type) : _contractName; attributes.Add(new ExportAttribute(contractName, _contractType)); 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 804d9e5..3b9143b 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 @@ -107,10 +107,8 @@ namespace System.Composition.Convention { throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(name)), nameof(name)); } - if (_metadataConstraintItems == null) - { - _metadataConstraintItems = new List>(); - } + + _metadataConstraintItems ??= new List>(); _metadataConstraintItems.Add(Tuple.Create(name, value)); return this; } @@ -137,10 +135,7 @@ namespace System.Composition.Convention throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(name)), nameof(name)); } - if (_metadataConstraintItemFuncs == null) - { - _metadataConstraintItemFuncs = new List>>(); - } + _metadataConstraintItemFuncs ??= new List>>(); _metadataConstraintItemFuncs.Add(Tuple.Create(name, getConstraintValueFromPartType)); return this; } @@ -164,12 +159,9 @@ namespace System.Composition.Convention { importAttribute = new ImportManyAttribute(contractName); } - if (attributes == null) - { - attributes = new List(); - } - attributes.Add(importAttribute); + attributes ??= new List(); + attributes.Add(importAttribute); //Add metadata attributes from direct specification if (_metadataConstraintItems != null) 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 cd30e94..6cadec4 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 @@ -433,10 +433,7 @@ namespace System.Composition.Convention throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(name)), nameof(name)); } - if (_metadataItems == null) - { - _metadataItems = new List>(); - } + _metadataItems ??= new List>(); _metadataItems.Add(Tuple.Create(name, value)); return this; } @@ -463,10 +460,7 @@ namespace System.Composition.Convention throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(name)), nameof(name)); } - if (_metadataItemFuncs == null) - { - _metadataItemFuncs = new List>>(); - } + _metadataItemFuncs ??= new List>>(); _metadataItemFuncs.Add(Tuple.Create(name, getValueFromPartType)); return this; } @@ -651,10 +645,7 @@ namespace System.Composition.Convention private static void ConfigureConstructorAttributes(ConstructorInfo constructorInfo, ref List>> configuredMembers, Action configureConstuctorImports) { - if (configuredMembers == null) - { - configuredMembers = new List>>(); - } + configuredMembers ??= new List>>(); // Make its attribute configuredMembers.Add(Tuple.Create((object)constructorInfo, s_importingConstructorList)); @@ -753,10 +744,8 @@ namespace System.Composition.Convention // Run through the import specifications see if any match foreach (Tuple, Action> importSpecification in _propertyImports) { - if (underlyingPi == null) - { - underlyingPi = pi.DeclaringType.GetRuntimeProperty(pi.Name); - } + underlyingPi ??= pi.DeclaringType.GetRuntimeProperty(pi.Name); + if (importSpecification.Item1 != null && importSpecification.Item1(underlyingPi)) { var importBuilder = new ImportConventionBuilder(); @@ -792,10 +781,7 @@ namespace System.Composition.Convention // Run through the export specifications see if any match foreach (Tuple, Action, Type> exportSpecification in _propertyExports) { - if (underlyingPi == null) - { - underlyingPi = pi.DeclaringType.GetRuntimeProperty(pi.Name); - } + underlyingPi ??= pi.DeclaringType.GetRuntimeProperty(pi.Name); if (exportSpecification.Item1 != null && exportSpecification.Item1(underlyingPi)) { @@ -828,10 +814,7 @@ namespace System.Composition.Convention if (attributes != null) { - if (configuredMembers == null) - { - configuredMembers = new List>>(); - } + configuredMembers ??= new List>>(); configuredMembers.Add(Tuple.Create((object)pi, attributes)); } 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 b60eb8a..73d2c5b 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 @@ -187,10 +187,7 @@ namespace System.Composition.Convention { var lambdaExpression = (LambdaExpression)parameter; Delegate importDelegate = lambdaExpression.Compile(); - if (_importBuilders == null) - { - _importBuilders = new Dictionary>(); - } + _importBuilders ??= new Dictionary>(); _importBuilders.Add(parameterInfos[index], (Action)importDelegate); ++index; } 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 c1fc011..5e446b3 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 @@ -59,8 +59,7 @@ namespace System.Composition.Hosting.Core throw new ArgumentNullException(nameof(action)); } - if (_nonPrerequisiteActions == null) - _nonPrerequisiteActions = new List(); + _nonPrerequisiteActions ??= new List(); _nonPrerequisiteActions.Add(action); } @@ -77,8 +76,7 @@ namespace System.Composition.Hosting.Core throw new ArgumentNullException(nameof(action)); } - if (_postCompositionActions == null) - _postCompositionActions = new List(); + _postCompositionActions ??= new List(); _postCompositionActions.Add(action); } diff --git a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Util/SmallSparseInitonlyArray.cs b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Util/SmallSparseInitonlyArray.cs index bd026a9..86d266d 100644 --- a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Util/SmallSparseInitonlyArray.cs +++ b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Util/SmallSparseInitonlyArray.cs @@ -19,8 +19,7 @@ namespace System.Composition.Hosting.Util public void Add(int index, object value) { - if (_elements == null) - _elements = new Element[ElementsCapacity]; + _elements ??= new Element[ElementsCapacity]; var newElement = new Element { Index = index, Value = value }; @@ -53,8 +52,7 @@ namespace System.Composition.Hosting.Util } } - if (_overflow == null) - _overflow = new SmallSparseInitonlyArray(); + _overflow ??= new SmallSparseInitonlyArray(); _overflow.Add(index, value); } diff --git a/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Discovery/DiscoveredPart.cs b/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Discovery/DiscoveredPart.cs index 48e8d77..6fc4def 100644 --- a/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Discovery/DiscoveredPart.cs +++ b/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Discovery/DiscoveredPart.cs @@ -103,9 +103,7 @@ namespace System.Composition.TypedParts.Discovery _constructor = GetConstructorInfoFromGenericType(_partType); } - if (_constructor == null) - _constructor = _partType.DeclaredConstructors - .FirstOrDefault(ci => ci.IsPublic && !(ci.IsStatic || ci.GetParameters().Any())); + _constructor ??= _partType.DeclaredConstructors.FirstOrDefault(ci => ci.IsPublic && !(ci.IsStatic || ci.GetParameters().Any())); if (_constructor == null) { 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 25af4ba..9840347 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ApplicationSettingsBase.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ApplicationSettingsBase.cs @@ -557,10 +557,7 @@ namespace System.Configuration Type type = GetType(); - if (_context == null) - { - _context = new SettingsContext(); - } + _context ??= new SettingsContext(); _context["GroupName"] = type.FullName; _context["SettingsKey"] = SettingsKey; _context["SettingsClassType"] = type; @@ -568,15 +565,8 @@ namespace System.Configuration PropertyInfo[] properties = SettingsFilter(type.GetProperties(BindingFlags.Instance | BindingFlags.Public)); _classAttributes = type.GetCustomAttributes(false); - if (_settings == null) - { - _settings = new SettingsPropertyCollection(); - } - - if (_providers == null) - { - _providers = new SettingsProviderCollection(); - } + _settings ??= new SettingsPropertyCollection(); + _providers ??= new SettingsProviderCollection(); for (int i = 0; i < properties.Length; i++) { diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/BaseConfigurationRecord.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/BaseConfigurationRecord.cs index 71f04c1..2874181 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/BaseConfigurationRecord.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/BaseConfigurationRecord.cs @@ -367,7 +367,7 @@ namespace System.Configuration // remove the LocationSectionRecord from the list _parent._locationSections.RemoveAt(i); - if (locationSubPathInputs == null) locationSubPathInputs = new ArrayList(); + locationSubPathInputs ??= new ArrayList(); locationSubPathInputs.Add(locationSectionRecord); } @@ -408,8 +408,7 @@ namespace System.Configuration // First add all indirect inputs per configKey to a local list. // We will sort all lists after the while loop. - if (indirectLocationInputs == null) - indirectLocationInputs = new Dictionary>(1); + indirectLocationInputs ??= new Dictionary>(1); string configKey = locationSectionRecord.SectionXmlInfo.ConfigKey; @@ -655,7 +654,7 @@ namespace System.Configuration else { // Remove the entire section record - if (removes == null) removes = new List(); + removes ??= new List(); removes.Add(sectionRecord); } @@ -1062,7 +1061,7 @@ namespace System.Configuration // Cache the results. if (cacheResults) { - if (sectionRecord == null) sectionRecord = EnsureSectionRecord(configKey, true); + sectionRecord ??= EnsureSectionRecord(configKey, true); sectionRecord.Result = tmpResult; if (getRuntimeObject) sectionRecord.ResultRuntimeObject = tmpResultRuntimeObject; @@ -1740,10 +1739,7 @@ namespace System.Configuration } } - if (factoryRecord.Factory == null) - { - factoryRecord.Factory = rootFactoryRecord.Factory; - } + factoryRecord.Factory ??= rootFactoryRecord.Factory; isRootDeclaredHere = ReferenceEquals(this, rootConfigRecord); @@ -2917,8 +2913,7 @@ namespace System.Configuration } // Check if the definition is allowed - if (factoryRecord == null) - factoryRecord = FindFactoryRecord(locationSectionRecord.ConfigKey, true); + factoryRecord ??= FindFactoryRecord(locationSectionRecord.ConfigKey, true); if (factoryRecord.HasErrors) continue; @@ -3143,8 +3138,14 @@ namespace System.Configuration lock (this) { - if (_sectionRecords == null) _sectionRecords = new Hashtable(); - else sectionRecord = GetSectionRecord(configKey, permitErrors); + if (_sectionRecords == null) + { + _sectionRecords = new Hashtable(); + } + else + { + sectionRecord = GetSectionRecord(configKey, permitErrors); + } if (sectionRecord == null) { @@ -3252,10 +3253,7 @@ namespace System.Configuration if (_flags[SupportsChangeNotifications]) { - if (ConfigStreamInfo.CallbackDelegate == null) - ConfigStreamInfo.CallbackDelegate = OnStreamChanged; - - callbackDelegate = ConfigStreamInfo.CallbackDelegate; + callbackDelegate = ConfigStreamInfo.CallbackDelegate ??= OnStreamChanged; } } @@ -3413,7 +3411,7 @@ namespace System.Configuration // Requires the hierarchy lock to be acquired (hl) internal void HlAddChild(string configName, BaseConfigurationRecord child) { - if (_children == null) _children = new Hashtable(StringComparer.OrdinalIgnoreCase); + _children ??= new Hashtable(StringComparer.OrdinalIgnoreCase); _children.Add(configName, child); } @@ -3654,7 +3652,7 @@ namespace System.Configuration // (e.g. if we're in machine.config) if (!_parent.IsRootConfig) return; - if (factoryList == null) factoryList = EnsureFactories(); + factoryList ??= EnsureFactories(); // Look to see if we already have a factory for "configProtectedData" FactoryRecord factoryRecord = (FactoryRecord)factoryList[ReservedSectionProtectedConfiguration]; diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientConfigPaths.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientConfigPaths.cs index a2a818b..7f6edad 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientConfigPaths.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientConfigPaths.cs @@ -343,7 +343,7 @@ namespace System.Configuration if (string.IsNullOrEmpty(ProductName) && (mainType != null)) ProductName = mainType.Name.Trim(); // give up, return empty string - if (ProductName == null) ProductName = string.Empty; + ProductName ??= string.Empty; } if (string.IsNullOrEmpty(_companyName)) diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientSettingsStore.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientSettingsStore.cs index 13e4456..06a7887 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientSettingsStore.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientSettingsStore.cs @@ -236,17 +236,8 @@ namespace System.Configuration } } - internal static IInternalConfigConfigurationFactory ConfigFactory - { - get - { - if (s_configFactory == null) - { - s_configFactory = TypeUtil.CreateInstance(InternalConfigConfigurationFactoryTypeName); - } - return s_configFactory; - } - } + internal static IInternalConfigConfigurationFactory ConfigFactory => + s_configFactory ??= TypeUtil.CreateInstance(InternalConfigConfigurationFactoryTypeName); private ClientSettingsConfigurationHost() { } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElement.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElement.cs index c1a2aad..53bdfed 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElement.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElement.cs @@ -262,11 +262,8 @@ namespace System.Configuration if (source._lockedAttributesList != null) { // Mark entry as from the parent - read only - if (_lockedAttributesList == null) - { - _lockedAttributesList = new ConfigurationLockCollection(this, - ConfigurationLockCollectionType.LockedAttributes); - } + _lockedAttributesList ??= new ConfigurationLockCollection(this, + ConfigurationLockCollectionType.LockedAttributes); foreach (string key in source._lockedAttributesList) _lockedAttributesList.Add(key, ConfigurationValueFlags.Inherited); @@ -274,12 +271,9 @@ namespace System.Configuration if (source._lockedAllExceptAttributesList != null) { - if (_lockedAllExceptAttributesList == null) - { - _lockedAllExceptAttributesList = new ConfigurationLockCollection(this, - ConfigurationLockCollectionType.LockedExceptionList, string.Empty, - source._lockedAllExceptAttributesList); - } + _lockedAllExceptAttributesList ??= new ConfigurationLockCollection(this, + ConfigurationLockCollectionType.LockedExceptionList, string.Empty, + source._lockedAllExceptAttributesList); StringCollection intersectionCollection = IntersectLockCollections(_lockedAllExceptAttributesList, source._lockedAllExceptAttributesList); @@ -291,11 +285,8 @@ namespace System.Configuration if (source._lockedElementsList != null) { - if (_lockedElementsList == null) - { - _lockedElementsList = new ConfigurationLockCollection(this, - ConfigurationLockCollectionType.LockedElements); - } + _lockedElementsList ??= new ConfigurationLockCollection(this, + ConfigurationLockCollectionType.LockedElements); ConfigurationElementCollection collection = null; if (Properties.DefaultCollectionProperty != null) @@ -307,8 +298,7 @@ namespace System.Configuration // Default collections don't know their tag name collection.InternalElementTagName = source.ElementTagName; //point to the same instance of the collection from parent - if (collection._lockedElementsList == null) - collection._lockedElementsList = _lockedElementsList; + collection._lockedElementsList ??= _lockedElementsList; } } @@ -586,8 +576,7 @@ namespace System.Configuration { collection.InternalElementTagName = parentElement.ElementTagName; // Default collections don't know there tag name - if (collection._lockedElementsList == null) - collection._lockedElementsList = _lockedElementsList; + collection._lockedElementsList ??= _lockedElementsList; } } @@ -801,7 +790,7 @@ namespace System.Configuration // NOTE[ Thread Safety ]: Non-guarded access to static variable - since this code is called only from CreatePropertyBagFromType // which in turn is done onle once per type and is guarded by the s_propertyBag.SyncRoot then this call is thread safe as well - if (s_perTypeValidators == null) s_perTypeValidators = new Dictionary(); + s_perTypeValidators ??= new Dictionary(); // A type validator should be cached only once. If it isn't then attribute parsing is done more then once which should be avoided Debug.Assert(!s_perTypeValidators.ContainsKey(type)); @@ -1593,11 +1582,9 @@ namespace System.Configuration if (lockedAttributesList != null) { - if (_lockedAttributesList == null) - { - _lockedAttributesList = new ConfigurationLockCollection(this, - ConfigurationLockCollectionType.LockedAttributes); - } + _lockedAttributesList ??= new ConfigurationLockCollection(this, + ConfigurationLockCollectionType.LockedAttributes); + foreach ( string key in ParseLockedAttributes(lockedAttributesList, ConfigurationLockCollectionType.LockedAttributes)) @@ -1632,11 +1619,8 @@ namespace System.Configuration if (lockedElementList != null) { - if (_lockedElementsList == null) - { - _lockedElementsList = new ConfigurationLockCollection(this, - ConfigurationLockCollectionType.LockedElements); - } + _lockedElementsList ??= new ConfigurationLockCollection(this, + ConfigurationLockCollectionType.LockedElements); ConfigurationLockCollection localLockedElementList = ParseLockedAttributes(lockedElementList, ConfigurationLockCollectionType.LockedElements); @@ -1704,11 +1688,9 @@ namespace System.Configuration if (defaultCollectionProperty != null) { defaultCollection = (ConfigurationElement)this[defaultCollectionProperty]; - if (_lockedElementsList == null) - { - _lockedElementsList = new ConfigurationLockCollection(this, - ConfigurationLockCollectionType.LockedElements); - } + _lockedElementsList ??= new ConfigurationLockCollection(this, + ConfigurationLockCollectionType.LockedElements); + defaultCollection._lockedElementsList = _lockedElementsList; if (_lockedAllExceptElementsList == null) { diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationManagerInternalFactory.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationManagerInternalFactory.cs index b6b1cf4..7301fc5 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationManagerInternalFactory.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationManagerInternalFactory.cs @@ -9,17 +9,6 @@ namespace System.Configuration { private static volatile IConfigurationManagerInternal s_instance; - internal static IConfigurationManagerInternal Instance - { - get - { - if (s_instance == null) - { - s_instance = new ConfigurationManagerInternal(); - } - - return s_instance; - } - } + internal static IConfigurationManagerInternal Instance => s_instance ??= new ConfigurationManagerInternal(); } } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/DictionarySectionHandler.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/DictionarySectionHandler.cs index b2ff1b7..a20e964 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/DictionarySectionHandler.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/DictionarySectionHandler.cs @@ -49,17 +49,12 @@ namespace System.Configuration { HandlerBase.CheckForChildNodes(child); string key = HandlerBase.RemoveRequiredAttribute(child, KeyAttributeName); - string value; - if (ValueRequired) - value = HandlerBase.RemoveRequiredAttribute(child, ValueAttributeName); - else - value = HandlerBase.RemoveAttribute(child, ValueAttributeName); + string value = ValueRequired ? + HandlerBase.RemoveRequiredAttribute(child, ValueAttributeName) : + HandlerBase.RemoveAttribute(child, ValueAttributeName); HandlerBase.CheckForUnrecognizedAttributes(child); - if (value == null) - value = ""; - - res[key] = value; + res[key] = value ?? ""; } else if (child.Name == "remove") { diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ErrorsHelper.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ErrorsHelper.cs index 2ca9406..3d90f19 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ErrorsHelper.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ErrorsHelper.cs @@ -23,7 +23,7 @@ namespace System.Configuration Debug.Assert(e != null, "e != null"); // Create on demand - if (errors == null) errors = new List(); + errors ??= new List(); ConfigurationErrorsException ce = e as ConfigurationErrorsException; if (ce == null) errors.Add(e); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/LocalFileSettingsProvider.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/LocalFileSettingsProvider.cs index 09081d9..828a359 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/LocalFileSettingsProvider.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/LocalFileSettingsProvider.cs @@ -36,18 +36,7 @@ namespace System.Configuration } } - private XmlEscaper Escaper - { - get - { - if (_escaper == null) - { - _escaper = new XmlEscaper(); - } - - return _escaper; - } - } + private XmlEscaper Escaper => _escaper ??= new XmlEscaper(); /// /// We maintain a single instance of the ClientSettingsStore per instance of provider. @@ -477,10 +466,7 @@ namespace System.Configuration } } - if (serializedValue == null) - { - serializedValue = string.Empty; - } + serializedValue ??= string.Empty; // We need to escape string serialized values if (setting.SerializeAs == SettingsSerializeAs.String) diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/MgmtConfigurationRecord.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/MgmtConfigurationRecord.cs index 36c30ce..bb84b6f 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/MgmtConfigurationRecord.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/MgmtConfigurationRecord.cs @@ -299,7 +299,7 @@ namespace System.Configuration // Record all location tags in the config file, even if they are empty. protected override void AddLocation(string locationSubPath) { - if (_locationTags == null) _locationTags = new Hashtable(StringComparer.OrdinalIgnoreCase); + _locationTags ??= new Hashtable(StringComparer.OrdinalIgnoreCase); _locationTags[locationSubPath] = locationSubPath; } @@ -1710,7 +1710,7 @@ namespace System.Configuration if (addToConfigSourceUpdates) { - if (configSourceUpdates == null) configSourceUpdates = new ArrayList(); + configSourceUpdates ??= new ArrayList(); configSourceUpdates.Add(definitionUpdate); } } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProviderSettings.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProviderSettings.cs index 74b7449..74b4520 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProviderSettings.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProviderSettings.cs @@ -113,8 +113,7 @@ namespace System.Configuration if ((prop.Name != "name") && (prop.Name != "type")) { if (_propertyNameCollection.Get(prop.Name) != null) continue; - if (removeList == null) - removeList = new ArrayList(); + removeList ??= new ArrayList(); if ((Values.GetConfigValue(prop.Name).ValueFlags & ConfigurationValueFlags.Locked) != 0) continue; diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingValueElement.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingValueElement.cs index 2042139..76aeaa6 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingValueElement.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingValueElement.cs @@ -13,18 +13,8 @@ namespace System.Configuration private XmlNode _valueXml; private bool _isModified; - protected internal override ConfigurationPropertyCollection Properties - { - get - { - if (_properties == null) - { - _properties = new ConfigurationPropertyCollection(); - } - - return _properties; - } - } + protected internal override ConfigurationPropertyCollection Properties => + _properties ??= new ConfigurationPropertyCollection(); public XmlNode ValueXml { diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/TypeUtil.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/TypeUtil.cs index 91a6ce2..aaeb706 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/TypeUtil.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/TypeUtil.cs @@ -100,12 +100,7 @@ namespace System.Configuration } } - if (type == null) - { - type = GetImplicitType(typeString); - } - - return type; + return type ?? GetImplicitType(typeString); } // Ask the host to get the type specified by typeString. If it fails, try to retrieve it @@ -127,12 +122,7 @@ namespace System.Configuration } } - if (type == null) - { - type = GetImplicitType(typeString); - } - - return type; + return type ?? GetImplicitType(typeString); } internal static T CreateInstance(string typeString) diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/UpdateConfigHost.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/UpdateConfigHost.cs index f8e7be8..3cdd1ab 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/UpdateConfigHost.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/UpdateConfigHost.cs @@ -36,7 +36,7 @@ namespace System.Configuration if (!alwaysIntercept && StringUtil.EqualsIgnoreCase(oldStreamname, newStreamname)) return; - if (_streams == null) _streams = new HybridDictionary(true); + _streams ??= new HybridDictionary(true); _streams[oldStreamname] = new StreamUpdate(newStreamname); } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/XmlUtil.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/XmlUtil.cs index 2e083fc..5b09f60 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/XmlUtil.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/XmlUtil.cs @@ -921,8 +921,13 @@ namespace System.Configuration private void ResetCachedStringWriter() { if (_cachedStringWriter == null) + { _cachedStringWriter = new StringWriter(new StringBuilder(64), CultureInfo.InvariantCulture); - else _cachedStringWriter.GetStringBuilder().Length = 0; + } + else + { + _cachedStringWriter.GetStringBuilder().Length = 0; + } } // Copy a configuration section to a string, and advance the reader. diff --git a/src/libraries/System.Console/src/System/IO/StdInReader.cs b/src/libraries/System.Console/src/System/IO/StdInReader.cs index f7e2810..e20465b 100644 --- a/src/libraries/System.Console/src/System/IO/StdInReader.cs +++ b/src/libraries/System.Console/src/System/IO/StdInReader.cs @@ -205,10 +205,7 @@ namespace System.IO if (ConsolePal.TryGetCursorPosition(out int left, out int top, reinitializeForRead: true) && left == 0 && top > 0) { - if (s_clearToEol == null) - { - s_clearToEol = ConsolePal.TerminalFormatStrings.Instance.ClrEol ?? string.Empty; - } + s_clearToEol ??= ConsolePal.TerminalFormatStrings.Instance.ClrEol ?? string.Empty; // Move to end of previous line ConsolePal.SetCursorPosition(ConsolePal.WindowWidth - 1, top - 1); diff --git a/src/libraries/System.Console/src/System/TermInfo.cs b/src/libraries/System.Console/src/System/TermInfo.cs index 0ac9b5a..8f4d31c 100644 --- a/src/libraries/System.Console/src/System/TermInfo.cs +++ b/src/libraries/System.Console/src/System/TermInfo.cs @@ -524,11 +524,7 @@ namespace System /// The formatted string. public static string Evaluate(string format, FormatParam arg) { - FormatParam[]? args = t_cachedOneElementArgsArray; - if (args == null) - { - t_cachedOneElementArgsArray = args = new FormatParam[1]; - } + FormatParam[] args = t_cachedOneElementArgsArray ??= new FormatParam[1]; args[0] = arg; @@ -542,11 +538,7 @@ namespace System /// The formatted string. public static string Evaluate(string format, FormatParam arg1, FormatParam arg2) { - FormatParam[]? args = t_cachedTwoElementArgsArray; - if (args == null) - { - t_cachedTwoElementArgsArray = args = new FormatParam[2]; - } + FormatParam[] args = t_cachedTwoElementArgsArray ??= new FormatParam[2]; args[0] = arg1; args[1] = arg2; diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DataRecordInternal.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DataRecordInternal.cs index 4f2a9ce..e148813 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DataRecordInternal.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DataRecordInternal.cs @@ -359,14 +359,8 @@ namespace System.Data.Common } [RequiresUnreferencedCode("PropertyDescriptor's PropertyType cannot be statically discovered. The public parameterless constructor or the 'Default' static field may be trimmed from the Attribute's Type.")] - PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[]? attributes) - { - if (_propertyDescriptors == null) - { - _propertyDescriptors = new PropertyDescriptorCollection(null); - } - return _propertyDescriptors; - } + PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[]? attributes) => + _propertyDescriptors ??= new PropertyDescriptorCollection(null); object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor? pd) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Constraint.cs b/src/libraries/System.Data.Common/src/System/Data/Constraint.cs index f960762..c82f3d3 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Constraint.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Constraint.cs @@ -32,10 +32,7 @@ namespace System.Data get { return _name; } set { - if (value == null) - { - value = string.Empty; - } + value ??= string.Empty; if (string.IsNullOrEmpty(value) && (Table != null) && InCollection) { diff --git a/src/libraries/System.Data.Common/src/System/Data/DataColumn.cs b/src/libraries/System.Data.Common/src/System/Data/DataColumn.cs index 089db87..1e2021a 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataColumn.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataColumn.cs @@ -318,10 +318,7 @@ namespace System.Data get { return _caption ?? _columnName; } set { - if (value == null) - { - value = string.Empty; - } + value ??= string.Empty; if (_caption == null || string.Compare(_caption, value, true, Locale) != 0) { @@ -361,10 +358,7 @@ namespace System.Data long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, '{1}'", ObjectID, value); try { - if (value == null) - { - value = string.Empty; - } + value ??= string.Empty; if (string.Compare(_columnName, value, true, Locale) != 0) { @@ -412,10 +406,7 @@ namespace System.Data { get { - if (_encodedColumnName == null) - { - _encodedColumnName = XmlConvert.EncodeLocalName(ColumnName); - } + _encodedColumnName ??= XmlConvert.EncodeLocalName(ColumnName); Debug.Assert(!string.IsNullOrEmpty(_encodedColumnName)); return _encodedColumnName; @@ -439,10 +430,7 @@ namespace System.Data get { return _columnPrefix; } set { - if (value == null) - { - value = string.Empty; - } + value ??= string.Empty; DataCommonEventSource.Log.Trace(" {0}, '{1}'", ObjectID, value); @@ -733,10 +721,7 @@ namespace System.Data { long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, '{1}'", ObjectID, value); - if (value == null) - { - value = string.Empty; - } + value ??= string.Empty; try { @@ -1710,10 +1695,7 @@ namespace System.Data { if (value != null && value != DBNull.Value && ((string)value).Length > MaxLength) { - if (errorText == null) - { - errorText = ExceptionBuilder.MaxLengthViolationText(ColumnName); - } + errorText ??= ExceptionBuilder.MaxLengthViolationText(ColumnName); dr.RowError = errorText; dr.SetColumnError(this, errorText); error = true; @@ -1723,10 +1705,7 @@ namespace System.Data { if (!DataStorage.IsObjectNull(value) && ((SqlString)value).Value.Length > MaxLength) { - if (errorText == null) - { - errorText = ExceptionBuilder.MaxLengthViolationText(ColumnName); - } + errorText ??= ExceptionBuilder.MaxLengthViolationText(ColumnName); dr.RowError = errorText; dr.SetColumnError(this, errorText); error = true; @@ -1766,15 +1745,8 @@ namespace System.Data OnPropertyChanging(new PropertyChangedEventArgs(name)); } - private DataStorage InsureStorage() - { - if (_storage == null) - { - _storage = DataStorage.CreateStorage(this, _dataType, _storageType); - } - - return _storage; - } + private DataStorage InsureStorage() => + _storage ??= DataStorage.CreateStorage(this, _dataType, _storageType); internal void SetCapacity(int capacity) { diff --git a/src/libraries/System.Data.Common/src/System/Data/DataError.cs b/src/libraries/System.Data.Common/src/System/Data/DataError.cs index 3ef950a..2657da2 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataError.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataError.cs @@ -46,10 +46,7 @@ namespace System.Data } else { - if (_errorList == null) - { - _errorList = new ColumnError[initialCapacity]; - } + _errorList ??= new ColumnError[initialCapacity]; int i = IndexOf(column); _errorList[i]._column = column; _errorList[i]._error = error; diff --git a/src/libraries/System.Data.Common/src/System/Data/DataRelation.cs b/src/libraries/System.Data.Common/src/System/Data/DataRelation.cs index 71170c5..d903c18 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataRelation.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataRelation.cs @@ -359,10 +359,7 @@ namespace System.Data long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, '{1}'", ObjectID, value); try { - if (value == null) - { - value = string.Empty; - } + value ??= string.Empty; CultureInfo locale = (_dataSet != null ? _dataSet.Locale : CultureInfo.CurrentCulture); if (string.Compare(_relationName, value, true, locale) != 0) diff --git a/src/libraries/System.Data.Common/src/System/Data/DataRow.cs b/src/libraries/System.Data.Common/src/System/Data/DataRow.cs index 34679c6..c80fe12 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataRow.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataRow.cs @@ -732,7 +732,7 @@ namespace System.Data long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, column={1}, error='{2}'", _objectID, column.ObjectID, error); try { - if (_error == null) _error = new DataError(); + _error ??= new DataError(); if (GetColumnError(column) != error) { _error.SetColumnError(column, error); @@ -761,7 +761,7 @@ namespace System.Data public string GetColumnError(DataColumn column) { CheckColumn(column); - if (_error == null) _error = new DataError(); + _error ??= new DataError(); return _error.GetColumnError(column); } diff --git a/src/libraries/System.Data.Common/src/System/Data/DataSet.cs b/src/libraries/System.Data.Common/src/System/Data/DataSet.cs index fc153a2..b38833e 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataSet.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataSet.cs @@ -639,12 +639,10 @@ namespace System.Data { lock (_defaultViewManagerLock) { - if (_defaultViewManager == null) - { - _defaultViewManager = new DataViewManager(this, true); - } + _defaultViewManager ??= new DataViewManager(this, true); } } + return _defaultViewManager; } } @@ -758,10 +756,7 @@ namespace System.Data set { DataCommonEventSource.Log.Trace(" {0}, '{1}'", ObjectID, value); - if (value == null) - { - value = string.Empty; - } + value ??= string.Empty; if (value != _namespaceURI) { @@ -801,10 +796,7 @@ namespace System.Data get { return _datasetPrefix; } set { - if (value == null) - { - value = string.Empty; - } + value ??= string.Empty; if ((XmlConvert.DecodeName(value) == value) && (XmlConvert.EncodeName(value) != value)) { @@ -2182,10 +2174,7 @@ namespace System.Data } else { - if (xmlload == null) - { - xmlload = new XmlDataLoader(this, fIsXdr, topNode, false); - } + xmlload ??= new XmlDataLoader(this, fIsXdr, topNode, false); xmlload.LoadData(reader); topNodeIsProcessed = true; // we process the topnode @@ -2226,10 +2215,7 @@ namespace System.Data // now top node contains the data part xdoc.AppendChild(topNode); - if (xmlload == null) - { - xmlload = new XmlDataLoader(this, fIsXdr, topNode, false); - } + xmlload ??= new XmlDataLoader(this, fIsXdr, topNode, false); if (!isEmptyDataSet && !topNodeIsProcessed) { @@ -2734,10 +2720,7 @@ namespace System.Data } else { - if (xmlload == null) - { - xmlload = new XmlDataLoader(this, fIsXdr, topNode, mode == XmlReadMode.IgnoreSchema); - } + xmlload ??= new XmlDataLoader(this, fIsXdr, topNode, mode == XmlReadMode.IgnoreSchema); xmlload.LoadData(reader); } } //end of the while @@ -2747,8 +2730,7 @@ namespace System.Data // now top node contains the data part xdoc.AppendChild(topNode); - if (xmlload == null) - xmlload = new XmlDataLoader(this, fIsXdr, mode == XmlReadMode.IgnoreSchema); + xmlload ??= new XmlDataLoader(this, fIsXdr, mode == XmlReadMode.IgnoreSchema); if (mode == XmlReadMode.DiffGram) { diff --git a/src/libraries/System.Data.Common/src/System/Data/DataTable.cs b/src/libraries/System.Data.Common/src/System/Data/DataTable.cs index 7d601dc..a5cc7cb 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataTable.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataTable.cs @@ -1767,10 +1767,7 @@ namespace System.Data long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, value='{1}'", ObjectID, value); try { - if (value == null) - { - value = string.Empty; - } + value ??= string.Empty; CultureInfo currentLocale = Locale; if (string.Compare(_tableName, value, true, currentLocale) != 0) { @@ -2061,10 +2058,7 @@ namespace System.Data get { return _tablePrefix; } set { - if (value == null) - { - value = string.Empty; - } + value ??= string.Empty; DataCommonEventSource.Log.Trace(" {0}, value='{1}'", ObjectID, value); if ((XmlConvert.DecodeName(value) == value) && (XmlConvert.EncodeName(value) != value)) { @@ -2356,10 +2350,7 @@ namespace System.Data private DataTable CloneHierarchy(DataTable sourceTable, DataSet ds, Hashtable? visitedMap) { - if (visitedMap == null) - { - visitedMap = new Hashtable(); - } + visitedMap ??= new Hashtable(); if (visitedMap.Contains(sourceTable)) { return ((DataTable)visitedMap[sourceTable]!); @@ -5916,10 +5907,7 @@ namespace System.Data } else { - if (xmlload == null) - { - xmlload = new XmlDataLoader(this, fIsXdr, topNode, false); - } + xmlload ??= new XmlDataLoader(this, fIsXdr, topNode, false); xmlload.LoadData(reader); ret = fSchemaFound ? XmlReadMode.ReadSchema : XmlReadMode.IgnoreSchema; } @@ -5941,8 +5929,7 @@ namespace System.Data throw ExceptionBuilder.DataTableInferenceNotSupported(); } - if (xmlload == null) - xmlload = new XmlDataLoader(this, fIsXdr, false); + xmlload ??= new XmlDataLoader(this, fIsXdr, false); // so we InferSchema if (!fDiffsFound) @@ -6217,10 +6204,7 @@ namespace System.Data { throw ExceptionBuilder.DataTableInferenceNotSupported(); } - if (xmlload == null) - { - xmlload = new XmlDataLoader(this, fIsXdr, topNode, mode == XmlReadMode.IgnoreSchema); - } + xmlload ??= new XmlDataLoader(this, fIsXdr, topNode, mode == XmlReadMode.IgnoreSchema); xmlload.LoadData(reader); } } //end of the while @@ -6231,10 +6215,7 @@ namespace System.Data // now top node contains the data part xdoc.AppendChild(topNode); - if (xmlload == null) - { - xmlload = new XmlDataLoader(this, fIsXdr, mode == XmlReadMode.IgnoreSchema); - } + xmlload ??= new XmlDataLoader(this, fIsXdr, mode == XmlReadMode.IgnoreSchema); if (mode == XmlReadMode.DiffGram) { @@ -6812,9 +6793,7 @@ namespace System.Data #endif #if DEBUG - if (t_usedTables == null) - t_usedTables = new List(); - t_usedTables.Add(table); + (t_usedTables ??= new List()).Add(table); #endif _targetTable = table; table._rowDiffId = null; @@ -6863,8 +6842,7 @@ namespace System.Data #if DEBUG // initialize list of tables out of current tables // note: it might remain empty (still initialization is needed for assert to operate) - if (RowDiffIdUsageSection.t_usedTables == null) - RowDiffIdUsageSection.t_usedTables = new List(); + RowDiffIdUsageSection.t_usedTables ??= new List(); #endif for (int tableIndex = 0; tableIndex < ds.Tables.Count; ++tableIndex) { @@ -6914,11 +6892,7 @@ namespace System.Data // assert scope has been created either with RowDiffIdUsageSection.Prepare or DSRowDiffIdUsageSection.Prepare RowDiffIdUsageSection.Assert("missing call to RowDiffIdUsageSection.Prepare or DSRowDiffIdUsageSection.Prepare"); - if (_rowDiffId == null) - { - _rowDiffId = new Hashtable(); - } - return _rowDiffId; + return _rowDiffId ??= new Hashtable(); } } @@ -6926,10 +6900,7 @@ namespace System.Data internal void AddDependentColumn(DataColumn expressionColumn) { - if (_dependentColumns == null) - { - _dependentColumns = new List(); - } + _dependentColumns ??= new List(); if (!_dependentColumns.Contains(expressionColumn)) { diff --git a/src/libraries/System.Data.Common/src/System/Data/DataTableReader.cs b/src/libraries/System.Data.Common/src/System/Data/DataTableReader.cs index 58d56a3..b37c297 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataTableReader.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataTableReader.cs @@ -138,12 +138,7 @@ namespace System.Data // each time, we just get schema table of current table for once, no need to recreate each time, if schema is changed, reader is already // is invalid - if (_schemaTable == null) - { - _schemaTable = GetSchemaTableFromDataTable(_currentDataTable); - } - - return _schemaTable; + return _schemaTable ??= GetSchemaTableFromDataTable(_currentDataTable); } public override bool NextResult() @@ -158,10 +153,7 @@ namespace System.Data _currentDataTable = _tables[++_tableCounter]; - if (_listener != null) - { - _listener.UpdataTable(_currentDataTable); // it will unsubscribe from preveous tables events and subscribe to new table's events - } + _listener?.UpdataTable(_currentDataTable); // it will unsubscribe from preveous tables events and subscribe to new table's events _schemaTable = null; _rowCounter = -1; diff --git a/src/libraries/System.Data.Common/src/System/Data/DataView.cs b/src/libraries/System.Data.Common/src/System/Data/DataView.cs index 6a94981..6f165eb 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataView.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataView.cs @@ -153,15 +153,8 @@ namespace System.Data throw ExceptionBuilder.SetRowStateFilter(); } - if (Sort == null) - { - Sort = string.Empty; - } - - if (RowFilter == null) - { - RowFilter = string.Empty; - } + Sort ??= string.Empty; + RowFilter ??= string.Empty; DataExpression newFilter = new DataExpression(table, RowFilter); SetIndex(Sort, RowState, newFilter); diff --git a/src/libraries/System.Data.Common/src/System/Data/DataViewSetting.cs b/src/libraries/System.Data.Common/src/System/Data/DataViewSetting.cs index 0e91087..0648759 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataViewSetting.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataViewSetting.cs @@ -59,10 +59,7 @@ namespace System.Data [RequiresUnreferencedCode(Select.RequiresUnreferencedCodeMessage)] set { - if (value == null) - { - value = string.Empty; - } + value ??= string.Empty; if (_rowFilter != value) { @@ -89,10 +86,7 @@ namespace System.Data get { return _sort; } set { - if (value == null) - { - value = string.Empty; - } + value ??= string.Empty; if (_sort != value) { diff --git a/src/libraries/System.Data.Common/src/System/Data/ProviderBase/SchemaMapping.cs b/src/libraries/System.Data.Common/src/System/Data/ProviderBase/SchemaMapping.cs index b47462c..9d2b2df 100644 --- a/src/libraries/System.Data.Common/src/System/Data/ProviderBase/SchemaMapping.cs +++ b/src/libraries/System.Data.Common/src/System/Data/ProviderBase/SchemaMapping.cs @@ -1028,10 +1028,7 @@ namespace System.Data.ProviderBase // if (addPrimaryKeys && schemaRow.IsKey) { - if (keys == null) - { - keys = new DataColumn[schemaRows.Length]; - } + keys ??= new DataColumn[schemaRows.Length]; keys[keyCount++] = dataColumn; // see case 3 above, we do want dataColumn.AllowDBNull not schemaRow.AllowDBNull diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBytes.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBytes.cs index 9045b9a..0930071 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBytes.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBytes.cs @@ -200,16 +200,15 @@ namespace System.Data.SqlTypes if (offset < 0 || offset >= Length) throw new ArgumentOutOfRangeException(nameof(offset)); - if (_rgbWorkBuf == null) - _rgbWorkBuf = new byte[1]; + _rgbWorkBuf ??= new byte[1]; Read(offset, _rgbWorkBuf, 0, 1); return _rgbWorkBuf[0]; } set { - if (_rgbWorkBuf == null) - _rgbWorkBuf = new byte[1]; + _rgbWorkBuf ??= new byte[1]; + _rgbWorkBuf[0] = value; Write(offset, _rgbWorkBuf, 0, 1); } diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLChars.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLChars.cs index 7719da0..ad9e74a 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLChars.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLChars.cs @@ -195,16 +195,15 @@ namespace System.Data.SqlTypes if (offset < 0 || offset >= Length) throw new ArgumentOutOfRangeException(nameof(offset)); - if (_rgchWorkBuf == null) - _rgchWorkBuf = new char[1]; + _rgchWorkBuf ??= new char[1]; Read(offset, _rgchWorkBuf, 0, 1); return _rgchWorkBuf[0]; } set { - if (_rgchWorkBuf == null) - _rgchWorkBuf = new char[1]; + _rgchWorkBuf ??= new char[1]; + _rgchWorkBuf[0] = value; Write(offset, _rgchWorkBuf, 0, 1); } diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLString.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLString.cs index 5e9e2f5..ee53672 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLString.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLString.cs @@ -261,8 +261,7 @@ namespace System.Data.SqlTypes private void SetCompareInfo() { Debug.Assert(!IsNull); - if (m_cmpInfo == null) - m_cmpInfo = (CultureInfo.GetCultureInfo(m_lcid)).CompareInfo; + m_cmpInfo ??= (CultureInfo.GetCultureInfo(m_lcid)).CompareInfo; } public CompareInfo CompareInfo @@ -275,7 +274,9 @@ namespace System.Data.SqlTypes return m_cmpInfo!; } else + { throw new SqlNullValueException(); + } } } @@ -284,9 +285,13 @@ namespace System.Data.SqlTypes get { if (!IsNull) + { return m_flag; + } else + { throw new SqlNullValueException(); + } } } diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SqlXml.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SqlXml.cs index 00fc6c2..fb4d729 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SqlXml.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SqlXml.cs @@ -85,10 +85,7 @@ namespace System.Data.SqlTypes } // NOTE: Maintaining createSqlReaderMethodInfo private field member to preserve the serialization of the class - if (_createSqlReaderMethodInfo == null) - { - _createSqlReaderMethodInfo = CreateSqlReaderMethodInfo; - } + _createSqlReaderMethodInfo ??= CreateSqlReaderMethodInfo; Debug.Assert(_createSqlReaderMethodInfo != null, "MethodInfo reference for XmlReader.CreateSqlReader should not be null."); XmlReader r = CreateSqlXmlReader(stream); @@ -125,18 +122,8 @@ namespace System.Data.SqlTypes return CreateSqlReaderMethodInfo.CreateDelegate>(); } - private static MethodInfo CreateSqlReaderMethodInfo - { - get - { - if (s_createSqlReaderMethodInfo == null) - { - s_createSqlReaderMethodInfo = typeof(System.Xml.XmlReader).GetMethod("CreateSqlReader", BindingFlags.Static | BindingFlags.NonPublic)!; - } - - return s_createSqlReaderMethodInfo; - } - } + private static MethodInfo CreateSqlReaderMethodInfo => + s_createSqlReaderMethodInfo ??= typeof(System.Xml.XmlReader).GetMethod("CreateSqlReader", BindingFlags.Static | BindingFlags.NonPublic)!; // INullable public bool IsNull diff --git a/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs b/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs index 29c9c4d..2de32d6 100644 --- a/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs +++ b/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs @@ -217,10 +217,7 @@ namespace System.Data XmlSchemaSimpleType? xmlSimpleType = (item as XmlSchemaSimpleType); if (xmlSimpleType != null) { - if (_udSimpleTypes == null) - { - _udSimpleTypes = new Hashtable(); - } + _udSimpleTypes ??= new Hashtable(); _udSimpleTypes[type.QualifiedName.ToString()] = xmlSimpleType; DataColumn? dc = (DataColumn?)_existingSimpleTypeMap![type.QualifiedName.ToString()]; @@ -372,8 +369,7 @@ namespace System.Data { if (attrs[i].LocalName == "Expression") { - if (_expressions == null) - _expressions = new Hashtable(); + _expressions ??= new Hashtable(); _expressions[dc] = attrs[i].Value; _columnExpressions!.Add(dc); break; diff --git a/src/libraries/System.Data.Common/src/System/Data/XmlDataLoader.cs b/src/libraries/System.Data.Common/src/System/Data/XmlDataLoader.cs index 9fbc276..2f94d51 100644 --- a/src/libraries/System.Data.Common/src/System/Data/XmlDataLoader.cs +++ b/src/libraries/System.Data.Common/src/System/Data/XmlDataLoader.cs @@ -163,10 +163,7 @@ namespace System.Data } } - if (value == null) - value = string.Empty; - - return value; + return value ?? string.Empty; } private static string GetInitialTextFromNodes(ref XmlNode? n) @@ -197,10 +194,7 @@ namespace System.Data } } - if (value == null) - value = string.Empty; - - return value; + return value ?? string.Empty; } private static DataColumn? GetTextOnlyColumn(DataRow row) @@ -437,8 +431,7 @@ namespace System.Data // nothing left down here, continue from element - if (n == null) - n = e; + n ??= e; } } @@ -596,11 +589,9 @@ namespace System.Data // Keep constraints status for datataset/table InitNameTable(); // Adds DataSet namespaces to reader's nametable - if (_nodeToSchemaMap == null) - { // Create XML to dataset map - _nodeToSchemaMap = _isTableLevel ? new XmlToDatasetMap(_dataReader.NameTable, _dataTable!) : + // Create XML to dataset map + _nodeToSchemaMap ??= _isTableLevel ? new XmlToDatasetMap(_dataReader.NameTable, _dataTable!) : new XmlToDatasetMap(_dataReader.NameTable, _dataSet!); - } if (_isTableLevel) { @@ -1255,10 +1246,7 @@ namespace System.Data StringBuilder? builder = null; while (_dataReader.Read() && entryDepth < _dataReader.Depth && IsTextLikeNode(_dataReader.NodeType)) { - if (builder == null) - { - builder = new StringBuilder(text); - } + builder ??= new StringBuilder(text); builder.Append(_dataReader.Value); // Concatenate other sequential text like // nodes we might have. This is rare. // We're using this instead of dataReader.ReadString() diff --git a/src/libraries/System.Data.Common/src/System/Data/XmlToDatasetMap.cs b/src/libraries/System.Data.Common/src/System/Data/XmlToDatasetMap.cs index 568779d..c66e8f5 100644 --- a/src/libraries/System.Data.Common/src/System/Data/XmlToDatasetMap.cs +++ b/src/libraries/System.Data.Common/src/System/Data/XmlToDatasetMap.cs @@ -176,12 +176,9 @@ namespace System.Data string _tableLocalName = table.EncodedTableName; // Table name - string? tableLocalName = nameTable.Get(_tableLocalName); // Look it up in nametable - - if (tableLocalName == null) - { // If not found - tableLocalName = nameTable.Add(_tableLocalName); // Add it - } + string tableLocalName = + nameTable.Get(_tableLocalName) ?? // Look it up in nametable + nameTable.Add(_tableLocalName); // If not found, add it table._encodedTableName = tableLocalName; // And set it back @@ -231,12 +228,9 @@ namespace System.Data private static bool AddColumnSchema(XmlNameTable nameTable, DataColumn col, XmlNodeIdHashtable columns) { string _columnLocalName = XmlConvert.EncodeLocalName(col.ColumnName); - string? columnLocalName = nameTable.Get(_columnLocalName); // Look it up in a name table - - if (columnLocalName == null) - { // Not found? - columnLocalName = nameTable.Add(_columnLocalName); // Add it - } + string columnLocalName = + nameTable.Get(_columnLocalName) ?? // Look it up in a name table + nameTable.Add(_columnLocalName); // Not found? Add it col._encodedColumnName = columnLocalName; // And set it back @@ -297,15 +291,11 @@ namespace System.Data // Hash tables with columns schema maps // and child tables schema maps - string? dsNamespace = nameTable.Get(dataSet.Namespace); // Attept to look up DataSet namespace - // in the name table - - if (dsNamespace == null) - { // Found ? - dsNamespace = nameTable.Add(dataSet.Namespace); // Nope. Add it - } - dataSet._namespaceURI = dsNamespace; // Set a DataSet namespace URI + string dsNamespace = + nameTable.Get(dataSet.Namespace) ?? // Attempt to look up DataSet namespace in the name table + nameTable.Add(dataSet.Namespace); // Found? Nope. Add it + dataSet._namespaceURI = dsNamespace; // Set a DataSet namespace URI foreach (DataTable t in dataSet.Tables) { // For each table @@ -334,19 +324,13 @@ namespace System.Data // Handle namespaces and names as usuall string _tableLocalName = XmlConvert.EncodeLocalName(r.ChildTable.TableName); - string? tableLocalName = nameTable.Get(_tableLocalName); - - if (tableLocalName == null) - { - tableLocalName = nameTable.Add(_tableLocalName); - } - - string? tableNamespace = nameTable.Get(r.ChildTable.Namespace); + string? tableLocalName = + nameTable.Get(_tableLocalName) ?? + nameTable.Add(_tableLocalName); - if (tableNamespace == null) - { - tableNamespace = nameTable.Add(r.ChildTable.Namespace); - } + string? tableNamespace = + nameTable.Get(r.ChildTable.Namespace) ?? + nameTable.Add(r.ChildTable.Namespace); XmlNodeIdentety idTable = new XmlNodeIdentety(tableLocalName, tableNamespace); tableSchemaInfo.ColumnsSchemaMap[idTable] = r.ChildTable; diff --git a/src/libraries/System.Data.Common/src/System/Xml/XmlDataDocument.cs b/src/libraries/System.Data.Common/src/System/Xml/XmlDataDocument.cs index f79179d..5bd3410 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/XmlDataDocument.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/XmlDataDocument.cs @@ -357,10 +357,8 @@ namespace System.Xml // fBoundToDataSet and fBoundToDocument should have the same value Debug.Assert(_fBoundToDataSet ? _fBoundToDocument : (!_fBoundToDocument)); #endif - if (prefix == null) - prefix = string.Empty; - if (namespaceURI == null) - namespaceURI = string.Empty; + prefix ??= string.Empty; + namespaceURI ??= string.Empty; if (!_fAssociateDataRow) { @@ -474,12 +472,12 @@ namespace System.Xml if (docelem == null) { string docElemName = XmlConvert.EncodeLocalName(DataSet.DataSetName); - if (docElemName == null || docElemName.Length == 0) + if (string.IsNullOrEmpty(docElemName)) + { docElemName = "Xml"; - string ns = DataSet.Namespace; - if (ns == null) - ns = string.Empty; - docelem = new XmlBoundElement(string.Empty, docElemName, ns, this); + } + + docelem = new XmlBoundElement(string.Empty, docElemName, DataSet.Namespace ?? string.Empty, this); AppendChild(docelem); } @@ -730,11 +728,14 @@ namespace System.Xml Debug.Assert(col.ColumnMapping == MappingType.SimpleContent); newNode = CreateTextNode(col.ConvertObjectToXml(value)); if (node.FirstChild != null) + { node.InsertBefore(newNode, node.FirstChild); + } else + { node.AppendChild(newNode); - if (priorNode == null) - priorNode = newNode; + } + priorNode ??= newNode; } } } @@ -1477,7 +1478,9 @@ namespace System.Xml _bHasXSINIL = true; } else + { attr.Value = Keywords.TRUE; + } } else { diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/DbDataRecord.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/DbDataRecord.cs index 1e97a9c..176a116 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/DbDataRecord.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/DbDataRecord.cs @@ -115,10 +115,7 @@ namespace System.Data.Odbc // retrieve all the value in between so they can go back to values they've skipped for (int c = 0; c < i; c++) { - if (values[c] == null) - { - values[c] = _record.GetValue(c); - } + values[c] ??= _record.GetValue(c); } } return values[i]; @@ -126,10 +123,7 @@ namespace System.Data.Odbc internal DbSchemaInfo GetSchema(int i) { - if (_schema == null) - { - _schema = new DbSchemaInfo[Count]; - } + _schema ??= new DbSchemaInfo[Count]; return _schema[i] ??= new DbSchemaInfo(); } diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcCommand.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcCommand.cs index ec050d4..0b62490 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcCommand.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcCommand.cs @@ -411,10 +411,7 @@ namespace System.Data.Odbc _connection.AddWeakReference(this, OdbcReferenceCollection.CommandTag); } - if (_cmdWrapper._dataReaderBuf == null) - { - _cmdWrapper._dataReaderBuf = new CNativeBuffer(4096); - } + _cmdWrapper._dataReaderBuf ??= new CNativeBuffer(4096); // if there is already a statement handle we need to do some cleanup // diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnection.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnection.cs index 69329e3..cf23b50 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnection.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnection.cs @@ -201,12 +201,9 @@ namespace System.Data.Odbc { if (IsOpen) { - if (ProviderInfo.DriverName == null) - { - ProviderInfo.DriverName = GetInfoStringUnhandled(ODBC32.SQL_INFO.DRIVER_NAME)!; - } - return ProviderInfo.DriverName; + return ProviderInfo.DriverName ??= GetInfoStringUnhandled(ODBC32.SQL_INFO.DRIVER_NAME)!; } + return string.Empty; } } diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataReader.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataReader.cs index d5e4a5c..ef5bc0b 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataReader.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataReader.cs @@ -402,11 +402,7 @@ namespace System.Data.Odbc if (null != _dataCache) { DbSchemaInfo info = _dataCache.GetSchema(i); - if (info._typename == null) - { - info._typename = GetColAttributeStr(i, ODBC32.SQL_DESC.TYPE_NAME, ODBC32.SQL_COLUMN.TYPE_NAME, ODBC32.HANDLER.THROW)!; - } - return info._typename; + return info._typename ??= GetColAttributeStr(i, ODBC32.SQL_DESC.TYPE_NAME, ODBC32.SQL_COLUMN.TYPE_NAME, ODBC32.HANDLER.THROW)!; } throw ADP.DataReaderNoData(); } @@ -421,11 +417,7 @@ namespace System.Data.Odbc if (null != _dataCache) { DbSchemaInfo info = _dataCache.GetSchema(i); - if (info._type == null) - { - info._type = GetSqlType(i)._type; - } - return info._type; + return info._type ??= GetSqlType(i)._type; } throw ADP.DataReaderNoData(); } @@ -435,15 +427,7 @@ namespace System.Data.Odbc if (null != _dataCache) { DbSchemaInfo info = _dataCache.GetSchema(i); - if (info._name == null) - { - info._name = GetColAttributeStr(i, ODBC32.SQL_DESC.NAME, ODBC32.SQL_COLUMN.NAME, ODBC32.HANDLER.THROW); - if (null == info._name) - { // MDAC 66681 - info._name = ""; - } - } - return info._name; + return info._name ??= GetColAttributeStr(i, ODBC32.SQL_DESC.NAME, ODBC32.SQL_COLUMN.NAME, ODBC32.HANDLER.THROW) ?? ""; } throw ADP.DataReaderNoData(); } @@ -2378,10 +2362,7 @@ namespace System.Data.Odbc _metadata[ordinal].isNullable = false; _metadata[ordinal].baseTableName = qualifiedTableName.Table; - if (_metadata[ordinal].baseColumnName == null) - { - _metadata[ordinal].baseColumnName = columnname; - } + _metadata[ordinal].baseColumnName ??= columnname; } else { @@ -2453,10 +2434,7 @@ namespace System.Data.Odbc if (ordinal != -1) { _metadata[ordinal].isRowVersion = true; - if (_metadata[ordinal].baseColumnName == null) - { - _metadata[ordinal].baseColumnName = columnname; - } + _metadata[ordinal].baseColumnName ??= columnname; } } // Unbind the column @@ -2656,14 +2634,8 @@ namespace System.Data.Odbc // test test test - we don't know if this is nulalble or not so why do we want to set it to a value? _metadata[indexordinal].isNullable = false; _metadata[indexordinal].isUnique = true; - if (_metadata[indexordinal].baseTableName == null) - { - _metadata[indexordinal].baseTableName = qualifiedTableName.Table; - } - if (_metadata[indexordinal].baseColumnName == null) - { - _metadata[indexordinal].baseColumnName = columnname; - } + _metadata[indexordinal].baseTableName ??= qualifiedTableName.Table; + _metadata[indexordinal].baseColumnName ??= columnname; } } // Unbind the columns diff --git a/src/libraries/System.Data.Odbc/tests/OdbcParameterTests.cs b/src/libraries/System.Data.Odbc/tests/OdbcParameterTests.cs index 369bd2a..c7a9569 100644 --- a/src/libraries/System.Data.Odbc/tests/OdbcParameterTests.cs +++ b/src/libraries/System.Data.Odbc/tests/OdbcParameterTests.cs @@ -182,10 +182,7 @@ namespace System.Data.Odbc.Tests public bool connectSqlServer(string connStr) { - if (con == null) - { - con = new OdbcConnection(connStr); - } + con ??= new OdbcConnection(connStr); con.Open(); trn = con.BeginTransaction(); diff --git a/src/libraries/System.Data.OleDb/src/OleDbCommandBuilder.cs b/src/libraries/System.Data.OleDb/src/OleDbCommandBuilder.cs index b14b18c..03cf948 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbCommandBuilder.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbCommandBuilder.cs @@ -379,10 +379,7 @@ namespace System.Data.OleDb connection.GetLiteralQuotes(ADP.QuoteIdentifier, out quotePrefix, out quoteSuffix); // if the quote suffix is null assume that it is the same as the prefix (See OLEDB spec // IDBInfo::GetLiteralInfo DBLITERAL_QUOTE_SUFFIX.) - if (quoteSuffix == null) - { - quoteSuffix = quotePrefix; - } + quoteSuffix ??= quotePrefix; } return ADP.BuildQuotedString(quotePrefix, quoteSuffix, unquotedIdentifier); @@ -429,10 +426,7 @@ namespace System.Data.OleDb connection.GetLiteralQuotes(ADP.UnquoteIdentifier, out quotePrefix, out quoteSuffix); // if the quote suffix is null assume that it is the same as the prefix (See OLEDB spec // IDBInfo::GetLiteralInfo DBLITERAL_QUOTE_SUFFIX.) - if (quoteSuffix == null) - { - quoteSuffix = quotePrefix; - } + quoteSuffix ??= quotePrefix; } string? unquotedIdentifier; diff --git a/src/libraries/System.Data.OleDb/src/OleDbMetaDataFactory.cs b/src/libraries/System.Data.OleDb/src/OleDbMetaDataFactory.cs index 4c0296e..425457a 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbMetaDataFactory.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbMetaDataFactory.cs @@ -319,10 +319,7 @@ namespace System.Data.OleDb { // if the quote suffix is null assume that it is the same as the prefix (See OLEDB spec // IDBInfo::GetLiteralInfo DBLITERAL_QUOTE_SUFFIX.) - if (quoteSuffix == null) - { - quoteSuffix = quotePrefix; - } + quoteSuffix ??= quotePrefix; // only know how to build the parttern if the suffix is 1 character // in all other cases just leave the field null diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DiagnosticSourceEventSource.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DiagnosticSourceEventSource.cs index a8d700d..0b9102c 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DiagnosticSourceEventSource.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DiagnosticSourceEventSource.cs @@ -483,8 +483,7 @@ namespace System.Diagnostics public static void CreateFilterAndTransformList(ref FilterAndTransform? specList, string? filterAndPayloadSpecs, DiagnosticSourceEventSource eventSource) { DestroyFilterAndTransformList(ref specList, eventSource); // Stop anything that was on before. - if (filterAndPayloadSpecs == null) - filterAndPayloadSpecs = ""; + filterAndPayloadSpecs ??= ""; // Points just beyond the last point in the string that has yet to be parsed. Thus we start with the whole string. int endIdx = filterAndPayloadSpecs.Length; @@ -642,10 +641,7 @@ namespace System.Diagnostics _eventSource.Message("DiagnosticSource: Could not find Event to log Activity " + activityName); } - if (writeEvent == null) - { - writeEvent = _eventSource.Event; - } + writeEvent ??= _eventSource.Event; // Set up a subscription that watches for the given Diagnostic Sources and events which will call back // to the EventSource. @@ -1197,8 +1193,7 @@ namespace System.Diagnostics _fetches = new PropertySpec(propertyName, _fetches); // If the user did not explicitly set a name, it is the last one (first to be processed from the end). - if (_outputName == null) - _outputName = propertyName; + _outputName ??= propertyName; endIdx = dotIdx; // This works even when LastIndexOf return -1. } diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/MeterListener.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/MeterListener.cs index 4b3c0f1..165b313 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/MeterListener.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/MeterListener.cs @@ -117,10 +117,8 @@ namespace System.Diagnostics.Metrics /// The callback which can be used to get measurement recording of numeric type T. public void SetMeasurementEventCallback(MeasurementCallback? measurementCallback) where T : struct { - if (measurementCallback is null) - { - measurementCallback = (instrument, measurement, tags, state) => { /* no-op */}; - } + measurementCallback ??= (instrument, measurement, tags, state) => { /* no-op */}; + if (typeof(T) == typeof(byte)) { _byteMeasurementCallback = (MeasurementCallback)(object)measurementCallback; diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/RandomNumberGenerator.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/RandomNumberGenerator.cs index 71c686e..dfb8c50 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/RandomNumberGenerator.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/RandomNumberGenerator.cs @@ -12,17 +12,7 @@ namespace System.Diagnostics private ulong _s0, _s1, _s2, _s3; - public static RandomNumberGenerator Current - { - get - { - if (t_random == null) - { - t_random = new RandomNumberGenerator(); - } - return t_random; - } - } + public static RandomNumberGenerator Current => t_random ??= new RandomNumberGenerator(); #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLog.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLog.cs index e24ce1f..272d5d7 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLog.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLog.cs @@ -1053,8 +1053,7 @@ namespace System.Diagnostics // The EventLog.set_Source used to do some normalization and throw some exceptions. We mimic that behavior here. private static string CheckAndNormalizeSourceName(string source) { - if (source == null) - source = string.Empty; + source ??= string.Empty; // this 254 limit is the max length of a registry key. if (source.Length + EventLogKey.Length > 254) diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogConfiguration.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogConfiguration.cs index 894437a..1c58e48 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogConfiguration.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogConfiguration.cs @@ -51,8 +51,7 @@ namespace System.Diagnostics.Eventing.Reader public EventLogConfiguration(string logName, EventLogSession session) { - if (session == null) - session = EventLogSession.GlobalSession; + session ??= EventLogSession.GlobalSession; _session = session; LogName = logName; diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogRecord.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogRecord.cs index 41ccebb..37f50c2 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogRecord.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogRecord.cs @@ -236,11 +236,7 @@ namespace System.Diagnostics.Eventing.Reader return _containerChannel; lock (_syncObject) { - if (_containerChannel == null) - { - _containerChannel = (string)NativeWrapper.EvtGetEventInfo(this.Handle, UnsafeNativeMethods.EvtEventPropertyId.EvtEventPath); - } - return _containerChannel; + return _containerChannel ??= (string)NativeWrapper.EvtGetEventInfo(this.Handle, UnsafeNativeMethods.EvtEventPropertyId.EvtEventPath); } } } @@ -253,11 +249,7 @@ namespace System.Diagnostics.Eventing.Reader return _matchedQueryIds; lock (_syncObject) { - if (_matchedQueryIds == null) - { - _matchedQueryIds = (int[])NativeWrapper.EvtGetEventInfo(this.Handle, UnsafeNativeMethods.EvtEventPropertyId.EvtEventQueryIDs); - } - return _matchedQueryIds; + return _matchedQueryIds ??= (int[])NativeWrapper.EvtGetEventInfo(this.Handle, UnsafeNativeMethods.EvtEventPropertyId.EvtEventQueryIDs); } } } @@ -365,11 +357,7 @@ namespace System.Diagnostics.Eventing.Reader return _keywordsNames; lock (_syncObject) { - if (_keywordsNames == null) - { - _keywordsNames = _cachedMetadataInformation.GetKeywordDisplayNames(this.ProviderName, Handle); - } - return _keywordsNames; + return _keywordsNames ??= _cachedMetadataInformation.GetKeywordDisplayNames(this.ProviderName, Handle); } } } diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogSession.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogSession.cs index 31bfdf8..8d97e21 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogSession.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogSession.cs @@ -94,8 +94,7 @@ namespace System.Diagnostics.Eventing.Reader public EventLogSession(string server, string domain, string user, SecureString password, SessionAuthentication logOnType) { - if (server == null) - server = "localhost"; + server ??= "localhost"; _syncObject = new object(); diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/ProviderMetadata.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/ProviderMetadata.cs index e43b7af..6be68d1 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/ProviderMetadata.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/ProviderMetadata.cs @@ -55,11 +55,8 @@ namespace System.Diagnostics.Eventing.Reader internal ProviderMetadata(string providerName, EventLogSession session, CultureInfo targetCultureInfo, string logFilePath) { - if (targetCultureInfo == null) - targetCultureInfo = CultureInfo.CurrentCulture; - - if (session == null) - session = EventLogSession.GlobalSession; + targetCultureInfo ??= CultureInfo.CurrentCulture; + session ??= EventLogSession.GlobalSession; _session = session; _providerName = providerName; @@ -240,8 +237,7 @@ namespace System.Diagnostics.Eventing.Reader internal string FindStandardLevelDisplayName(string name, uint value) { - if (_standardLevels == null) - _standardLevels = (List)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevels); + _standardLevels ??= (List)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevels); foreach (EventLevel standardLevel in _standardLevels) { if (standardLevel.Name == name && standardLevel.Value == value) @@ -251,8 +247,7 @@ namespace System.Diagnostics.Eventing.Reader } internal string FindStandardOpcodeDisplayName(string name, uint value) { - if (_standardOpcodes == null) - _standardOpcodes = (List)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodes); + _standardOpcodes ??= (List)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodes); foreach (EventOpcode standardOpcode in _standardOpcodes) { if (standardOpcode.Name == name && standardOpcode.Value == value) @@ -262,8 +257,7 @@ namespace System.Diagnostics.Eventing.Reader } internal string FindStandardKeywordDisplayName(string name, long value) { - if (_standardKeywords == null) - _standardKeywords = (List)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywords); + _standardKeywords ??= (List)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywords); foreach (EventKeyword standardKeyword in _standardKeywords) { if (standardKeyword.Name == name && standardKeyword.Value == value) @@ -273,8 +267,7 @@ namespace System.Diagnostics.Eventing.Reader } internal string FindStandardTaskDisplayName(string name, uint value) { - if (_standardTasks == null) - _standardTasks = (List)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTasks); + _standardTasks ??= (List)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTasks); foreach (EventTask standardTask in _standardTasks) { if (standardTask.Name == name && standardTask.Value == value) diff --git a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounter.cs b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounter.cs index fc13490..09a07e0 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounter.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounter.cs @@ -166,8 +166,7 @@ namespace System.Diagnostics Initialize(); - if (_helpMsg == null) - _helpMsg = PerformanceCounterLib.GetCounterHelp(currentMachineName, currentCategoryName, _counterName); + _helpMsg ??= PerformanceCounterLib.GetCounterHelp(currentMachineName, currentCategoryName, _counterName); return _helpMsg; } diff --git a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterCategory.cs b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterCategory.cs index d92a6bb..9b4f2c6 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterCategory.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterCategory.cs @@ -92,8 +92,7 @@ namespace System.Diagnostics if (_categoryName == null) throw new InvalidOperationException(SR.CategoryNameNotSet); - if (_categoryHelp == null) - _categoryHelp = PerformanceCounterLib.GetCategoryHelp(_machineName, _categoryName); + _categoryHelp ??= PerformanceCounterLib.GetCategoryHelp(_machineName, _categoryName); return _categoryHelp; } diff --git a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterLib.cs b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterLib.cs index 220156f..927f9d1 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterLib.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterLib.cs @@ -113,10 +113,7 @@ namespace System.Diagnostics { lock (InternalSyncObject) { - if (s_computerName == null) - { - s_computerName = Interop.Kernel32.GetComputerName() ?? string.Empty; - } + s_computerName ??= Interop.Kernel32.GetComputerName() ?? string.Empty; } } @@ -214,8 +211,7 @@ namespace System.Diagnostics { lock (_helpTableLock) { - if (_helpTable == null) - _helpTable = GetStringTable(true); + _helpTable ??= GetStringTable(true); } } @@ -256,8 +252,7 @@ namespace System.Diagnostics { lock (_nameTableLock) { - if (_nameTable == null) - _nameTable = GetStringTable(false); + _nameTable ??= GetStringTable(false); } } @@ -409,9 +404,7 @@ namespace System.Diagnostics for (int index = 0; index < entry.CounterIndexes.Length; ++index) { int counterIndex = entry.CounterIndexes[index]; - string counterName = (string)NameTable[counterIndex]; - if (counterName == null) - counterName = string.Empty; + string counterName = (string)NameTable[counterIndex] ?? string.Empty; if (string.Equals(counterName, counter, StringComparison.OrdinalIgnoreCase)) return true; @@ -529,9 +522,10 @@ namespace System.Diagnostics { serviceParentKey = Registry.LocalMachine.OpenSubKey(ServicePath, true); - serviceKey = serviceParentKey.OpenSubKey(categoryName + "\\Performance", true); - if (serviceKey == null) - serviceKey = serviceParentKey.CreateSubKey(categoryName + "\\Performance"); + string categoryPerfKeyName = $"{categoryName}\\Performance"; + serviceKey = + serviceParentKey.OpenSubKey(categoryPerfKeyName, writable: true) ?? + serviceParentKey.CreateSubKey(categoryPerfKeyName); serviceKey.SetValue("Open", "OpenPerformanceData"); serviceKey.SetValue("Collect", "CollectPerformanceData"); @@ -548,9 +542,10 @@ namespace System.Diagnostics counterTypes[i] = ((int)creationData[i].CounterType).ToString(CultureInfo.InvariantCulture); } - linkageKey = serviceParentKey.OpenSubKey(categoryName + "\\Linkage", true); - if (linkageKey == null) - linkageKey = serviceParentKey.CreateSubKey(categoryName + "\\Linkage"); + string categoryLinkageKeyName = $"{categoryName}\\Linkage"; + linkageKey = + serviceParentKey.OpenSubKey(categoryLinkageKeyName, writable: true) ?? + serviceParentKey.CreateSubKey(categoryLinkageKeyName); linkageKey.SetValue("Export", new string[] { categoryName }); @@ -558,21 +553,13 @@ namespace System.Diagnostics serviceKey.SetValue("Counter Names", (object)counters); object firstID = serviceKey.GetValue("First Counter"); - if (firstID != null) - iniRegistered = true; - else - iniRegistered = false; + iniRegistered = firstID != null; } finally { - if (serviceKey != null) - serviceKey.Close(); - - if (linkageKey != null) - linkageKey.Close(); - - if (serviceParentKey != null) - serviceParentKey.Close(); + serviceKey?.Close(); + linkageKey?.Close(); + serviceParentKey?.Close(); } } @@ -966,9 +953,7 @@ namespace System.Diagnostics for (int index = 0; index < entry.CounterIndexes.Length; ++index) { int counterIndex = entry.CounterIndexes[index]; - string counterName = (string)NameTable[counterIndex]; - if (counterName == null) - counterName = string.Empty; + string counterName = (string)NameTable[counterIndex] ?? string.Empty; if (string.Equals(counterName, counter, StringComparison.OrdinalIgnoreCase)) { @@ -1017,12 +1002,13 @@ namespace System.Diagnostics //race with CloseAllLibraries lock (InternalSyncObject) { - if (PerformanceCounterLib.s_libraryTable == null) - PerformanceCounterLib.s_libraryTable = new Hashtable(); + PerformanceCounterLib.s_libraryTable ??= new Hashtable(); string libraryKey = machineName + ":" + lcidString; if (PerformanceCounterLib.s_libraryTable.Contains(libraryKey)) + { return (PerformanceCounterLib)PerformanceCounterLib.s_libraryTable[libraryKey]; + } else { PerformanceCounterLib library = new PerformanceCounterLib(machineName, lcidString); @@ -1038,8 +1024,7 @@ namespace System.Diagnostics { lock (InternalSyncObject) { - if (_performanceMonitor == null) - _performanceMonitor = new PerformanceMonitor(_machineName); + _performanceMonitor ??= new PerformanceMonitor(_machineName); } } @@ -1054,14 +1039,10 @@ namespace System.Diagnostics private Hashtable GetStringTable(bool isHelp) { Hashtable stringTable; - RegistryKey libraryKey; - if (string.Equals(_machineName, ComputerName, StringComparison.OrdinalIgnoreCase)) - libraryKey = Registry.PerformanceData; - else - { - libraryKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.PerformanceData, _machineName); - } + RegistryKey libraryKey = string.Equals(_machineName, ComputerName, StringComparison.OrdinalIgnoreCase) ? + Registry.PerformanceData : + RegistryKey.OpenRemoteBaseKey(RegistryHive.PerformanceData, _machineName); try { @@ -1122,9 +1103,7 @@ namespace System.Diagnostics for (int index = 0; index < (names.Length / 2); ++index) { - string nameString = names[(index * 2) + 1]; - if (nameString == null) - nameString = string.Empty; + string nameString = names[(index * 2) + 1] ?? string.Empty; int key; if (!int.TryParse(names[index * 2], NumberStyles.Integer, CultureInfo.InvariantCulture, out key)) diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/PerformanceCounterLib.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/PerformanceCounterLib.cs index 15b5220..9f828f5 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/PerformanceCounterLib.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/PerformanceCounterLib.cs @@ -46,8 +46,7 @@ namespace System.Diagnostics { lock (_nameTableLock) { - if (_nameTable == null) - _nameTable = GetStringTable(false); + _nameTable ??= GetStringTable(false); } } @@ -80,8 +79,7 @@ namespace System.Diagnostics { lock (LazyInitializer.EnsureInitialized(ref s_internalSyncObject)) { - if (_performanceMonitor == null) - _performanceMonitor = new PerformanceMonitor(_machineName); + _performanceMonitor ??= new PerformanceMonitor(_machineName); } } @@ -155,9 +153,7 @@ namespace System.Diagnostics for (int index = 0; index < (names.Length / 2); ++index) { - string nameString = names[(index * 2) + 1]; - if (nameString == null) - nameString = string.Empty; + string nameString = names[(index * 2) + 1] ?? string.Empty; int key; if (!int.TryParse(names[index * 2], NumberStyles.Integer, CultureInfo.InvariantCulture, out key)) diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Win32.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Win32.cs index a8ab0cf..4113c31 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Win32.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Win32.cs @@ -265,18 +265,7 @@ namespace System.Diagnostics return true; } - public string MainWindowTitle - { - get - { - if (_mainWindowTitle == null) - { - _mainWindowTitle = GetMainWindowTitle(); - } - - return _mainWindowTitle; - } - } + public string MainWindowTitle => _mainWindowTitle ??= GetMainWindowTitle(); private bool IsRespondingCore() { diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessWaitState.Unix.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessWaitState.Unix.cs index a7b4804..d807deb 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessWaitState.Unix.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessWaitState.Unix.cs @@ -652,10 +652,7 @@ namespace System.Diagnostics } else { - if (additionalToRemove == null) - { - additionalToRemove = new List(); - } + additionalToRemove ??= new List(); additionalToRemove.Add(pws); } } diff --git a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/DefaultTraceListener.cs b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/DefaultTraceListener.cs index 4af317f..665b858 100644 --- a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/DefaultTraceListener.cs +++ b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/DefaultTraceListener.cs @@ -145,10 +145,7 @@ namespace System.Diagnostics private void Write(string? message, bool useLogFile) { - if (message == null) - { - message = string.Empty; - } + message ??= string.Empty; if (NeedIndent && message.Length != 0) { diff --git a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/Switch.cs b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/Switch.cs index d8b98d8..1b50f00c 100644 --- a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/Switch.cs +++ b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/Switch.cs @@ -55,11 +55,8 @@ namespace System.Diagnostics protected Switch(string displayName, string? description, string defaultSwitchValue) { - // displayName is used as a hashtable key, so it can never - // be null. - if (displayName == null) displayName = string.Empty; - - _displayName = displayName; + // displayName is used as a hashtable key, so it can never be null. + _displayName = displayName ?? string.Empty; _description = description; // Add a weakreference to this switch and cleanup invalid references diff --git a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceEventCache.cs b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceEventCache.cs index cdc431d..43dd994 100644 --- a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceEventCache.cs +++ b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceEventCache.cs @@ -51,18 +51,7 @@ namespace System.Diagnostics } } - public string Callstack - { - get - { - if (_stackTrace == null) - { - _stackTrace = Environment.StackTrace; - } - - return _stackTrace; - } - } + public string Callstack => _stackTrace ??= Environment.StackTrace; public Stack LogicalOperationStack { diff --git a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceInternal.cs b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceInternal.cs index e00b1f9..0ebc7fe 100644 --- a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceInternal.cs +++ b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceInternal.cs @@ -80,17 +80,7 @@ namespace System.Diagnostics } } - internal static string AppName - { - get - { - if (s_appName == null) - { - s_appName = Assembly.GetEntryAssembly()?.GetName().Name ?? string.Empty; - } - return s_appName; - } - } + internal static string AppName => s_appName ??= Assembly.GetEntryAssembly()?.GetName().Name ?? string.Empty; public static bool AutoFlush { diff --git a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceListener.cs b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceListener.cs index 52e43b1..87944a1 100644 --- a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceListener.cs +++ b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceListener.cs @@ -42,15 +42,7 @@ namespace System.Diagnostics _listenerName = name; } - public StringDictionary Attributes - { - get - { - if (_attributes == null) - _attributes = new StringDictionary(); - return _attributes; - } - } + public StringDictionary Attributes => _attributes ??= new StringDictionary(); /// /// Gets or sets a name for this . diff --git a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceSource.cs b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceSource.cs index 8747480..d8d2a39 100644 --- a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceSource.cs +++ b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceSource.cs @@ -470,10 +470,7 @@ namespace System.Diagnostics // Ensure that config is loaded Initialize(); - if (_attributes == null) - _attributes = new StringDictionary(); - - return _attributes; + return _attributes ??= new StringDictionary(); } } diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADAMStoreCtx.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADAMStoreCtx.cs index 087b1a5..fb9e6b1 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADAMStoreCtx.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADAMStoreCtx.cs @@ -37,8 +37,7 @@ namespace System.DirectoryServices.AccountManagement LoadFilterMappingTable(mappingIndex, s_filterPropertiesTableRaw); LoadPropertyMappingTable(mappingIndex, s_propertyMappingTableRaw); - if (NonPresentAttrDefaultStateMapping == null) - NonPresentAttrDefaultStateMapping = new Dictionary(); + NonPresentAttrDefaultStateMapping ??= new Dictionary(); for (int i = 0; i < s_presenceStateTable.GetLength(0); i++) { diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx.cs index 5932bf2..0ed20ee 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx.cs @@ -155,14 +155,12 @@ namespace System.DirectoryServices.AccountManagement // (it's probably read-only, e.g., "lastLogon"). if (toLdap != null) { - if (mappingTableByProperty[propertyName] == null) - mappingTableByProperty[propertyName] = new ArrayList(); + mappingTableByProperty[propertyName] ??= new ArrayList(); ((ArrayList)mappingTableByProperty[propertyName]).Add(propertyEntry); } - if (mappingTableByPropertyFull[propertyName] == null) - mappingTableByPropertyFull[propertyName] = new ArrayList(); + mappingTableByPropertyFull[propertyName] ??= new ArrayList(); ((ArrayList)mappingTableByPropertyFull[propertyName]).Add(propertyEntry); @@ -173,8 +171,7 @@ namespace System.DirectoryServices.AccountManagement { string ldapAttributeLower = ldapAttribute.ToLowerInvariant(); - if (mappingTableByLDAP[ldapAttributeLower] == null) - mappingTableByLDAP[ldapAttributeLower] = new ArrayList(); + mappingTableByLDAP[ldapAttributeLower] ??= new ArrayList(); ((ArrayList)mappingTableByLDAP[ldapAttributeLower]).Add(propertyEntry); } diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_Query.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_Query.cs index 5a274e3..f9d1fa7 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_Query.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_Query.cs @@ -365,8 +365,7 @@ namespace System.DirectoryServices.AccountManagement protected static bool IdentityClaimToFilter(string identity, string identityFormat, ref string filter, bool throwOnFail) { - if (identity == null) - identity = ""; + identity ??= ""; StringBuilder sb = new StringBuilder(); @@ -481,9 +480,7 @@ namespace System.DirectoryServices.AccountManagement if (ic.UrnScheme == null) throw new ArgumentException(SR.StoreCtxIdentityClaimMustHaveScheme); - string urnValue = ic.UrnValue; - if (urnValue == null) - urnValue = ""; + string urnValue = ic.UrnValue ?? ""; string filterString = null; diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AuthenticablePrincipal.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AuthenticablePrincipal.cs index 828be6a..3155d39 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AuthenticablePrincipal.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AuthenticablePrincipal.cs @@ -398,8 +398,7 @@ namespace System.DirectoryServices.AccountManagement { // If this is the first AccountInfo attribute we're loading, // we'll need to create the AccountInfo to hold it - if (_accountInfo == null) - _accountInfo = new AccountInfo(this); + _accountInfo ??= new AccountInfo(this); _accountInfo.LoadValueIntoProperty(propertyName, value); } @@ -407,8 +406,7 @@ namespace System.DirectoryServices.AccountManagement { // If this is the first PasswordInfo attribute we're loading, // we'll need to create the PasswordInfo to hold it - if (_passwordInfo == null) - _passwordInfo = new PasswordInfo(this); + _passwordInfo ??= new PasswordInfo(this); _passwordInfo.LoadValueIntoProperty(propertyName, value); } diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Context.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Context.cs index b4be630..acaf5a6 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Context.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Context.cs @@ -625,10 +625,7 @@ namespace System.DirectoryServices.AccountManagement try { - string hostname = _name; - - if (hostname == null) - hostname = Utils.GetComputerFlatName(); + string hostname = _name ?? Utils.GetComputerFlatName(); GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalContext", "DoMachineInit: hostname is " + hostname); diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx.cs index 5355ec6..b02f4f6 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx.cs @@ -131,8 +131,7 @@ namespace System.DirectoryServices.AccountManagement // { foreach (Hashtable propertyMappingTableByProperty in byPropertyTables) { - if (propertyMappingTableByProperty[propertyName] == null) - propertyMappingTableByProperty[propertyName] = new ArrayList(); + propertyMappingTableByProperty[propertyName] ??= new ArrayList(); ((ArrayList)propertyMappingTableByProperty[propertyName]).Add(propertyEntry); } @@ -147,8 +146,7 @@ namespace System.DirectoryServices.AccountManagement foreach (Hashtable propertyMappingTableByWinNT in byWinNTTables) { - if (propertyMappingTableByWinNT[winNTAttributeLower] == null) - propertyMappingTableByWinNT[winNTAttributeLower] = new ArrayList(); + propertyMappingTableByWinNT[winNTAttributeLower] ??= new ArrayList(); ((ArrayList)propertyMappingTableByWinNT[winNTAttributeLower]).Add(propertyEntry); } diff --git a/src/libraries/System.DirectoryServices.AccountManagement/tests/AccountManagementTests.cs b/src/libraries/System.DirectoryServices.AccountManagement/tests/AccountManagementTests.cs index 33de32c..c5c0aa6 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/tests/AccountManagementTests.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/tests/AccountManagementTests.cs @@ -747,18 +747,7 @@ namespace System.DirectoryServices.AccountManagement.Tests ((CustomFilter) AdvancedSearchFilter).SetFilter(name); } - public override AdvancedFilters AdvancedSearchFilter - { - get - { - if (_customFilter == null) - { - _customFilter = new CustomFilter(this); - } - - return _customFilter; - } - } + public override AdvancedFilters AdvancedSearchFilter => _customFilter ??= new CustomFilter(this); // Custom properties [DirectoryProperty("postalCode")] diff --git a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.cs b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.cs index 8ff1ecc..650f9c4 100644 --- a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.cs +++ b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.cs @@ -18,8 +18,7 @@ namespace System.DirectoryServices.Protocols UTF8Encoding utf8Encoder = new UTF8Encoding(); byte[] encodingResult = null; // value is allowed to be null in certain scenario, so if it is null, just set it to empty array. - if (value == null) - value = Array.Empty(); + value ??= Array.Empty(); Debug.WriteLine("Begin encoding\n"); 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 0165343..c6dd1c6 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchema.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchema.cs @@ -189,10 +189,7 @@ namespace System.DirectoryServices.ActiveDirectory // refresh the schema on the client // bind to the abstract schema - if (_abstractSchemaEntry == null) - { - _abstractSchemaEntry = directoryEntryMgr.GetCachedDirectoryEntry("Schema"); - } + _abstractSchemaEntry ??= directoryEntryMgr.GetCachedDirectoryEntry("Schema"); _abstractSchemaEntry.RefreshCache(); } catch (COMException e) @@ -404,11 +401,7 @@ namespace System.DirectoryServices.ActiveDirectory get { CheckIfDisposed(); - if (_cachedSchemaRoleOwner == null) - { - _cachedSchemaRoleOwner = GetSchemaRoleOwner(); - } - return _cachedSchemaRoleOwner; + return _cachedSchemaRoleOwner ??= GetSchemaRoleOwner(); } } 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 2f4a873..e46383f 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClass.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClass.cs @@ -281,10 +281,7 @@ namespace System.DirectoryServices.ActiveDirectory try { // create a new directory entry for this class - if (_schemaEntry == null) - { - _schemaEntry = DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext); - } + _schemaEntry ??= DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext); // this will create the class and set the CN value string rdn = "CN=" + _commonName; @@ -1119,10 +1116,7 @@ namespace System.DirectoryServices.ActiveDirectory { if (!_propertiesFromSchemaContainerInitialized) { - if (_schemaEntry == null) - { - _schemaEntry = DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext); - } + _schemaEntry ??= DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext); _propertyValuesFromServer = GetPropertiesFromSchemaContainer(_context, _schemaEntry, (_isDefunctOnServer) ? _commonName! : _ldapDisplayName, _isDefunctOnServer); _propertiesFromSchemaContainerInitialized = true; @@ -1301,10 +1295,7 @@ namespace System.DirectoryServices.ActiveDirectory return classes; } - if (_schemaEntry == null) - { - _schemaEntry = DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext); - } + _schemaEntry ??= DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext); // constructing the filter StringBuilder str = new StringBuilder(100); @@ -1379,10 +1370,7 @@ namespace System.DirectoryServices.ActiveDirectory return properties; } - if (_schemaEntry == null) - { - _schemaEntry = DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext); - } + _schemaEntry ??= DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext); // constructing the filter StringBuilder str = new StringBuilder(100); 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 7022619..3533048 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClassCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClassCollection.cs @@ -243,10 +243,7 @@ namespace System.DirectoryServices.ActiveDirectory { if (_isBound) { - if (_classEntry == null) - { - _classEntry = _schemaClass.GetSchemaClassDirectoryEntry(); - } + _classEntry ??= _schemaClass.GetSchemaClassDirectoryEntry(); try { @@ -268,10 +265,7 @@ namespace System.DirectoryServices.ActiveDirectory { if (_isBound) { - if (_classEntry == null) - { - _classEntry = _schemaClass.GetSchemaClassDirectoryEntry(); - } + _classEntry ??= _schemaClass.GetSchemaClassDirectoryEntry(); try { @@ -290,10 +284,7 @@ namespace System.DirectoryServices.ActiveDirectory { if (_isBound) { - if (_classEntry == null) - { - _classEntry = _schemaClass.GetSchemaClassDirectoryEntry(); - } + _classEntry ??= _schemaClass.GetSchemaClassDirectoryEntry(); // because this collection can contain values from the superior classes, // these values would not exist in the classEntry diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaProperty.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaProperty.cs index fb6efff..07626c6 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaProperty.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaProperty.cs @@ -316,10 +316,7 @@ namespace System.DirectoryServices.ActiveDirectory try { // create a new directory entry for this class - if (_schemaEntry == null) - { - _schemaEntry = DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext); - } + _schemaEntry ??= DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext); // this will create the class and set the CN value string rdn = "CN=" + _commonName; @@ -987,10 +984,7 @@ namespace System.DirectoryServices.ActiveDirectory try { - if (_schemaEntry == null) - { - _schemaEntry = DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext); - } + _schemaEntry ??= DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext); string filter = "(&(" + PropertyManager.ObjectCategory + "=attributeSchema)" + "(" + PropertyManager.LinkID + "=" + linkIdToSearch + "))"; ReadOnlyActiveDirectorySchemaPropertyCollection linkedProperties = ActiveDirectorySchema.GetAllProperties(_context, _schemaEntry, filter); @@ -1155,10 +1149,7 @@ namespace System.DirectoryServices.ActiveDirectory { if (!_propertiesFromSchemaContainerInitialized) { - if (_schemaEntry == null) - { - _schemaEntry = DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext); - } + _schemaEntry ??= DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext); _propertyValuesFromServer = GetPropertiesFromSchemaContainer(_context, _schemaEntry, (_isDefunctOnServer) ? _commonName! : _ldapDisplayName, _isDefunctOnServer); _propertiesFromSchemaContainerInitialized = true; diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaPropertyCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaPropertyCollection.cs index a1a139d..c947713 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaPropertyCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaPropertyCollection.cs @@ -256,10 +256,7 @@ namespace System.DirectoryServices.ActiveDirectory { if (_isBound) { - if (_classEntry == null) - { - _classEntry = _schemaClass.GetSchemaClassDirectoryEntry(); - } + _classEntry ??= _schemaClass.GetSchemaClassDirectoryEntry(); try { @@ -281,10 +278,7 @@ namespace System.DirectoryServices.ActiveDirectory { if (_isBound) { - if (_classEntry == null) - { - _classEntry = _schemaClass.GetSchemaClassDirectoryEntry(); - } + _classEntry ??= _schemaClass.GetSchemaClassDirectoryEntry(); try { @@ -303,10 +297,7 @@ namespace System.DirectoryServices.ActiveDirectory { if (_isBound) { - if (_classEntry == null) - { - _classEntry = _schemaClass.GetSchemaClassDirectoryEntry(); - } + _classEntry ??= _schemaClass.GetSchemaClassDirectoryEntry(); // because this collection can contain values from the superior classes, // these values would not exist in the classEntry 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 689fda3..47675bc 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ConfigSet.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ConfigSet.cs @@ -280,11 +280,7 @@ namespace System.DirectoryServices.ActiveDirectory get { CheckIfDisposed(); - if (_cachedSites == null) - { - _cachedSites = new ReadOnlySiteCollection(GetSites()); - } - return _cachedSites; + return _cachedSites ??= new ReadOnlySiteCollection(GetSites()); } } @@ -293,11 +289,7 @@ namespace System.DirectoryServices.ActiveDirectory get { CheckIfDisposed(); - if (_cachedADAMInstances == null) - { - _cachedADAMInstances = FindAllAdamInstances(); - } - return _cachedADAMInstances; + return _cachedADAMInstances ??= FindAllAdamInstances(); } } @@ -306,11 +298,7 @@ namespace System.DirectoryServices.ActiveDirectory get { CheckIfDisposed(); - if (_cachedApplicationPartitions == null) - { - _cachedApplicationPartitions = new ApplicationPartitionCollection(GetApplicationPartitions()); - } - return _cachedApplicationPartitions; + return _cachedApplicationPartitions ??= new ApplicationPartitionCollection(GetApplicationPartitions()); } } @@ -339,11 +327,7 @@ namespace System.DirectoryServices.ActiveDirectory get { CheckIfDisposed(); - if (_cachedSchemaRoleOwner == null) - { - _cachedSchemaRoleOwner = GetRoleOwner(AdamRole.SchemaRole); - } - return _cachedSchemaRoleOwner; + return _cachedSchemaRoleOwner ??= GetRoleOwner(AdamRole.SchemaRole); } } @@ -352,11 +336,7 @@ namespace System.DirectoryServices.ActiveDirectory get { CheckIfDisposed(); - if (_cachedNamingRoleOwner == null) - { - _cachedNamingRoleOwner = GetRoleOwner(AdamRole.NamingRole); - } - return _cachedNamingRoleOwner; + return _cachedNamingRoleOwner ??= GetRoleOwner(AdamRole.NamingRole); } } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryEntryManager.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryEntryManager.cs index 89c1c6b..7817e52 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryEntryManager.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryEntryManager.cs @@ -154,10 +154,7 @@ namespace System.DirectoryServices.ActiveDirectory private DirectoryEntry GetNewDirectoryEntry(string dn) { - if (_bindingPrefix == null) - { - _bindingPrefix = "LDAP://" + _context.GetServerName() + "/"; - } + _bindingPrefix ??= "LDAP://" + _context.GetServerName() + "/"; _pathCracker.Set(dn, NativeComInterfaces.ADS_SETTYPE_DN); string escapedDN = _pathCracker.Retrieve(NativeComInterfaces.ADS_FORMAT_X500_DN); 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 b208550..1e9b45c 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServer.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServer.cs @@ -196,11 +196,7 @@ namespace System.DirectoryServices.ActiveDirectory get { CheckIfDisposed(); - if (cachedPartitions == null) - { - cachedPartitions = new ReadOnlyStringCollection(GetPartitions()); - } - return cachedPartitions; + return cachedPartitions ??= new ReadOnlyStringCollection(GetPartitions()); } } 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 e828ec3..db1b624 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Domain.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Domain.cs @@ -858,11 +858,7 @@ namespace System.DirectoryServices.ActiveDirectory get { CheckIfDisposed(); - if (_cachedDomainControllers == null) - { - _cachedDomainControllers = FindAllDomainControllers(); - } - return _cachedDomainControllers; + return _cachedDomainControllers ??= FindAllDomainControllers(); } } @@ -871,11 +867,7 @@ namespace System.DirectoryServices.ActiveDirectory get { CheckIfDisposed(); - if (_cachedChildren == null) - { - _cachedChildren = new DomainCollection(GetChildDomains()); - } - return _cachedChildren; + return _cachedChildren ??= new DomainCollection(GetChildDomains()); } } @@ -937,11 +929,7 @@ namespace System.DirectoryServices.ActiveDirectory get { CheckIfDisposed(); - if (_cachedRidRoleOwner == null) - { - _cachedRidRoleOwner = GetRoleOwner(ActiveDirectoryRole.RidRole); - } - return _cachedRidRoleOwner; + return _cachedRidRoleOwner ??= GetRoleOwner(ActiveDirectoryRole.RidRole); } } @@ -950,11 +938,7 @@ namespace System.DirectoryServices.ActiveDirectory get { CheckIfDisposed(); - if (_cachedInfrastructureRoleOwner == null) - { - _cachedInfrastructureRoleOwner = GetRoleOwner(ActiveDirectoryRole.InfrastructureRole); - } - return _cachedInfrastructureRoleOwner; + return _cachedInfrastructureRoleOwner ??= GetRoleOwner(ActiveDirectoryRole.InfrastructureRole); } } 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 6591bd0..2a5be2a 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainController.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainController.cs @@ -712,11 +712,7 @@ namespace System.DirectoryServices.ActiveDirectory get { CheckIfDisposed(); - if (_cachedRoles == null) - { - _cachedRoles = new ActiveDirectoryRoleCollection(GetRoles()); - } - return _cachedRoles; + return _cachedRoles ??= new ActiveDirectoryRoleCollection(GetRoles()); } } @@ -1005,10 +1001,7 @@ namespace System.DirectoryServices.ActiveDirectory throw new ArgumentException(SR.InvalidFlags, nameof(flag)); } - if (domainName == null) - { - domainName = DirectoryContext.GetLoggedOnDomain(); - } + domainName ??= DirectoryContext.GetLoggedOnDomain(); // call DsGetDcName errorCode = Locator.DsGetDcNameWrapper(null, domainName, siteName, (long)flag | (long)PrivateLocatorFlags.DirectoryServicesRequired, out domainControllerInfo); 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 94df08c..19547e4 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Forest.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Forest.cs @@ -649,11 +649,7 @@ namespace System.DirectoryServices.ActiveDirectory get { CheckIfDisposed(); - if (_cachedSites == null) - { - _cachedSites = new ReadOnlySiteCollection(GetSites()); - } - return _cachedSites; + return _cachedSites ??= new ReadOnlySiteCollection(GetSites()); } } @@ -662,11 +658,7 @@ namespace System.DirectoryServices.ActiveDirectory get { CheckIfDisposed(); - if (_cachedDomains == null) - { - _cachedDomains = new DomainCollection(GetDomains()); - } - return _cachedDomains; + return _cachedDomains ??= new DomainCollection(GetDomains()); } } @@ -675,11 +667,7 @@ namespace System.DirectoryServices.ActiveDirectory get { CheckIfDisposed(); - if (_cachedGlobalCatalogs == null) - { - _cachedGlobalCatalogs = FindAllGlobalCatalogs(); - } - return _cachedGlobalCatalogs; + return _cachedGlobalCatalogs ??= FindAllGlobalCatalogs(); } } @@ -688,11 +676,7 @@ namespace System.DirectoryServices.ActiveDirectory get { CheckIfDisposed(); - if (_cachedApplicationPartitions == null) - { - _cachedApplicationPartitions = new ApplicationPartitionCollection(GetApplicationPartitions()); - } - return _cachedApplicationPartitions; + return _cachedApplicationPartitions ??= new ApplicationPartitionCollection(GetApplicationPartitions()); } } @@ -765,11 +749,7 @@ namespace System.DirectoryServices.ActiveDirectory get { CheckIfDisposed(); - if (_cachedSchemaRoleOwner == null) - { - _cachedSchemaRoleOwner = GetRoleOwner(ActiveDirectoryRole.SchemaRole); - } - return _cachedSchemaRoleOwner; + return _cachedSchemaRoleOwner ??= GetRoleOwner(ActiveDirectoryRole.SchemaRole); } } @@ -778,11 +758,7 @@ namespace System.DirectoryServices.ActiveDirectory get { CheckIfDisposed(); - if (_cachedNamingRoleOwner == null) - { - _cachedNamingRoleOwner = GetRoleOwner(ActiveDirectoryRole.NamingRole); - } - return _cachedNamingRoleOwner; + return _cachedNamingRoleOwner ??= GetRoleOwner(ActiveDirectoryRole.NamingRole); } } 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 9918903..01c3958 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyStringCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyStringCollection.cs @@ -11,12 +11,7 @@ namespace System.DirectoryServices.ActiveDirectory internal ReadOnlyStringCollection(ArrayList values) { - if (values == null) - { - values = new ArrayList(); - } - - this.InnerList.AddRange(values); + this.InnerList.AddRange(values ?? new ArrayList()); } public string this[int index] { diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/Design/DirectoryEntryConverter.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/Design/DirectoryEntryConverter.cs index ee3e353..5ab69ec 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/Design/DirectoryEntryConverter.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/Design/DirectoryEntryConverter.cs @@ -62,14 +62,8 @@ namespace System.DirectoryServices.Design return base.ConvertTo(context, culture, value, destinationType!); } - public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext? context) - { - if (s_values == null) - { - s_values = new StandardValuesCollection(new object?[] { null }); - } - return s_values; - } + public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext? context) => + s_values ??= new StandardValuesCollection(new object?[] { null }); internal static DirectoryEntry? GetFromCache(string path) { diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntries.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntries.cs index 01ce522..71d53ef 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntries.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntries.cs @@ -126,10 +126,7 @@ namespace System.DirectoryServices if (_enumVariant == null) throw new InvalidOperationException(SR.DSNoCurrentChild); - if (_currentEntry == null) - _currentEntry = new DirectoryEntry(_enumVariant.GetValue(), _container.UsePropertyCache, _container.GetUsername(), _container.GetPassword(), _container.AuthenticationType); - - return _currentEntry; + return _currentEntry ??= new DirectoryEntry(_enumVariant.GetValue(), _container.UsePropertyCache, _container.GetUsername(), _container.GetPassword(), _container.AuthenticationType); } } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntry.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntry.cs index 7815049..d554e62 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntry.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntry.cs @@ -340,8 +340,7 @@ namespace System.DirectoryServices get => _path; set { - if (value == null) - value = ""; + value ??= ""; if (System.DirectoryServices.ActiveDirectory.Utils.Compare(_path, value) == 0) return; @@ -354,18 +353,8 @@ namespace System.DirectoryServices /// /// Gets a of properties set on this object. /// - public PropertyCollection Properties - { - get - { - if (_propertyCollection == null) - { - _propertyCollection = new PropertyCollection(this); - } - - return _propertyCollection; - } - } + public PropertyCollection Properties => + _propertyCollection ??= new PropertyCollection(this); /// /// Gets the name of the schema used for this @@ -446,10 +435,7 @@ namespace System.DirectoryServices _passwordIsNull = true; } - if (value == null) - _userNameIsNull = true; - else - _userNameIsNull = false; + _userNameIsNull = value == null; _credentials.UserName = value; diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectorySearcher.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectorySearcher.cs index 7548578..846fffa 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectorySearcher.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectorySearcher.cs @@ -233,17 +233,8 @@ namespace System.DirectoryServices /// [Editor("System.Windows.Forms.Design.StringCollectionEditor, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] - public StringCollection PropertiesToLoad - { - get - { - if (_propertiesToLoad == null) - { - _propertiesToLoad = new StringCollection(); - } - return _propertiesToLoad; - } - } + public StringCollection PropertiesToLoad => + _propertiesToLoad ??= new StringCollection(); /// /// Gets or sets how referrals are chased. @@ -413,8 +404,7 @@ namespace System.DirectoryServices get => _attributeScopeQuery; set { - if (value == null) - value = ""; + value ??= ""; // user explicitly set AttributeScopeQuery and value is not null or empty string if (value.Length != 0) diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/SearchResultCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/SearchResultCollection.cs index 63f1230..4711b60 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/SearchResultCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/SearchResultCollection.cs @@ -64,17 +64,8 @@ namespace System.DirectoryServices } } - internal UnsafeNativeMethods.IDirectorySearch SearchObject - { - get - { - if (_searchObject == null) - { - _searchObject = (UnsafeNativeMethods.IDirectorySearch)_rootEntry.AdsObject; // get it only once - } - return _searchObject; - } - } + internal UnsafeNativeMethods.IDirectorySearch SearchObject => + _searchObject ??= (UnsafeNativeMethods.IDirectorySearch)_rootEntry.AdsObject; // get it only once /// /// Gets the handle returned by IDirectorySearch::ExecuteSearch, which was called @@ -257,10 +248,7 @@ namespace System.DirectoryServices if (!_initialized || _eof) throw new InvalidOperationException(SR.DSNoCurrentEntry); - if (_currentResult == null) - _currentResult = GetCurrentResult(); - - return _currentResult; + return _currentResult ??= GetCurrentResult(); } } diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/ColorConverter.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/ColorConverter.cs index 33433e2..d3de084 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/ColorConverter.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/ColorConverter.cs @@ -134,9 +134,7 @@ namespace System.Drawing { obj = GetNamedColor(text); if (obj == null) { - if (culture == null) { - culture = CultureInfo.CurrentCulture; - } + culture ??= CultureInfo.CurrentCulture; char sep = culture.TextInfo.ListSeparator[0]; bool tryMappingToKnownColor = true; @@ -252,9 +250,7 @@ namespace System.Drawing { return "'" + c.Name + "'"; } else { - if (culture == null) { - culture = CultureInfo.CurrentCulture; - } + culture ??= CultureInfo.CurrentCulture; string sep = culture.TextInfo.ListSeparator + " "; TypeConverter intConverter = TypeDescriptor.GetConverter(typeof(int)); string[] args; diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/FontConverter.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/FontConverter.cs index 350eb93..1e2125a 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/FontConverter.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/FontConverter.cs @@ -33,10 +33,7 @@ namespace System.Drawing { if (destinationType == typeof(string)) { - if (culture == null) - { - culture = CultureInfo.CurrentCulture; - } + culture ??= CultureInfo.CurrentCulture; ValueStringBuilder sb = default; sb.Append(font.Name); @@ -120,10 +117,7 @@ namespace System.Drawing return null; } - if (culture == null) - { - culture = CultureInfo.CurrentCulture; - } + culture ??= CultureInfo.CurrentCulture; char separator = culture.TextInfo.ListSeparator[0]; // For vi-VN: ',' string fontName = font; // start with the assumption that only the font name was provided. @@ -355,8 +349,7 @@ namespace System.Drawing } // font family not found in private fonts also - if (fontFamily == null) - fontFamily = FontFamily.GenericSansSerif; + fontFamily ??= FontFamily.GenericSansSerif; } return new Font(fontFamily, size, style, unit, charSet, vertical); diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Image.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Image.cs index c146909..129c9bf 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Image.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Image.cs @@ -292,10 +292,7 @@ namespace System.Drawing { ArgumentNullException.ThrowIfNull(format); - ImageCodecInfo? codec = format.FindEncoder(); - - if (codec == null) - codec = ImageFormat.Png.FindEncoder()!; + ImageCodecInfo codec = format.FindEncoder() ?? ImageFormat.Png.FindEncoder()!; Save(filename, codec, null); } diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/ImageAnimator.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/ImageAnimator.cs index 48e0f1c..e0b8933 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/ImageAnimator.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/ImageAnimator.cs @@ -250,10 +250,7 @@ namespace System.Drawing { // Construct the image array // - if (s_imageInfoList == null) - { - s_imageInfoList = new List(); - } + s_imageInfoList ??= new List(); // Add the new image // diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Internal/SystemColorTracker.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Internal/SystemColorTracker.cs index 150ba75..c8a16f1 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Internal/SystemColorTracker.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Internal/SystemColorTracker.cs @@ -48,7 +48,9 @@ namespace System.Drawing.Internal // COM+ takes forever to Finalize() weak references, so it pays to reuse them. if (list[index] == null) + { list[index] = new WeakReference(obj); + } else { Debug.Assert(list[index].Target == null, $"Trying to reuse a weak reference that isn't broken yet: list[{index}], length = {list.Length}"); diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/PointConverter.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/PointConverter.cs index 8cde405..04d64fe 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/PointConverter.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/PointConverter.cs @@ -66,9 +66,7 @@ namespace System.Drawing { // Parse 2 integer values. // - if (culture == null) { - culture = CultureInfo.CurrentCulture; - } + culture ??= CultureInfo.CurrentCulture; char sep = culture.TextInfo.ListSeparator[0]; string[] tokens = text.Split(sep); int[] values = new int[tokens.Length]; @@ -109,9 +107,7 @@ namespace System.Drawing { if (destinationType == typeof(string)) { Point pt = (Point)value; - if (culture == null) { - culture = CultureInfo.CurrentCulture; - } + culture ??= CultureInfo.CurrentCulture; string sep = culture.TextInfo.ListSeparator + " "; TypeConverter intConverter = TypeDescriptor.GetConverter(typeof(int)); string[] args = new string[2]; diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/MarginsConverter.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/MarginsConverter.cs index 42266a7..6d5bc85 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/MarginsConverter.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/MarginsConverter.cs @@ -57,10 +57,7 @@ namespace System.Drawing.Printing else { // Parse 4 integer values. - if (culture == null) - { - culture = CultureInfo.CurrentCulture; - } + culture ??= CultureInfo.CurrentCulture; char sep = culture.TextInfo.ListSeparator[0]; string[] tokens = text.Split(sep); int[] values = new int[tokens.Length]; @@ -99,10 +96,7 @@ namespace System.Drawing.Printing { if (destinationType == typeof(string)) { - if (culture == null) - { - culture = CultureInfo.CurrentCulture; - } + culture ??= CultureInfo.CurrentCulture; string sep = culture.TextInfo.ListSeparator + " "; TypeConverter intConverter = GetIntConverter(); string?[] args = new string[4]; diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PageSettings.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PageSettings.cs index c94f82a..0c043e5 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PageSettings.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PageSettings.cs @@ -255,13 +255,8 @@ namespace System.Drawing.Printing /// public PrinterSettings PrinterSettings { - get { return printerSettings; } - set - { - if (value == null) - value = new PrinterSettings(); - printerSettings = value; - } + get => printerSettings; + set => printerSettings = value ?? new PrinterSettings(); } /// diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrintDocument.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrintDocument.cs index eaa7307..c315870 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrintDocument.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrintDocument.cs @@ -47,9 +47,7 @@ namespace System.Drawing.Printing get { return _defaultPageSettings; } set { - if (value == null) - value = new PageSettings(); - _defaultPageSettings = value; + _defaultPageSettings = value ?? new PageSettings(); _userSetPageSettings = true; } } @@ -64,14 +62,8 @@ namespace System.Drawing.Printing ] public string DocumentName { - get { return _documentName; } - - set - { - if (value == null) - value = ""; - _documentName = value; - } + get => _documentName; + set => _documentName = value ?? ""; } // If true, positions the origin of the graphics object @@ -105,18 +97,8 @@ namespace System.Drawing.Printing ] public PrintController PrintController { - get - { - if (_printController == null) - { - _printController = new StandardPrintController(); - } - return _printController; - } - set - { - _printController = value; - } + get => _printController ??= new StandardPrintController(); + set => _printController = value; } /// @@ -132,8 +114,7 @@ namespace System.Drawing.Printing get { return _printerSettings; } set { - if (value == null) - value = new PrinterSettings(); + value ??= new PrinterSettings(); _printerSettings = value; // reset the PageSettings that match the PrinterSettings only if we have created the defaultPageSettings.. if (!_userSetPageSettings) diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.cs index a4de17e..933589d 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.cs @@ -1236,8 +1236,7 @@ namespace System.Drawing.Printing // Write null terminated string, return length of string in characters (including null) private static short WriteOneDEVNAME(string str, IntPtr bufferStart, int index) { - if (str == null) - str = ""; + str ??= ""; IntPtr address = (IntPtr)(checked((long)bufferStart + index * Marshal.SystemDefaultCharSize)); char[] data = str.ToCharArray(); diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/QueryPageSettingsEventArgs.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/QueryPageSettingsEventArgs.cs index 3ae2152..ea8f3e5 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/QueryPageSettingsEventArgs.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/QueryPageSettingsEventArgs.cs @@ -39,10 +39,7 @@ namespace System.Drawing.Printing } set { - if (value == null) - { - value = new PageSettings(); - } + value ??= new PageSettings(); _pageSettings = value; PageSettingsChanged = true; } diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/RectangleConverter.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/RectangleConverter.cs index f1db851..1924f42 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/RectangleConverter.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/RectangleConverter.cs @@ -66,9 +66,7 @@ namespace System.Drawing { // Parse 4 integer values. // - if (culture == null) { - culture = CultureInfo.CurrentCulture; - } + culture ??= CultureInfo.CurrentCulture; char sep = culture.TextInfo.ListSeparator[0]; string[] tokens = text.Split(sep); int[] values = new int[tokens.Length]; @@ -109,9 +107,7 @@ namespace System.Drawing { if (destinationType == typeof(string)) { Rectangle rect = (Rectangle)value; - if (culture == null) { - culture = CultureInfo.CurrentCulture; - } + culture ??= CultureInfo.CurrentCulture; string sep = culture.TextInfo.ListSeparator + " "; TypeConverter intConverter = TypeDescriptor.GetConverter(typeof(int)); string[] args = new string[4]; diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/SizeConverter.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/SizeConverter.cs index 004d29a..2b91a3b 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/SizeConverter.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/SizeConverter.cs @@ -66,9 +66,7 @@ namespace System.Drawing { // Parse 2 integer values. // - if (culture == null) { - culture = CultureInfo.CurrentCulture; - } + culture ??= CultureInfo.CurrentCulture; char sep = culture.TextInfo.ListSeparator[0]; string[] tokens = text.Split(sep); int[] values = new int[tokens.Length]; @@ -109,19 +107,17 @@ namespace System.Drawing { if (destinationType == typeof(string)) { Size size = (Size)value; - if (culture == null) { - culture = CultureInfo.CurrentCulture; - } + culture ??= CultureInfo.CurrentCulture; string sep = culture.TextInfo.ListSeparator + " "; TypeConverter intConverter = TypeDescriptor.GetConverter(typeof(int)); - string[] args = new string[2]; - int nArg = 0; // Note: ConvertToString will raise exception if value cannot be converted. + return + intConverter.ConvertToString(context, culture, size.Width) + + sep + + intConverter.ConvertToString(context, culture, size.Height); args[nArg++] = intConverter.ConvertToString(context, culture, size.Width); args[nArg++] = intConverter.ConvertToString(context, culture, size.Height); - - return string.Join(sep, args); } if (destinationType == typeof(InstanceDescriptor)) { Size size = (Size)value; diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/SystemBrushes.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/SystemBrushes.cs index 93f74c7..868531c 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/SystemBrushes.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/SystemBrushes.cs @@ -75,12 +75,7 @@ namespace System.Drawing Debug.Assert(idx >= 0 && idx < systemBrushes.Length, "System colors have been added but our system color array has not been expanded."); - if (systemBrushes[idx] == null) - { - systemBrushes[idx] = new SolidBrush(c, true); - } - - return systemBrushes[idx]; + return systemBrushes[idx] ??= new SolidBrush(c, true); } } } diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/SystemFonts.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/SystemFonts.cs index c250081..60476b1 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/SystemFonts.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/SystemFonts.cs @@ -211,10 +211,7 @@ namespace System.Drawing } // Use GenericSansSerif as a last resort - this will always work. - if (defaultFont == null) - { - defaultFont = new Font(FontFamily.GenericSansSerif, 8); - } + defaultFont ??= new Font(FontFamily.GenericSansSerif, 8); if (defaultFont.Unit != GraphicsUnit.Point) { diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/SystemPens.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/SystemPens.cs index c43553f..52a3dc3 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/SystemPens.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/SystemPens.cs @@ -76,12 +76,7 @@ namespace System.Drawing idx--; Debug.Assert(idx >= 0 && idx < systemPens.Length, "System colors have been added but our system color array has not been expanded."); - if (systemPens[idx] == null) - { - systemPens[idx] = new Pen(c, true); - } - - return systemPens[idx]; + return systemPens[idx] ??= new Pen(c, true); } } } diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/ToolboxBitmapAttribute.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/ToolboxBitmapAttribute.cs index be2a5c7d..0f086e9 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/ToolboxBitmapAttribute.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/ToolboxBitmapAttribute.cs @@ -88,20 +88,8 @@ namespace System.Drawing { if ((large && _largeImage == null) || (!large && _smallImage == null)) { - Image? img; - if (large) - { - img = _largeImage; - } - else - { - img = _smallImage; - } - - if (img == null) - { - img = GetImageFromResource(type, imgName, large); - } + Image? img = large ? _largeImage : _smallImage; + img ??= GetImageFromResource(type, imgName, large); // last resort for large images. if (large && _largeImage == null && _smallImage != null) diff --git a/src/libraries/System.Drawing.Common/src/misc/GDI/DeviceContext.cs b/src/libraries/System.Drawing.Common/src/misc/GDI/DeviceContext.cs index b64f7c4..35290aa 100644 --- a/src/libraries/System.Drawing.Common/src/misc/GDI/DeviceContext.cs +++ b/src/libraries/System.Drawing.Common/src/misc/GDI/DeviceContext.cs @@ -241,10 +241,7 @@ namespace System.Drawing.Internal HandleRef hdc = new HandleRef(this, _hDC); int state = Interop.Gdi32.SaveDC(hdc); - if (_contextStack == null) - { - _contextStack = new Stack(); - } + _contextStack ??= new Stack(); GraphicsState g = new GraphicsState(); g.hBitmap = _hCurrentBmp; diff --git a/src/libraries/System.Drawing.Common/src/misc/GDI/DeviceContexts.cs b/src/libraries/System.Drawing.Common/src/misc/GDI/DeviceContexts.cs index d8a4dea..a9169ae 100644 --- a/src/libraries/System.Drawing.Common/src/misc/GDI/DeviceContexts.cs +++ b/src/libraries/System.Drawing.Common/src/misc/GDI/DeviceContexts.cs @@ -18,18 +18,15 @@ namespace System.Drawing.Internal /// internal static void AddDeviceContext(DeviceContext dc) { - if (t_activeDeviceContexts == null) + ClientUtils.WeakRefCollection wrc = t_activeDeviceContexts ??= new ClientUtils.WeakRefCollection() { - t_activeDeviceContexts = new ClientUtils.WeakRefCollection() - { - RefCheckThreshold = 20 - }; - } + RefCheckThreshold = 20 + }; - if (!t_activeDeviceContexts.Contains(dc)) + if (!wrc.Contains(dc)) { dc.Disposing += new EventHandler(OnDcDisposing); - t_activeDeviceContexts.Add(dc); + wrc.Add(dc); } } diff --git a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.BitString.cs b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.BitString.cs index e36dd61..f1914c6 100644 --- a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.BitString.cs +++ b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.BitString.cs @@ -541,10 +541,7 @@ namespace System.Formats.Asn1 throw new AsnContentException(SR.ContentException_InvalidUnderCerOrDer_TryBer); } - if (readerStack == null) - { - readerStack = new Stack<(int, int, bool, int)>(); - } + readerStack ??= new Stack<(int, int, bool, int)>(); if (!source.Overlaps(cur, out int curOffset)) { diff --git a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.OctetString.cs b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.OctetString.cs index db7bbee..19dc0e1 100644 --- a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.OctetString.cs +++ b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.OctetString.cs @@ -406,10 +406,7 @@ namespace System.Formats.Asn1 throw new AsnContentException(SR.ContentException_InvalidUnderCerOrDer_TryBer); } - if (readerStack == null) - { - readerStack = new Stack<(int, int, bool, int)>(); - } + readerStack ??= new Stack<(int, int, bool, int)>(); if (!source.Overlaps(cur, out int curOffset)) { 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 34343ad..d7052b7 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 @@ -449,10 +449,7 @@ namespace System.Formats.Asn1 private Scope PushTag(Asn1Tag tag, UniversalTagNumber tagType) { - if (_nestingStack == null) - { - _nestingStack = new Stack(); - } + _nestingStack ??= new Stack(); Debug.Assert(tag.IsConstructed); WriteTag(tag); 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 c5f3773..cca0747 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 @@ -430,9 +430,13 @@ namespace System.IO.Packaging // Generate an ID if id is null. Throw exception if neither null nor a valid unique xsd:ID. if (id == null) + { id = GenerateUniqueRelationshipId(); + } else + { ValidateUniqueRelationshipId(id); + } // create and add PackageRelationship relationship = new PackageRelationship(_package, _sourcePart, targetUri, targetMode, relationshipType, id); 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 f191c40..5841cb6 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 @@ -714,28 +714,10 @@ namespace System.IO.Packaging } //Returns the normalized string for the part uri. - internal string NormalizedPartUriString - { - get - { - if (_normalizedPartUriString == null) - _normalizedPartUriString = GetNormalizedPartUriString(); - - return _normalizedPartUriString; - } - } + internal string NormalizedPartUriString => _normalizedPartUriString ??= GetNormalizedPartUriString(); //Returns the normalized part uri - internal ValidatedPartUri NormalizedPartUri - { - get - { - if (_normalizedPartUri == null) - _normalizedPartUri = GetNormalizedPartUri(); - - return _normalizedPartUri; - } - } + internal ValidatedPartUri NormalizedPartUri => _normalizedPartUri ??= GetNormalizedPartUri(); //Returns true, if the original string passed to create //this object was normalized 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 3d1c537..ec906ee 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 @@ -69,9 +69,7 @@ namespace System.IO.Packaging { ThrowIfObjectDisposed(); - if (_packageProperties == null) - _packageProperties = new PartBasedPackageProperties(this); - return _packageProperties; + return _packageProperties ??= new PartBasedPackageProperties(this); } } @@ -1001,10 +999,7 @@ namespace System.IO.Packaging private void EnsureRelationships() { // once per package - if (_relationships == null) - { - _relationships = new InternalRelationshipCollection(this); - } + _relationships ??= new InternalRelationshipCollection(this); } //Delete All Package-level Relationships 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 55cdbf0..7ce1382 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 @@ -113,9 +113,13 @@ namespace System.IO.Packaging _container = package; if (contentType == null) + { _contentType = null; + } else + { _contentType = new ContentType(contentType); + } _requestedStreams = null; _compressionOption = compressionOption; @@ -333,8 +337,7 @@ namespace System.IO.Packaging Debug.Assert(!IsStreamClosed(s)); //Lazy init - if (_requestedStreams == null) - _requestedStreams = new List(); //Default capacity is 4 + _requestedStreams ??= new List(); //Default capacity is 4 //Delete all the closed streams from the _requestedStreams list. //Each time a new stream is handed out, we go through the list diff --git a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/XmlCompatibilityReader.cs b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/XmlCompatibilityReader.cs index db69f44..1695a4f 100644 --- a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/XmlCompatibilityReader.cs +++ b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/XmlCompatibilityReader.cs @@ -817,8 +817,7 @@ namespace System.IO.Packaging /// private void AddSubsumingNamespace(string namespaceName) { - if (_subsumingNamespaces == null) - _subsumingNamespaces = new Dictionary(); + _subsumingNamespaces ??= new Dictionary(); _subsumingNamespaces[namespaceName] = null; } @@ -844,8 +843,7 @@ namespace System.IO.Packaging /// private void AddKnownNamespace(string namespaceName) { - if (_knownNamespaces == null) - _knownNamespaces = new Dictionary(); + _knownNamespaces ??= new Dictionary(); _knownNamespaces[namespaceName] = null; } @@ -1422,125 +1420,25 @@ namespace System.IO.Packaging } } - private string AlternateContent - { - get - { - if (_alternateContent == null) - { - _alternateContent = Reader.NameTable.Add("AlternateContent"); - } - return _alternateContent; - } - } + private string AlternateContent => _alternateContent ??= Reader.NameTable.Add("AlternateContent"); - private string Choice - { - get - { - if (_choice == null) - { - _choice = Reader.NameTable.Add("Choice"); - } - return _choice; - } - } + private string Choice => _choice ??= Reader.NameTable.Add("Choice"); - private string Fallback - { - get - { - if (_fallback == null) - { - _fallback = Reader.NameTable.Add("Fallback"); - } - return _fallback; - } - } + private string Fallback => _fallback ??= Reader.NameTable.Add("Fallback"); - private string Requires - { - get - { - if (_requires == null) - { - _requires = Reader.NameTable.Add("Requires"); - } - return _requires; - } - } + private string Requires => _requires ??= Reader.NameTable.Add("Requires"); - private string Ignorable - { - get - { - if (_ignorable == null) - { - _ignorable = Reader.NameTable.Add("Ignorable"); - } - return _ignorable; - } - } + private string Ignorable => _ignorable ??= Reader.NameTable.Add("Ignorable"); - private string MustUnderstand - { - get - { - if (_mustUnderstand == null) - { - _mustUnderstand = Reader.NameTable.Add("MustUnderstand"); - } - return _mustUnderstand; - } - } + private string MustUnderstand => _mustUnderstand ??= Reader.NameTable.Add("MustUnderstand"); - private string ProcessContent - { - get - { - if (_processContent == null) - { - _processContent = Reader.NameTable.Add("ProcessContent"); - } - return _processContent; - } - } + private string ProcessContent => _processContent ??= Reader.NameTable.Add("ProcessContent"); - private string PreserveElements - { - get - { - if (_preserveElements == null) - { - _preserveElements = Reader.NameTable.Add("PreserveElements"); - } - return _preserveElements; - } - } + private string PreserveElements => _preserveElements ??= Reader.NameTable.Add("PreserveElements"); - private string PreserveAttributes - { - get - { - if (_preserveAttributes == null) - { - _preserveAttributes = Reader.NameTable.Add("PreserveAttributes"); - } - return _preserveAttributes; - } - } + private string PreserveAttributes => _preserveAttributes ??= Reader.NameTable.Add("PreserveAttributes"); - private string CompatibilityUri - { - get - { - if (_compatibilityUri == null) - { - _compatibilityUri = Reader.NameTable.Add(MarkupCompatibilityURI); - } - return _compatibilityUri; - } - } + private string CompatibilityUri => _compatibilityUri ??= Reader.NameTable.Add(MarkupCompatibilityURI); #endregion Private Properties #region Nested Classes private struct NamespaceElementPair @@ -1881,11 +1779,7 @@ namespace System.IO.Packaging } else { - if (_names == null) - { - _names = new Dictionary(); - } - + _names ??= new Dictionary(); _names[elementName] = null; // we don't care about value, just key } } @@ -1936,11 +1830,7 @@ namespace System.IO.Packaging } else { - if (_names == null) - { - _names = new Dictionary(); - } - + _names ??= new Dictionary(); _names.Add(itemName, itemName); } } diff --git a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ZipPackage.cs b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ZipPackage.cs index 3fb085f..b14ac61 100644 --- a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ZipPackage.cs +++ b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ZipPackage.cs @@ -701,8 +701,7 @@ namespace System.IO.Packaging { // The part Uris are stored in the Override Dictionary in their original form , but they are compared // in a normalized manner using the PartUriComparer - if (_overrideDictionary == null) - _overrideDictionary = new Dictionary(OverrideDictionaryInitialSize); + _overrideDictionary ??= new Dictionary(OverrideDictionaryInitialSize); } private void ParseContentTypesFile(System.Collections.ObjectModel.ReadOnlyCollection zipFiles) diff --git a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeCompletionCallbacks.cs b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeCompletionCallbacks.cs index 47c9d06..76ac8b1 100644 --- a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeCompletionCallbacks.cs +++ b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeCompletionCallbacks.cs @@ -50,11 +50,7 @@ namespace System.IO.Pipelines } catch (Exception ex) { - if (exceptions == null) - { - exceptions = new List(); - } - + exceptions ??= new List(); exceptions.Add(ex); } } diff --git a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeReader.cs b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeReader.cs index fad6054..3ec9cdd 100644 --- a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeReader.cs +++ b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeReader.cs @@ -77,11 +77,7 @@ namespace System.IO.Pipelines { lock (_lock) { - if (_internalTokenSource == null) - { - _internalTokenSource = new CancellationTokenSource(); - } - return _internalTokenSource; + return _internalTokenSource ??= new CancellationTokenSource(); } } } diff --git a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeWriter.cs b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeWriter.cs index a836334..ce83c11 100644 --- a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeWriter.cs +++ b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeWriter.cs @@ -38,11 +38,7 @@ namespace System.IO.Pipelines { lock (_lockObject) { - if (_internalTokenSource == null) - { - _internalTokenSource = new CancellationTokenSource(); - } - return _internalTokenSource; + return _internalTokenSource ??= new CancellationTokenSource(); } } } diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/DynamicObject.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/DynamicObject.cs index 7e7d64c..f924518 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/DynamicObject.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/DynamicObject.cs @@ -463,8 +463,7 @@ namespace System.Dynamic if (variable.IsByRef) { - if (block == null) - block = new ReadOnlyCollectionBuilder(); + block ??= new ReadOnlyCollectionBuilder(); block.Add( Expression.Assign( diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/ExpandoClass.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/ExpandoClass.cs index 8451677..ac7cf78 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/ExpandoClass.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/ExpandoClass.cs @@ -89,10 +89,7 @@ namespace System.Dynamic /// private List GetTransitionList(int hashCode) { - if (_transitions == null) - { - _transitions = new Dictionary>(); - } + _transitions ??= new Dictionary>(); if (!_transitions.TryGetValue(hashCode, out List? infos)) { diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/DelegateHelpers.Generated.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/DelegateHelpers.Generated.cs index 8884a27..7735664 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/DelegateHelpers.Generated.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/DelegateHelpers.Generated.cs @@ -67,10 +67,7 @@ namespace System.Linq.Expressions.Compiler { Type lookingUp = initialArg; TypeInfo nextTypeInfo; - if (curTypeInfo.TypeChain == null) - { - curTypeInfo.TypeChain = new Dictionary(); - } + curTypeInfo.TypeChain ??= new Dictionary(); if (!curTypeInfo.TypeChain.TryGetValue(lookingUp, out nextTypeInfo)) { diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LabelInfo.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LabelInfo.cs index 427db15..4ac9a12 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LabelInfo.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LabelInfo.cs @@ -381,10 +381,7 @@ namespace System.Linq.Expressions.Compiler { Debug.Assert(CanJumpInto); - if (_labels == null) - { - _labels = new Dictionary(); - } + _labels ??= new Dictionary(); _labels.Add(target, info); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.ControlFlow.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.ControlFlow.cs index 7281856..c141e54 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.ControlFlow.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.ControlFlow.cs @@ -72,10 +72,7 @@ namespace System.Linq.Expressions.Compiler Debug.Assert(label != null); } - if (label == null) - { - label = DefineLabel(node.Target); - } + label ??= DefineLabel(node.Target); if (node.DefaultValue != null) { diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Expressions.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Expressions.cs index 073071a..bf7bfd8 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Expressions.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Expressions.cs @@ -529,10 +529,7 @@ namespace System.Linq.Expressions.Compiler WriteBack? wb = EmitAddressWriteBack(argument, type); if (wb != null) { - if (writeBacks == null) - { - writeBacks = new List(); - } + writeBacks ??= new List(); writeBacks.Add(wb); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Statements.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Statements.cs index f01cff0..730bbb3 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Statements.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Statements.cs @@ -714,9 +714,7 @@ namespace System.Linq.Expressions.Compiler // if (switchValue == null) { // switchIndex = nullCase; // } else { - // if (_dictField == null) { - // _dictField = new Dictionary(count) { { ... }, ... }; - // } + // _dictField ??= new Dictionary(count) { { ... }, ... }; // if (!_dictField.TryGetValue(switchValue, out switchIndex)) { // switchIndex = -1; // } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/StackSpiller.ChildRewriter.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/StackSpiller.ChildRewriter.cs index d8d978d..fcfda01 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/StackSpiller.ChildRewriter.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/StackSpiller.ChildRewriter.cs @@ -350,10 +350,7 @@ namespace System.Linq.Expressions.Compiler /// private void MarkRef(int index) { - if (_byRefs == null) - { - _byRefs = new bool[_expressions.Length]; - } + _byRefs ??= new bool[_expressions.Length]; _byRefs[index] = true; } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/StackSpiller.Temps.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/StackSpiller.Temps.cs index d19ba67..ecae9cb 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/StackSpiller.Temps.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/StackSpiller.Temps.cs @@ -143,10 +143,7 @@ namespace System.Linq.Expressions.Compiler Debug.Assert(_freeTemps == null || !_freeTemps.Contains(temp)); Debug.Assert(_usedTemps == null || !_usedTemps.Contains(temp)); - if (_usedTemps == null) - { - _usedTemps = new Stack(); - } + _usedTemps ??= new Stack(); _usedTemps.Push(temp); @@ -162,10 +159,7 @@ namespace System.Linq.Expressions.Compiler { Debug.Assert(_freeTemps == null || !_freeTemps.Contains(temp)); - if (_freeTemps == null) - { - _freeTemps = new List(); - } + _freeTemps ??= new List(); _freeTemps.Add(temp); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/StackSpiller.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/StackSpiller.cs index 86d2013..010ce55 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/StackSpiller.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/StackSpiller.cs @@ -919,10 +919,7 @@ namespace System.Linq.Expressions.Compiler @case = new SwitchCase(body.Node, testValues); - if (clone == null) - { - clone = Clone(cases, i); - } + clone ??= Clone(cases, i); } if (clone != null) @@ -987,10 +984,7 @@ namespace System.Linq.Expressions.Compiler { handler = Expression.MakeCatchBlock(handler.Test, handler.Variable, rbody.Node, filter); - if (clone == null) - { - clone = Clone(handlers, i); - } + clone ??= Clone(handlers, i); } if (clone != null) diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/VariableBinder.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/VariableBinder.cs index 47ae039..1791672 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/VariableBinder.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/VariableBinder.cs @@ -178,10 +178,7 @@ namespace System.Linq.Expressions.Compiler } // Otherwise, merge it - if (currentScope.MergedScopes == null) - { - currentScope.MergedScopes = new HashSet(ReferenceEqualityComparer.Instance); - } + currentScope.MergedScopes ??= new HashSet(ReferenceEqualityComparer.Instance); currentScope.MergedScopes.Add(block); foreach (ParameterExpression v in block.Variables) { @@ -221,10 +218,7 @@ namespace System.Linq.Expressions.Compiler } Debug.Assert(referenceScope != null); - if (referenceScope.ReferenceCount == null) - { - referenceScope.ReferenceCount = new Dictionary(); - } + referenceScope.ReferenceCount ??= new Dictionary(); Helpers.IncrementCount(node, referenceScope.ReferenceCount); return node; diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/DebugViewWriter.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/DebugViewWriter.cs index 7019a6d..02d5101 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/DebugViewWriter.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/DebugViewWriter.cs @@ -399,10 +399,7 @@ namespace System.Linq.Expressions { Out($".Lambda {GetLambdaName(node)}<{node.Type}>"); - if (_lambdas == null) - { - _lambdas = new Queue(); - } + _lambdas ??= new Queue(); // N^2 performance, for keeping the order of the lambdas. if (!_lambdas.Contains(node)) diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ExpressionStringBuilder.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ExpressionStringBuilder.cs index 6bc6d13..526dcba 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ExpressionStringBuilder.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ExpressionStringBuilder.cs @@ -35,10 +35,7 @@ namespace System.Linq.Expressions private int GetId(object o) { - if (_ids == null) - { - _ids = new Dictionary(); - } + _ids ??= new Dictionary(); int id; if (!_ids.TryGetValue(o, out id)) diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/BranchLabel.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/BranchLabel.cs index 585d590..cdc11b8 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/BranchLabel.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/BranchLabel.cs @@ -72,10 +72,7 @@ namespace System.Linq.Expressions.Interpreter if (_targetIndex == UnknownIndex) { - if (_forwardBranchFixups == null) - { - _forwardBranchFixups = new List(); - } + _forwardBranchFixups ??= new List(); _forwardBranchFixups.Add(branchIndex); } else diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/ControlFlowInstructions.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/ControlFlowInstructions.cs index 194af7b..2f4d6e4 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/ControlFlowInstructions.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/ControlFlowInstructions.cs @@ -28,7 +28,7 @@ namespace System.Linq.Expressions.Interpreter Instruction[] cache = Cache; if (cache != null && offset >= 0 && offset < cache.Length) { - return cache[offset] ?? (cache[offset] = this); + return cache[offset] ??= this; } return this; @@ -49,17 +49,7 @@ namespace System.Linq.Expressions.Interpreter { private static Instruction[]? s_cache; - public override Instruction[] Cache - { - get - { - if (s_cache == null) - { - s_cache = new Instruction[CacheSize]; - } - return s_cache; - } - } + public override Instruction[] Cache => s_cache ??= new Instruction[CacheSize]; public override string InstructionName => "BranchFalse"; public override int ConsumedStack => 1; @@ -81,17 +71,7 @@ namespace System.Linq.Expressions.Interpreter { private static Instruction[]? s_cache; - public override Instruction[] Cache - { - get - { - if (s_cache == null) - { - s_cache = new Instruction[CacheSize]; - } - return s_cache; - } - } + public override Instruction[] Cache => s_cache ??= new Instruction[CacheSize]; public override string InstructionName => "BranchTrue"; public override int ConsumedStack => 1; @@ -113,17 +93,7 @@ namespace System.Linq.Expressions.Interpreter { private static Instruction[]? s_cache; - public override Instruction[] Cache - { - get - { - if (s_cache == null) - { - s_cache = new Instruction[CacheSize]; - } - return s_cache; - } - } + public override Instruction[] Cache => s_cache ??= new Instruction[CacheSize]; public override string InstructionName => "CoalescingBranch"; public override int ConsumedStack => 1; @@ -150,11 +120,8 @@ namespace System.Linq.Expressions.Interpreter { get { - if (s_caches == null) - { - s_caches = new Instruction[2][][] { new Instruction[2][], new Instruction[2][] }; - } - return s_caches[ConsumedStack][ProducedStack] ?? (s_caches[ConsumedStack][ProducedStack] = new Instruction[CacheSize]); + s_caches ??= new Instruction[2][][] { new Instruction[2][], new Instruction[2][] }; + return s_caches[ConsumedStack][ProducedStack] ??= new Instruction[CacheSize]; } } @@ -272,7 +239,7 @@ namespace System.Linq.Expressions.Interpreter if (labelIndex < CacheSize) { int index = Variants * labelIndex | (labelTargetGetsValue ? 4 : 0) | (hasResult ? 2 : 0) | (hasValue ? 1 : 0); - return s_cache[index] ?? (s_cache[index] = new GotoInstruction(labelIndex, hasResult, hasValue, labelTargetGetsValue)); + return s_cache[index] ??= new GotoInstruction(labelIndex, hasResult, hasValue, labelTargetGetsValue); } return new GotoInstruction(labelIndex, hasResult, hasValue, labelTargetGetsValue); } @@ -528,7 +495,7 @@ namespace System.Linq.Expressions.Interpreter { if (labelIndex < CacheSize) { - return s_cache[labelIndex] ?? (s_cache[labelIndex] = new EnterFinallyInstruction(labelIndex)); + return s_cache[labelIndex] ??= new EnterFinallyInstruction(labelIndex); } return new EnterFinallyInstruction(labelIndex); } @@ -589,7 +556,7 @@ namespace System.Linq.Expressions.Interpreter { if (labelIndex < CacheSize) { - return s_cache[labelIndex] ?? (s_cache[labelIndex] = new EnterFaultInstruction(labelIndex)); + return s_cache[labelIndex] ??= new EnterFaultInstruction(labelIndex); } return new EnterFaultInstruction(labelIndex); @@ -720,7 +687,7 @@ namespace System.Linq.Expressions.Interpreter if (labelIndex < CacheSize) { int index = (2 * labelIndex) | (hasValue ? 1 : 0); - return s_cache[index] ?? (s_cache[index] = new LeaveExceptionHandlerInstruction(labelIndex, hasValue)); + return s_cache[index] ??= new LeaveExceptionHandlerInstruction(labelIndex, hasValue); } return new LeaveExceptionHandlerInstruction(labelIndex, hasValue); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InstructionList.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InstructionList.cs index 4e9725a..1b0e18c 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InstructionList.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InstructionList.cs @@ -361,12 +361,9 @@ namespace System.Linq.Expressions.Interpreter { if (i >= PushIntMinCachedValue && i <= PushIntMaxCachedValue) { - if (s_Ints == null) - { - s_Ints = new Instruction[PushIntMaxCachedValue - PushIntMinCachedValue + 1]; - } + s_Ints ??= new Instruction[PushIntMaxCachedValue - PushIntMinCachedValue + 1]; i -= PushIntMinCachedValue; - Emit(s_Ints[i] ?? (s_Ints[i] = new LoadObjectInstruction(value))); + Emit(s_Ints[i] ??= new LoadObjectInstruction(value)); return; } } @@ -375,17 +372,14 @@ namespace System.Linq.Expressions.Interpreter if (_objects == null) { _objects = new List(); - if (s_loadObjectCached == null) - { - s_loadObjectCached = new Instruction[CachedObjectCount]; - } + s_loadObjectCached ??= new Instruction[CachedObjectCount]; } if (_objects.Count < s_loadObjectCached!.Length) { uint index = (uint)_objects.Count; _objects.Add(value); - Emit(s_loadObjectCached[index] ?? (s_loadObjectCached[index] = new LoadCachedObjectInstruction(index))); + Emit(s_loadObjectCached[index] ??= new LoadCachedObjectInstruction(index)); } else { @@ -433,14 +427,11 @@ namespace System.Linq.Expressions.Interpreter public void EmitLoadLocal(int index) { - if (s_loadLocal == null) - { - s_loadLocal = new Instruction[LocalInstrCacheSize]; - } + s_loadLocal ??= new Instruction[LocalInstrCacheSize]; if (index < s_loadLocal.Length) { - Emit(s_loadLocal[index] ?? (s_loadLocal[index] = new LoadLocalInstruction(index))); + Emit(s_loadLocal[index] ??= new LoadLocalInstruction(index)); } else { @@ -455,14 +446,11 @@ namespace System.Linq.Expressions.Interpreter internal static Instruction LoadLocalBoxed(int index) { - if (s_loadLocalBoxed == null) - { - s_loadLocalBoxed = new Instruction[LocalInstrCacheSize]; - } + s_loadLocalBoxed ??= new Instruction[LocalInstrCacheSize]; if (index < s_loadLocalBoxed.Length) { - return s_loadLocalBoxed[index] ?? (s_loadLocalBoxed[index] = new LoadLocalBoxedInstruction(index)); + return s_loadLocalBoxed[index] ??= new LoadLocalBoxedInstruction(index); } else { @@ -472,14 +460,11 @@ namespace System.Linq.Expressions.Interpreter public void EmitLoadLocalFromClosure(int index) { - if (s_loadLocalFromClosure == null) - { - s_loadLocalFromClosure = new Instruction[LocalInstrCacheSize]; - } + s_loadLocalFromClosure ??= new Instruction[LocalInstrCacheSize]; if (index < s_loadLocalFromClosure.Length) { - Emit(s_loadLocalFromClosure[index] ?? (s_loadLocalFromClosure[index] = new LoadLocalFromClosureInstruction(index))); + Emit(s_loadLocalFromClosure[index] ??= new LoadLocalFromClosureInstruction(index)); } else { @@ -489,14 +474,11 @@ namespace System.Linq.Expressions.Interpreter public void EmitLoadLocalFromClosureBoxed(int index) { - if (s_loadLocalFromClosureBoxed == null) - { - s_loadLocalFromClosureBoxed = new Instruction[LocalInstrCacheSize]; - } + s_loadLocalFromClosureBoxed ??= new Instruction[LocalInstrCacheSize]; if (index < s_loadLocalFromClosureBoxed.Length) { - Emit(s_loadLocalFromClosureBoxed[index] ?? (s_loadLocalFromClosureBoxed[index] = new LoadLocalFromClosureBoxedInstruction(index))); + Emit(s_loadLocalFromClosureBoxed[index] ??= new LoadLocalFromClosureBoxedInstruction(index)); } else { @@ -506,14 +488,11 @@ namespace System.Linq.Expressions.Interpreter public void EmitAssignLocal(int index) { - if (s_assignLocal == null) - { - s_assignLocal = new Instruction[LocalInstrCacheSize]; - } + s_assignLocal ??= new Instruction[LocalInstrCacheSize]; if (index < s_assignLocal.Length) { - Emit(s_assignLocal[index] ?? (s_assignLocal[index] = new AssignLocalInstruction(index))); + Emit(s_assignLocal[index] ??= new AssignLocalInstruction(index)); } else { @@ -523,14 +502,11 @@ namespace System.Linq.Expressions.Interpreter public void EmitStoreLocal(int index) { - if (s_storeLocal == null) - { - s_storeLocal = new Instruction[LocalInstrCacheSize]; - } + s_storeLocal ??= new Instruction[LocalInstrCacheSize]; if (index < s_storeLocal.Length) { - Emit(s_storeLocal[index] ?? (s_storeLocal[index] = new StoreLocalInstruction(index))); + Emit(s_storeLocal[index] ??= new StoreLocalInstruction(index)); } else { @@ -545,14 +521,11 @@ namespace System.Linq.Expressions.Interpreter internal static Instruction AssignLocalBoxed(int index) { - if (s_assignLocalBoxed == null) - { - s_assignLocalBoxed = new Instruction[LocalInstrCacheSize]; - } + s_assignLocalBoxed ??= new Instruction[LocalInstrCacheSize]; if (index < s_assignLocalBoxed.Length) { - return s_assignLocalBoxed[index] ?? (s_assignLocalBoxed[index] = new AssignLocalBoxedInstruction(index)); + return s_assignLocalBoxed[index] ??= new AssignLocalBoxedInstruction(index); } else { @@ -567,14 +540,11 @@ namespace System.Linq.Expressions.Interpreter internal static Instruction StoreLocalBoxed(int index) { - if (s_storeLocalBoxed == null) - { - s_storeLocalBoxed = new Instruction[LocalInstrCacheSize]; - } + s_storeLocalBoxed ??= new Instruction[LocalInstrCacheSize]; if (index < s_storeLocalBoxed.Length) { - return s_storeLocalBoxed[index] ?? (s_storeLocalBoxed[index] = new StoreLocalBoxedInstruction(index)); + return s_storeLocalBoxed[index] ??= new StoreLocalBoxedInstruction(index); } else { @@ -584,14 +554,11 @@ namespace System.Linq.Expressions.Interpreter public void EmitAssignLocalToClosure(int index) { - if (s_assignLocalToClosure == null) - { - s_assignLocalToClosure = new Instruction[LocalInstrCacheSize]; - } + s_assignLocalToClosure ??= new Instruction[LocalInstrCacheSize]; if (index < s_assignLocalToClosure.Length) { - Emit(s_assignLocalToClosure[index] ?? (s_assignLocalToClosure[index] = new AssignLocalToClosureInstruction(index))); + Emit(s_assignLocalToClosure[index] ??= new AssignLocalToClosureInstruction(index)); } else { @@ -968,10 +935,7 @@ namespace System.Linq.Expressions.Interpreter public BranchLabel MakeLabel() { - if (_labels == null) - { - _labels = new List(); - } + _labels ??= new List(); var label = new BranchLabel(); _labels.Add(label); diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InterpretedFrame.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InterpretedFrame.cs index 18a2e3c..f95008a 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InterpretedFrame.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InterpretedFrame.cs @@ -142,10 +142,7 @@ namespace System.Linq.Expressions.Interpreter internal void SaveTraceToException(Exception exception) { - if (exception.Data[typeof(InterpretedFrameInfo)] == null) - { - exception.Data[typeof(InterpretedFrameInfo)] = new List(GetStackTraceDebugInfo()).ToArray(); - } + exception.Data[typeof(InterpretedFrameInfo)] ??= new List(GetStackTraceDebugInfo()).ToArray(); } public static InterpretedFrameInfo[]? GetExceptionStackTrace(Exception exception) diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LabelInfo.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LabelInfo.cs index 3fbc68e..fbc67fd 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LabelInfo.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LabelInfo.cs @@ -165,10 +165,7 @@ namespace System.Linq.Expressions.Interpreter private void EnsureLabel(LightCompiler compiler) { - if (_label == null) - { - _label = compiler.Instructions.MakeLabel(); - } + _label ??= compiler.Instructions.MakeLabel(); } private bool DefinedIn(LabelScopeInfo scope) @@ -331,10 +328,7 @@ namespace System.Linq.Expressions.Interpreter { Debug.Assert(CanJumpInto); - if (_labels == null) - { - _labels = new HybridReferenceDictionary(); - } + _labels ??= new HybridReferenceDictionary(); _labels[target] = info; } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightCompiler.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightCompiler.cs index a560068..068f933 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightCompiler.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightCompiler.cs @@ -1743,10 +1743,7 @@ namespace System.Linq.Expressions.Interpreter Debug.Assert(label != null); } - if (label == null) - { - label = DefineLabel(node.Target); - } + label ??= DefineLabel(node.Target); if (node.DefaultValue != null) { @@ -2166,10 +2163,7 @@ namespace System.Linq.Expressions.Interpreter ByRefUpdater? updater = CompileAddress(arg, i); if (updater != null) { - if (updaters == null) - { - updaters = new List(); - } + updaters ??= new List(); updaters.Add(updater); } @@ -2406,10 +2400,7 @@ namespace System.Linq.Expressions.Interpreter ByRefUpdater? updater = CompileAddress(arg, i); if (updater != null) { - if (updaters == null) - { - updaters = new List(); - } + updaters ??= new List(); updaters.Add(updater); } } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LocalVariables.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LocalVariables.cs index f42254d..8e64650 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LocalVariables.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LocalVariables.cs @@ -79,10 +79,7 @@ namespace System.Linq.Expressions.Interpreter if (_variables.TryGetValue(variable, out existing)) { newScope = new VariableScope(result, start, existing); - if (existing.ChildScopes == null) - { - existing.ChildScopes = new List(); - } + existing.ChildScopes ??= new List(); existing.ChildScopes.Add(newScope); } else diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/LambdaExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/LambdaExpression.cs index 0743941..aa4128d 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/LambdaExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/LambdaExpression.cs @@ -613,11 +613,8 @@ namespace System.Linq.Expressions // method and call that will be used for creating instances of this // delegate type Func, LambdaExpression>? fastPath; - CacheDict, LambdaExpression>>? factories = s_lambdaFactories; - if (factories == null) - { - s_lambdaFactories = factories = new CacheDict, LambdaExpression>>(50); - } + CacheDict, LambdaExpression>>? factories = + s_lambdaFactories ??= new CacheDict, LambdaExpression>>(50); if (!factories.TryGetValue(delegateType, out fastPath)) { diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MethodCallExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MethodCallExpression.cs index 25291ad..731c1e4 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MethodCallExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MethodCallExpression.cs @@ -1142,10 +1142,7 @@ namespace System.Linq.Expressions { ArgumentNullException.ThrowIfNull(instance); ArgumentNullException.ThrowIfNull(methodName); - if (arguments == null) - { - arguments = Array.Empty(); - } + arguments ??= Array.Empty(); BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy; return Expression.Call(instance, FindMethod(instance.Type, methodName, typeArguments, arguments, flags)!, arguments); @@ -1173,9 +1170,9 @@ namespace System.Linq.Expressions ArgumentNullException.ThrowIfNull(type); ArgumentNullException.ThrowIfNull(methodName); - if (arguments == null) arguments = Array.Empty(); - BindingFlags flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy; - return Expression.Call(null, FindMethod(type, methodName, typeArguments, arguments, flags)!, arguments); + arguments ??= Array.Empty(); + const BindingFlags Flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy; + return Expression.Call(null, FindMethod(type, methodName, typeArguments, arguments, Flags)!, arguments); } /// Creates a that represents a method call. diff --git a/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/CallSiteBinder.cs b/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/CallSiteBinder.cs index 110b6bb..968b272 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/CallSiteBinder.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/CallSiteBinder.cs @@ -41,17 +41,7 @@ namespace System.Runtime.CompilerServices { private static LambdaSignature? s_instance; - internal static LambdaSignature Instance - { - get - { - if (s_instance == null) - { - s_instance = new LambdaSignature(); - } - return s_instance; - } - } + internal static LambdaSignature Instance => s_instance ??= new LambdaSignature(); internal readonly ReadOnlyCollection Parameters; internal readonly LabelTarget ReturnLabel; diff --git a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Enumerables/RangeEnumerable.cs b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Enumerables/RangeEnumerable.cs index 5e5413d..e33d959 100644 --- a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Enumerables/RangeEnumerable.cs +++ b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Enumerables/RangeEnumerable.cs @@ -96,8 +96,7 @@ namespace System.Linq.Parallel internal override bool MoveNext(ref int currentElement, ref int currentKey) { - if (_currentCount == null) - _currentCount = new Shared(-1); + _currentCount ??= new Shared(-1); // Calculate the next index and ensure it falls within our range. int nextCount = _currentCount.Value + 1; diff --git a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Enumerables/RepeatEnumerable.cs b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Enumerables/RepeatEnumerable.cs index c56de6c..2e80fd0 100644 --- a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Enumerables/RepeatEnumerable.cs +++ b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Enumerables/RepeatEnumerable.cs @@ -101,8 +101,7 @@ namespace System.Linq.Parallel internal override bool MoveNext([MaybeNullWhen(false), AllowNull] ref TResult currentElement, ref int currentKey) { - if (_currentIndex == null) - _currentIndex = new Shared(-1); + _currentIndex ??= new Shared(-1); if (_currentIndex.Value < (_count - 1)) { diff --git a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Partitioning/HashRepartitionEnumerator.cs b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Partitioning/HashRepartitionEnumerator.cs index 5a9ecf5..bce7107 100644 --- a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Partitioning/HashRepartitionEnumerator.cs +++ b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Partitioning/HashRepartitionEnumerator.cs @@ -125,9 +125,7 @@ namespace System.Linq.Parallel Debug.Assert(!ParallelEnumerable.SinglePartitionMode); - Mutables? mutables = _mutables; - if (mutables == null) - mutables = _mutables = new Mutables(); + Mutables mutables = _mutables ??= new Mutables(); // If we haven't enumerated the source yet, do that now. This is the first phase // of a two-phase barrier style operation. diff --git a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Partitioning/OrderedHashRepartitionEnumerator.cs b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Partitioning/OrderedHashRepartitionEnumerator.cs index 477f0f1..e1e749e 100644 --- a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Partitioning/OrderedHashRepartitionEnumerator.cs +++ b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Partitioning/OrderedHashRepartitionEnumerator.cs @@ -123,9 +123,7 @@ namespace System.Linq.Parallel Debug.Assert(!ParallelEnumerable.SinglePartitionMode); - Mutables? mutables = _mutables; - if (mutables == null) - mutables = _mutables = new Mutables(); + Mutables mutables = _mutables ??= new Mutables(); // If we haven't enumerated the source yet, do that now. This is the first phase // of a two-phase barrier style operation. diff --git a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Partitioning/PartitionedDataSource.cs b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Partitioning/PartitionedDataSource.cs index be2778b..cf86f5d 100644 --- a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Partitioning/PartitionedDataSource.cs +++ b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Partitioning/PartitionedDataSource.cs @@ -258,11 +258,7 @@ namespace System.Linq.Parallel internal override bool MoveNext([MaybeNullWhen(false), AllowNull] ref T currentElement, ref int currentKey) { // Lazily allocate the mutable holder. - Mutables? mutables = _mutables; - if (mutables == null) - { - mutables = _mutables = new Mutables(); - } + Mutables mutables = _mutables ??= new Mutables(); // If we are aren't within the chunk, we need to find another. if (++mutables._currentPositionInChunk < mutables._currentChunkSize || MoveNextSlowPath()) @@ -367,10 +363,7 @@ namespace System.Linq.Parallel internal override bool MoveNext([MaybeNullWhen(false), AllowNull] ref T currentElement, ref int currentKey) { // Lazily allocate the current index if needed. - if (_currentIndex == null) - { - _currentIndex = new Shared(_startIndex); - } + _currentIndex ??= new Shared(_startIndex); // Now increment the current index, check bounds, and so on. int current = ++_currentIndex.Value; @@ -436,11 +429,7 @@ namespace System.Linq.Parallel internal override bool MoveNext([MaybeNullWhen(false), AllowNull] ref T currentElement, ref int currentKey) { // Lazily allocate the mutable holder. - Mutables? mutables = _mutables; - if (mutables == null) - { - mutables = _mutables = new Mutables(); - } + Mutables mutables = _mutables ??= new Mutables(); // If we are aren't within the chunk, we need to find another. if (++mutables._currentPositionInChunk < mutables._currentChunkSize || MoveNextSlowPath()) @@ -545,10 +534,7 @@ namespace System.Linq.Parallel internal override bool MoveNext([MaybeNullWhen(false), AllowNull] ref T currentElement, ref int currentKey) { // Lazily allocate the current index if needed. - if (_currentIndex == null) - { - _currentIndex = new Shared(_startIndex); - } + _currentIndex ??= new Shared(_startIndex); // Now increment the current index, check bounds, and so on. int current = ++_currentIndex.Value; @@ -623,11 +609,7 @@ namespace System.Linq.Parallel internal override bool MoveNext([MaybeNullWhen(false), AllowNull] ref T currentElement, ref int currentKey) { - Mutables? mutables = _mutables; - if (mutables == null) - { - mutables = _mutables = new Mutables(); - } + Mutables? mutables = _mutables ??= new Mutables(); Debug.Assert(mutables._chunkBuffer != null); diff --git a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Binary/UnionQueryOperator.cs b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Binary/UnionQueryOperator.cs index a9136f0..eefc462 100644 --- a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Binary/UnionQueryOperator.cs +++ b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Binary/UnionQueryOperator.cs @@ -325,12 +325,7 @@ namespace System.Linq.Parallel _leftOrdered = leftOrdered; _rightOrdered = rightOrdered; - _comparer = comparer; - - if (_comparer == null) - { - _comparer = EqualityComparer.Default; - } + _comparer = comparer ?? EqualityComparer.Default; _cancellationToken = cancellationToken; } diff --git a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/QueryOperator.cs b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/QueryOperator.cs index 9d0e5c1..7770866 100644 --- a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/QueryOperator.cs +++ b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/QueryOperator.cs @@ -134,11 +134,7 @@ namespace System.Linq.Parallel QueryResults queryResults = GetQueryResults(querySettings); - if (mergeOptions == null) - { - mergeOptions = querySettings.MergeOptions; - } - + mergeOptions ??= querySettings.MergeOptions; Debug.Assert(mergeOptions != null); // Top-level preemptive cancellation test. diff --git a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/QuerySettings.cs b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/QuerySettings.cs index d8fa01b..93bcda2 100644 --- a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/QuerySettings.cs +++ b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/QuerySettings.cs @@ -172,26 +172,11 @@ namespace System.Linq.Parallel internal QuerySettings WithDefaults() { QuerySettings settings = this; - if (settings.TaskScheduler == null) - { - settings.TaskScheduler = TaskScheduler.Default; - } - - if (settings.DegreeOfParallelism == null) - { - settings.DegreeOfParallelism = Scheduling.GetDefaultDegreeOfParallelism(); - } - - if (settings.ExecutionMode == null) - { - settings.ExecutionMode = ParallelExecutionMode.Default; - } - - if (settings.MergeOptions == null) - { - settings.MergeOptions = ParallelMergeOptions.Default; - } + settings.TaskScheduler ??= TaskScheduler.Default; + settings.DegreeOfParallelism ??= Scheduling.GetDefaultDegreeOfParallelism(); + settings.ExecutionMode ??= ParallelExecutionMode.Default; + settings.MergeOptions ??= ParallelMergeOptions.Default; if (settings.MergeOptions == ParallelMergeOptions.Default) { settings.MergeOptions = ParallelMergeOptions.AutoBuffered; diff --git a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Unary/ContainsSearchOperator.cs b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Unary/ContainsSearchOperator.cs index eb7464f..3a723a4 100644 --- a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Unary/ContainsSearchOperator.cs +++ b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Unary/ContainsSearchOperator.cs @@ -40,15 +40,7 @@ namespace System.Linq.Parallel Debug.Assert(child != null, "child data source cannot be null"); _searchValue = searchValue; - - if (comparer == null) - { - _comparer = EqualityComparer.Default; - } - else - { - _comparer = comparer; - } + _comparer = comparer ?? EqualityComparer.Default; } //--------------------------------------------------------------------------------------- diff --git a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Unary/DistinctQueryOperator.cs b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Unary/DistinctQueryOperator.cs index 27afe76..5ebbefa 100644 --- a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Unary/DistinctQueryOperator.cs +++ b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Unary/DistinctQueryOperator.cs @@ -150,8 +150,7 @@ namespace System.Linq.Parallel TKey keyUnused = default!; Pair current = default(Pair); - if (_outputLoopCount == null) - _outputLoopCount = new Shared(0); + _outputLoopCount ??= new Shared(0); while (_source.MoveNext(ref current, ref keyUnused)) { diff --git a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Unary/IndexedWhereQueryOperator.cs b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Unary/IndexedWhereQueryOperator.cs index 251e58e..5455982 100644 --- a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Unary/IndexedWhereQueryOperator.cs +++ b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Unary/IndexedWhereQueryOperator.cs @@ -167,8 +167,7 @@ namespace System.Linq.Parallel // Iterate through the input until we reach the end of the sequence or find // an element matching the predicate. - if (_outputLoopCount == null) - _outputLoopCount = new Shared(0); + _outputLoopCount ??= new Shared(0); while (_source.MoveNext(ref currentElement!, ref currentKey)) { diff --git a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Unary/SortQueryOperator.cs b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Unary/SortQueryOperator.cs index 7fb10e1..a1fe751 100644 --- a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Unary/SortQueryOperator.cs +++ b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Unary/SortQueryOperator.cs @@ -38,15 +38,7 @@ namespace System.Linq.Parallel _keySelector = keySelector; // If a comparer wasn't supplied, we use the default one for the key type. - if (comparer == null) - { - _comparer = Util.GetDefaultComparer(); - } - else - { - _comparer = comparer; - } - + _comparer = comparer ?? Util.GetDefaultComparer(); if (descending) { _comparer = new ReverseComparer(_comparer); diff --git a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Unary/WhereQueryOperator.cs b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Unary/WhereQueryOperator.cs index b189b57..158795c 100644 --- a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Unary/WhereQueryOperator.cs +++ b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Unary/WhereQueryOperator.cs @@ -132,8 +132,7 @@ namespace System.Linq.Parallel // Iterate through the input until we reach the end of the sequence or find // an element matching the predicate. - if (_outputLoopCount == null) - _outputLoopCount = new Shared(0); + _outputLoopCount ??= new Shared(0); while (_source.MoveNext(ref currentElement!, ref currentKey)) { diff --git a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Utils/Sorting.cs b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Utils/Sorting.cs index f2f8f51..4bfc75c 100644 --- a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Utils/Sorting.cs +++ b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Utils/Sorting.cs @@ -233,10 +233,7 @@ namespace System.Linq.Parallel TKey currentKey = default(TKey)!; bool hadNext = _source.MoveNext(ref current!, ref currentKey); - if (keys == null) - { - keys = new GrowingArray(); - } + keys ??= new GrowingArray(); if (hadNext) { diff --git a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Utils/WrapperEqualityComparer.cs b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Utils/WrapperEqualityComparer.cs index d3455ae..6ed1a19 100644 --- a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Utils/WrapperEqualityComparer.cs +++ b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Utils/WrapperEqualityComparer.cs @@ -21,17 +21,8 @@ namespace System.Linq.Parallel { private readonly IEqualityComparer _comparer; - internal WrapperEqualityComparer(IEqualityComparer? comparer) - { - if (comparer == null) - { - _comparer = EqualityComparer.Default; - } - else - { - _comparer = comparer; - } - } + internal WrapperEqualityComparer(IEqualityComparer? comparer) => + _comparer = comparer ?? EqualityComparer.Default; public bool Equals(Wrapper x, Wrapper y) { diff --git a/src/libraries/System.Linq.Queryable/src/System/Linq/EnumerableRewriter.cs b/src/libraries/System.Linq.Queryable/src/System/Linq/EnumerableRewriter.cs index faf127b..9a0e36f 100644 --- a/src/libraries/System.Linq.Queryable/src/System/Linq/EnumerableRewriter.cs +++ b/src/libraries/System.Linq.Queryable/src/System/Linq/EnumerableRewriter.cs @@ -463,9 +463,14 @@ namespace System.Linq { LabelTarget? newTarget; if (_targetCache == null) + { _targetCache = new Dictionary(); + } else if (_targetCache.TryGetValue(node!, out newTarget)) + { return newTarget; + } + Type type = node!.Type; if (!typeof(IQueryable).IsAssignableFrom(type)) newTarget = base.VisitLabelTarget(node); diff --git a/src/libraries/System.Management/src/System/Management/ManagementBaseObject.cs b/src/libraries/System.Management/src/System/Management/ManagementBaseObject.cs index 53997ce..bc5db3b 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementBaseObject.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementBaseObject.cs @@ -343,10 +343,7 @@ namespace System.Management { Initialize(true); - if (properties == null) - properties = new PropertyDataCollection(this, false); - - return properties; + return properties ??= new PropertyDataCollection(this, false); } } @@ -365,10 +362,7 @@ namespace System.Management { Initialize(false); - if (systemProperties == null) - systemProperties = new PropertyDataCollection(this, true); - - return systemProperties; + return systemProperties ??= new PropertyDataCollection(this, true); } } @@ -388,10 +382,7 @@ namespace System.Management { Initialize(true); - if (qualifiers == null) - qualifiers = new QualifierDataCollection(this); - - return qualifiers; + return qualifiers ??= new QualifierDataCollection(this); } } diff --git a/src/libraries/System.Management/src/System/Management/ManagementClass.cs b/src/libraries/System.Management/src/System/Management/ManagementClass.cs index 9161fd9..24f280e 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementClass.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementClass.cs @@ -383,10 +383,7 @@ namespace System.Management { Initialize(true); - if (methods == null) - methods = new MethodDataCollection(this); - - return methods; + return methods ??= new MethodDataCollection(this); } } diff --git a/src/libraries/System.Management/src/System/Management/ManagementObject.cs b/src/libraries/System.Management/src/System/Management/ManagementObject.cs index ca70e41..26bc04d 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementObject.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementObject.cs @@ -502,10 +502,7 @@ namespace System.Management { get { - if (scope == null) - return scope = ManagementScope._Clone(null); - else - return scope; + return scope ??= ManagementScope._Clone(null); } set { @@ -557,10 +554,7 @@ namespace System.Management { get { - if (path == null) - return path = ManagementPath._Clone(null); - else - return path; + return path ??= ManagementPath._Clone(null); } set { @@ -624,10 +618,7 @@ namespace System.Management { get { - if (options == null) - return options = ObjectGetOptions._Clone(null); - else - return options; + return options ??= ObjectGetOptions._Clone(null); } set { @@ -1597,10 +1588,7 @@ namespace System.Management { } - if (newPath == null) - newPath = new ManagementPath(); - - return newPath; + return newPath ?? new ManagementPath(); } /// diff --git a/src/libraries/System.Management/src/System/Management/ManagementOptions.cs b/src/libraries/System.Management/src/System/Management/ManagementOptions.cs index 49c6a54..bb730db 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementOptions.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementOptions.cs @@ -166,10 +166,7 @@ namespace System.Management { get { - if (context == null) - return context = new ManagementNamedValueCollection(); - else - return context; + return context ??= new ManagementNamedValueCollection(); } set { diff --git a/src/libraries/System.Management/src/System/Management/ManagementPath.cs b/src/libraries/System.Management/src/System/Management/ManagementPath.cs index 633b306..2710b76 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementPath.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementPath.cs @@ -256,9 +256,13 @@ namespace System.Management { // Test/utilize isWbemPathShared *only* on public + internal members! if (wmiPath == null) + { wmiPath = CreateWbemPath(path); + } else + { SetWbemPath(wmiPath, path); + } } private static void SetWbemPath(IWbemPath wbemPath, string path) @@ -676,7 +680,9 @@ namespace System.Management wmiPathTmp = CreateWbemPath(nsPath); if (wmiPath == null) + { wmiPath = this.CreateWbemPath(""); + } else if (isWbemPathShared) { // Check if this IWbemPath is shared among multiple managed objects. @@ -926,7 +932,9 @@ namespace System.Management int status = (int)ManagementStatus.NoError; if (wmiPath == null) + { wmiPath = (IWbemPath)MTAHelper.CreateInMTA(typeof(WbemDefPath)); //new WbemDefPath(); + } else if (isWbemPathShared) { // Check if this IWbemPath is shared among multiple managed objects. diff --git a/src/libraries/System.Management/src/System/Management/ManagementScope.cs b/src/libraries/System.Management/src/System/Management/ManagementScope.cs index 1024c87..720b15e 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementScope.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementScope.cs @@ -808,10 +808,7 @@ namespace System.Management { get { - if (options == null) - return options = ConnectionOptions._Clone(null, new IdentifierChangedEventHandler(HandleIdentifierChange)); - else - return options; + return options ??= ConnectionOptions._Clone(null, new IdentifierChangedEventHandler(HandleIdentifierChange)); } set { @@ -849,10 +846,7 @@ namespace System.Management { get { - if (prvpath == null) - return prvpath = ManagementPath._Clone(null); - else - return prvpath; + return prvpath ??= ManagementPath._Clone(null); } set { diff --git a/src/libraries/System.Management/src/System/Management/Method.cs b/src/libraries/System.Management/src/System/Management/Method.cs index 267ed84..d90ed8b 100644 --- a/src/libraries/System.Management/src/System/Management/Method.cs +++ b/src/libraries/System.Management/src/System/Management/Method.cs @@ -240,15 +240,7 @@ namespace System.Management /// qualifiers for this method. /// /// - public QualifierDataCollection Qualifiers - { - get - { - if (qualifiers == null) - qualifiers = new QualifierDataCollection(parent, methodName, QualifierType.MethodQualifier); - return qualifiers; - } - } + public QualifierDataCollection Qualifiers => qualifiers ??= new QualifierDataCollection(parent, methodName, QualifierType.MethodQualifier); }//MethodData } diff --git a/src/libraries/System.Management/src/System/Management/Property.cs b/src/libraries/System.Management/src/System/Management/Property.cs index 62acc0e..07969d4 100644 --- a/src/libraries/System.Management/src/System/Management/Property.cs +++ b/src/libraries/System.Management/src/System/Management/Property.cs @@ -250,16 +250,8 @@ namespace System.Management /// A that represents /// the set of qualifiers defined on the property. /// - public QualifierDataCollection Qualifiers - { - get - { - if (qualifiers == null) - qualifiers = new QualifierDataCollection(parent, propertyName, QualifierType.PropertyQualifier); + public QualifierDataCollection Qualifiers => qualifiers ??= new QualifierDataCollection(parent, propertyName, QualifierType.PropertyQualifier); - return qualifiers; - } - } internal long NullEnumValue { get diff --git a/src/libraries/System.Management/src/System/Management/WMIGenerator.cs b/src/libraries/System.Management/src/System/Management/WMIGenerator.cs index 9406209..63e80d4 100644 --- a/src/libraries/System.Management/src/System/Management/WMIGenerator.cs +++ b/src/libraries/System.Management/src/System/Management/WMIGenerator.cs @@ -5775,10 +5775,7 @@ namespace System.Management /// private void AddPropertySet(CodeIndexerExpression prop, bool bArray, CodeStatementCollection statColl, string strType, CodeVariableReferenceExpression varValue) { - if (varValue == null) - { - varValue = new CodeVariableReferenceExpression("value"); - } + varValue ??= new CodeVariableReferenceExpression("value"); if (bArray == false) { 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 4fa86dc..91ba3aa 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 @@ -261,12 +261,7 @@ namespace System.Net.Http throw new InvalidOperationException(SR.Format(SR.net_http_invalid_enable_first, "ClientCertificateOptions", "Manual")); } - if (_clientCertificates == null) - { - _clientCertificates = new X509Certificate2Collection(); - } - - return _clientCertificates; + return _clientCertificates ??= new X509Certificate2Collection(); } } @@ -538,18 +533,7 @@ namespace System.Net.Http } } - public IDictionary Properties - { - get - { - if (_properties == null) - { - _properties = new Dictionary(); - } - - return _properties; - } - } + public IDictionary Properties => _properties ??= new Dictionary(); #endregion protected override void Dispose(bool disposing) diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/CacheControlHeaderValue.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/CacheControlHeaderValue.cs index fdba34a..0ced574 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/CacheControlHeaderValue.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/CacheControlHeaderValue.cs @@ -413,11 +413,7 @@ namespace System.Net.Http.Headers // Cache-Control is a header supporting lists of values. However, expose the header as an instance of // CacheControlHeaderValue. So if we already have an instance of CacheControlHeaderValue, add the values // from this string to the existing instances. - CacheControlHeaderValue? result = storeValue; - if (result == null) - { - result = new CacheControlHeaderValue(); - } + CacheControlHeaderValue? result = storeValue ?? new CacheControlHeaderValue(); if (!TrySetCacheControlValues(result, nameValueList)) { diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpContent.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpContent.cs index 8e508e8..0e2244c 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpContent.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpContent.cs @@ -109,17 +109,7 @@ namespace System.Net.Http } #endif - public HttpContentHeaders Headers - { - get - { - if (_headers == null) - { - _headers = new HttpContentHeaders(this); - } - return _headers; - } - } + public HttpContentHeaders Headers => _headers ??= new HttpContentHeaders(this); private bool IsBuffered { diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpTelemetry.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpTelemetry.cs index 9e5e1f5..ce03900 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpTelemetry.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpTelemetry.cs @@ -183,9 +183,9 @@ namespace System.Net.Http { if (IsEnabled()) { - if (arg1 == null) arg1 = ""; - if (arg2 == null) arg2 = ""; - if (arg4 == null) arg4 = ""; + arg1 ??= ""; + arg2 ??= ""; + arg4 ??= ""; fixed (char* arg1Ptr = arg1) fixed (char* arg2Ptr = arg2) diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/NetEventSource.Http.cs b/src/libraries/System.Net.Http/src/System/Net/Http/NetEventSource.Http.cs index d1de2d9..4cc2568 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/NetEventSource.Http.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/NetEventSource.Http.cs @@ -83,8 +83,8 @@ namespace System.Net { if (IsEnabled()) { - if (arg4 == null) arg4 = ""; - if (arg5 == null) arg5 = ""; + arg4 ??= ""; + arg5 ??= ""; fixed (char* string4Bytes = arg4) fixed (char* string5Bytes = arg5) diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http3Connection.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http3Connection.cs index dc796d8..b9f743a 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http3Connection.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http3Connection.cs @@ -127,10 +127,7 @@ namespace System.Net.Http { // Close the QuicConnection in the background. - if (_connectionClosedTask == null) - { - _connectionClosedTask = _connection.CloseAsync((long)Http3ErrorCode.NoError).AsTask(); - } + _connectionClosedTask ??= _connection.CloseAsync((long)Http3ErrorCode.NoError).AsTask(); QuicConnection connection = _connection; _connection = null; diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionPool.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionPool.cs index c5c29f1..8bfce77 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionPool.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionPool.cs @@ -855,10 +855,7 @@ namespace System.Net.Http { lock (SyncObj) { - if (_http3ConnectionCreateLock == null) - { - _http3ConnectionCreateLock = new SemaphoreSlim(1); - } + _http3ConnectionCreateLock ??= new SemaphoreSlim(1); } } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpEnvironmentProxy.Unix.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpEnvironmentProxy.Unix.cs index f466dbe..cddca3c 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpEnvironmentProxy.Unix.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpEnvironmentProxy.Unix.cs @@ -32,15 +32,8 @@ namespace System.Net.Http Uri? allProxy = GetUriFromString(Environment.GetEnvironmentVariable(EnvAllProxyLC)) ?? GetUriFromString(Environment.GetEnvironmentVariable(EnvAllProxyUC)); - if (httpProxy == null) - { - httpProxy = allProxy; - } - - if (httpsProxy == null) - { - httpsProxy = allProxy; - } + httpProxy ??= allProxy; + httpsProxy ??= allProxy; } // Do not instantiate if nothing is set. diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpEnvironmentProxy.Windows.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpEnvironmentProxy.Windows.cs index 272235c1..b5370b1 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpEnvironmentProxy.Windows.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpEnvironmentProxy.Windows.cs @@ -24,15 +24,8 @@ namespace System.Net.Http { Uri? allProxy = GetUriFromString(Environment.GetEnvironmentVariable(EnvAllProxyUC)); - if (httpProxy == null) - { - httpProxy = allProxy; - } - - if (httpsProxy == null) - { - httpsProxy = allProxy; - } + httpProxy ??= allProxy; + httpsProxy ??= allProxy; } // Do not instantiate if nothing is set. diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerContext.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerContext.cs index a1e213c..8139792 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerContext.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerContext.cs @@ -20,18 +20,7 @@ namespace System.Net // This can be used to cache the results of HttpListener.AuthenticationSchemeSelectorDelegate. internal AuthenticationSchemes AuthenticationSchemes { get; set; } - public HttpListenerResponse Response - { - get - { - if (_response == null) - { - _response = new HttpListenerResponse(this); - } - - return _response; - } - } + public HttpListenerResponse Response => _response ??= new HttpListenerResponse(this); public Task AcceptWebSocketAsync(string? subProtocol) { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequest.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequest.cs index b44dc6d..473ae22 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequest.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequest.cs @@ -60,10 +60,8 @@ namespace System.Net { _cookies = ParseCookies(RequestUri, cookieString); } - if (_cookies == null) - { - _cookies = new CookieCollection(); - } + + _cookies ??= new CookieCollection(); } return _cookies; } @@ -514,12 +512,9 @@ namespace System.Net internal void AddByte(byte b) { - { - if (_byteBuffer == null) - _byteBuffer = new byte[_bufferSize]; + _byteBuffer ??= new byte[_bufferSize]; - _byteBuffer[_numBytes++] = b; - } + _byteBuffer[_numBytes++] = b; } internal string GetString() diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerResponse.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerResponse.cs index b8aa859..bb52043 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerResponse.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerResponse.cs @@ -161,17 +161,9 @@ namespace System.Net { get { - if (_statusDescription == null) - { - // if the user hasn't set this, generated on the fly, if possible. - // We know this one is safe, no need to verify it as in the setter. - _statusDescription = HttpStatusDescription.Get(StatusCode); - } - if (_statusDescription == null) - { - _statusDescription = string.Empty; - } - return _statusDescription; + // if the user hasn't set this, generate on the fly, if possible. + // We know this one is safe, no need to verify it as in the setter. + return _statusDescription ??= HttpStatusDescription.Get(StatusCode) ?? string.Empty; } set { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpConnection.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpConnection.cs index bab09a5..96a85b9 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpConnection.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpConnection.cs @@ -91,13 +91,7 @@ namespace System.Net return true; } - var c2 = c as X509Certificate2; - if (c2 == null) - { - c2 = new X509Certificate2(c.GetRawCertData()); - } - - _clientCert = c2; + _clientCert = c as X509Certificate2 ?? new X509Certificate2(c.GetRawCertData()); _clientCertErrors = new int[] { (int)e }; return true; }); @@ -192,8 +186,7 @@ namespace System.Net public void BeginReadRequest() { - if (_buffer == null) - _buffer = new byte[BufferSize]; + _buffer ??= new byte[BufferSize]; try { if (_reuses == 1) @@ -409,8 +402,7 @@ namespace System.Net private string? ReadLine(byte[] buffer, int offset, int len, ref int used) { - if (_currentLine == null) - _currentLine = new StringBuilder(128); + _currentLine ??= new StringBuilder(128); int last = offset + len; used = 0; for (int i = offset; i < last && _lineState != LineState.LF; i++) diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerResponse.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerResponse.Managed.cs index 728e784..506a980 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerResponse.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerResponse.Managed.cs @@ -52,10 +52,7 @@ namespace System.Net private void EnsureResponseStream() { - if (_responseStream == null) - { - _responseStream = _httpContext!.Connection.GetResponseStream(); - } + _responseStream ??= _httpContext!.Connection.GetResponseStream(); } public Version ProtocolVersion diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpStreamAsyncResult.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpStreamAsyncResult.cs index d0c5b1c8..53be0f5 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpStreamAsyncResult.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpStreamAsyncResult.cs @@ -88,8 +88,7 @@ namespace System.Net { lock (_locker) { - if (_handle == null) - _handle = new ManualResetEvent(_completed); + _handle ??= new ManualResetEvent(_completed); } return _handle; diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ListenerAsyncResult.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ListenerAsyncResult.Managed.cs index 91cdec0..4e7d5b4 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ListenerAsyncResult.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ListenerAsyncResult.Managed.cs @@ -220,8 +220,7 @@ namespace System.Net lock (_locker) { - if (_handle == null) - _handle = new ManualResetEvent(_completed); + _handle ??= new ManualResetEvent(_completed); } return _handle; diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/ServiceNameStore.cs b/src/libraries/System.Net.HttpListener/src/System/Net/ServiceNameStore.cs index 39e1f42..013db59 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/ServiceNameStore.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/ServiceNameStore.cs @@ -14,17 +14,7 @@ namespace System.Net private readonly List _serviceNames; private ServiceNameCollection? _serviceNameCollection; - public ServiceNameCollection ServiceNames - { - get - { - if (_serviceNameCollection == null) - { - _serviceNameCollection = new ServiceNameCollection(_serviceNames); - } - return _serviceNameCollection; - } - } + public ServiceNameCollection ServiceNames => _serviceNameCollection ??= new ServiceNameCollection(_serviceNames); public ServiceNameStore() { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs index 6c47d53..7a530aa 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs @@ -573,10 +573,7 @@ namespace System.Net } // HandleAuthentication may have cleaned this up. - if (memoryBlob == null) - { - memoryBlob = new SyncRequestContext(checked((int)size)); - } + memoryBlob ??= new SyncRequestContext(checked((int)size)); requestId = 0; } @@ -788,13 +785,8 @@ namespace System.Net ExtendedProtectionSelector? extendedProtectionSelector = _extendedProtectionSelectorDelegate; if (extendedProtectionSelector != null) { - extendedProtectionPolicy = extendedProtectionSelector(httpContext.Request); - - if (extendedProtectionPolicy == null) - { - extendedProtectionPolicy = new ExtendedProtectionPolicy(PolicyEnforcement.Never); - } // Cache the results of extendedProtectionSelector (if any) + extendedProtectionPolicy = extendedProtectionSelector(httpContext.Request) ?? new ExtendedProtectionPolicy(PolicyEnforcement.Never); httpContext.ExtendedProtectionPolicy = extendedProtectionPolicy; } @@ -1518,10 +1510,7 @@ namespace System.Net if (challenge.Length > 0) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, "challenge:" + challenge); - if (challenges == null) - { - challenges = new ArrayList(4); - } + challenges ??= new ArrayList(4); challenges.Add(challenge); } } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequest.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequest.Windows.cs index 2176ccd..8807cdc 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequest.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequest.Windows.cs @@ -190,10 +190,7 @@ namespace System.Net { get { - if (_webHeaders == null) - { - _webHeaders = Interop.HttpApi.GetHeaders(RequestBuffer, OriginalBlobAddress); - } + _webHeaders ??= Interop.HttpApi.GetHeaders(RequestBuffer, OriginalBlobAddress); if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"webHeaders:{_webHeaders}"); return _webHeaders; } @@ -203,26 +200,13 @@ namespace System.Net { get { - if (_httpMethod == null) - { - _httpMethod = Interop.HttpApi.GetVerb(RequestBuffer, OriginalBlobAddress); - } + _httpMethod ??= Interop.HttpApi.GetVerb(RequestBuffer, OriginalBlobAddress); if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"_httpMethod:{_httpMethod}"); return _httpMethod!; } } - public Stream InputStream - { - get - { - if (_requestStream == null) - { - _requestStream = HasEntityBody ? new HttpRequestStream(HttpListenerContext) : Stream.Null; - } - return _requestStream; - } - } + public Stream InputStream => _requestStream ??= HasEntityBody ? new HttpRequestStream(HttpListenerContext) : Stream.Null; public bool IsAuthenticated { @@ -302,10 +286,7 @@ namespace System.Net { get { - if (_localEndPoint == null) - { - _localEndPoint = Interop.HttpApi.GetLocalEndPoint(RequestBuffer, OriginalBlobAddress); - } + _localEndPoint ??= Interop.HttpApi.GetLocalEndPoint(RequestBuffer, OriginalBlobAddress); if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"_localEndPoint={_localEndPoint}"); return _localEndPoint!; } @@ -528,11 +509,8 @@ namespace System.Net { get { - if (_requestUri == null) - { - _requestUri = HttpListenerRequestUriBuilder.GetRequestUri( - _rawUrl!, RequestScheme, _cookedUrlHost!, _cookedUrlPath!, _cookedUrlQuery!); - } + _requestUri ??= HttpListenerRequestUriBuilder.GetRequestUri( + _rawUrl!, RequestScheme, _cookedUrlHost!, _cookedUrlPath!, _cookedUrlQuery!); if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"_requestUri:{_requestUri}"); return _requestUri; diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerResponse.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerResponse.Windows.cs index f4767d9..78b72b2 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerResponse.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerResponse.Windows.cs @@ -2,12 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Text; -using System.ComponentModel; -using System.Diagnostics; using Microsoft.Win32.SafeHandles; namespace System.Net @@ -124,27 +125,27 @@ namespace System.Net { ContentLength64 = responseEntity.Length; } + EnsureResponseStream(); - Debug.Assert(_responseStream != null); if (willBlock) { try { - _responseStream!.Write(responseEntity, 0, responseEntity.Length); + _responseStream.Write(responseEntity, 0, responseEntity.Length); } catch (Win32Exception) { } finally { - _responseStream!.Close(); + _responseStream.Close(); _responseState = ResponseState.Closed; HttpListenerContext!.Close(); } } else { - _responseStream!.BeginWrite(responseEntity, 0, responseEntity.Length, new AsyncCallback(NonBlockingCloseCallback), null); + _responseStream.BeginWrite(responseEntity, 0, responseEntity.Length, new AsyncCallback(NonBlockingCloseCallback), null); } } @@ -154,8 +155,9 @@ namespace System.Net { return; } + EnsureResponseStream(); - _responseStream!.Close(); + _responseStream.Close(); _responseState = ResponseState.Closed; HttpListenerContext!.Close(); @@ -163,12 +165,10 @@ namespace System.Net internal BoundaryType BoundaryType => _boundaryType; + [MemberNotNull(nameof(_responseStream))] private void EnsureResponseStream() { - if (_responseStream == null) - { - _responseStream = new HttpResponseStream(HttpListenerContext!); - } + _responseStream ??= new HttpResponseStream(HttpListenerContext!); } private void NonBlockingCloseCallback(IAsyncResult asyncResult) diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBase.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBase.cs index 38ee04e..e39b53f 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBase.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBase.cs @@ -922,10 +922,7 @@ namespace System.Net.WebSockets { lock (_thisLock) { - if (_receiveOperation == null) - { - _receiveOperation = new WebSocketOperation.ReceiveOperation(this); - } + _receiveOperation ??= new WebSocketOperation.ReceiveOperation(this); } } } @@ -936,10 +933,7 @@ namespace System.Net.WebSockets { lock (_thisLock) { - if (_sendOperation == null) - { - _sendOperation = new WebSocketOperation.SendOperation(this); - } + _sendOperation ??= new WebSocketOperation.SendOperation(this); } } } diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/MailPriority.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/MailPriority.cs index 6ceea22..81a7c54 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/MailPriority.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/MailPriority.cs @@ -350,10 +350,7 @@ namespace System.Net.Mail internal void PrepareEnvelopeHeaders(bool sendEnvelope, bool allowUnicode) { - if (_headersEncoding == null) - { - _headersEncoding = Encoding.GetEncoding(MimeBasePart.DefaultCharSet); - } + _headersEncoding ??= Encoding.GetEncoding(MimeBasePart.DefaultCharSet); EncodeHeaders(EnvelopeHeaders, allowUnicode); @@ -384,12 +381,7 @@ namespace System.Net.Mail internal void PrepareHeaders(bool sendEnvelope, bool allowUnicode) { - string headerName; - - if (_headersEncoding == null) - { - _headersEncoding = Encoding.GetEncoding(MimeBasePart.DefaultCharSet); - } + _headersEncoding ??= Encoding.GetEncoding(MimeBasePart.DefaultCharSet); //ContentType is written directly to the stream so remove potential user duplicate Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.ContentType)!); @@ -398,7 +390,7 @@ namespace System.Net.Mail // add sender to headers first so that it is written first to allow the IIS smtp svc to // send MAIL FROM with the sender if both sender and from are present - headerName = MailHeaderInfo.GetString(MailHeaderID.Sender)!; + string headerName = MailHeaderInfo.GetString(MailHeaderID.Sender)!; if (Sender != null) { Headers.InternalAdd(headerName, Sender.Encode(headerName.Length, allowUnicode)); diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs index 25ec53c..c7ffda1 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs @@ -104,7 +104,7 @@ namespace System.Net.Mail if (NetEventSource.Log.IsEnabled()) NetEventSource.Associate(this, _transport); _onSendCompletedDelegate = new SendOrPostCallback(SendCompletedWaitCallback); - if (_host != null && _host.Length != 0) + if (!string.IsNullOrEmpty(_host)) { _host = _host.Trim(); } @@ -114,8 +114,7 @@ namespace System.Net.Mail _port = DefaultPort; } - if (_targetName == null) - _targetName = "SMTPSVC/" + _host; + _targetName ??= "SMTPSVC/" + _host; if (_clientDomain == null) { diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpReplyReaderFactory.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpReplyReaderFactory.cs index fc44d01..a13e89b 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpReplyReaderFactory.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpReplyReaderFactory.cs @@ -73,10 +73,7 @@ namespace System.Net.Mail { if (_readState != ReadState.Done) { - if (_byteBuffer == null) - { - _byteBuffer = new byte[SmtpReplyReaderFactory.DefaultBufferSize]; - } + _byteBuffer ??= new byte[SmtpReplyReaderFactory.DefaultBufferSize]; while (0 != Read(caller, _byteBuffer, 0, _byteBuffer.Length)) ; } @@ -310,10 +307,7 @@ namespace System.Net.Mail return Array.Empty(); } - if (_byteBuffer == null) - { - _byteBuffer = new byte[SmtpReplyReaderFactory.DefaultBufferSize]; - } + _byteBuffer ??= new byte[SmtpReplyReaderFactory.DefaultBufferSize]; System.Diagnostics.Debug.Assert(_readState == ReadState.Status0); @@ -398,10 +392,7 @@ namespace System.Net.Mail return; } - if (_parent._byteBuffer == null) - { - _parent._byteBuffer = new byte[SmtpReplyReaderFactory.DefaultBufferSize]; - } + _parent._byteBuffer ??= new byte[SmtpReplyReaderFactory.DefaultBufferSize]; System.Diagnostics.Debug.Assert(_parent._readState == ReadState.Status0); diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mime/MimeBasePart.cs b/src/libraries/System.Net.Mail/src/System/Net/Mime/MimeBasePart.cs index 005f996..50f1d36 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mime/MimeBasePart.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mime/MimeBasePart.cs @@ -162,21 +162,12 @@ namespace System.Net.Mime get { //persist existing info before returning - if (_headers == null) - { - _headers = new HeaderCollection(); - } + _headers ??= new HeaderCollection(); - if (_contentType == null) - { - _contentType = new ContentType(); - } + _contentType ??= new ContentType(); _contentType.PersistIfNeeded(_headers, false); - if (_contentDisposition != null) - { - _contentDisposition.PersistIfNeeded(_headers, false); - } + _contentDisposition?.PersistIfNeeded(_headers, false); return _headers; } diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mime/MimeMultiPart.cs b/src/libraries/System.Net.Mail/src/System/Net/Mime/MimeMultiPart.cs index 59e630c..543e4db 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mime/MimeMultiPart.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mime/MimeMultiPart.cs @@ -40,17 +40,7 @@ namespace System.Net.Mime ContentType.Boundary = GetNextBoundary(); } - internal Collection Parts - { - get - { - if (_parts == null) - { - _parts = new Collection(); - } - return _parts; - } - } + internal Collection Parts => _parts ??= new Collection(); internal static void Complete(IAsyncResult result, Exception? e) { @@ -71,10 +61,7 @@ namespace System.Net.Mime } catch (Exception ex) { - if (e == null) - { - e = ex; - } + e ??= ex; } context._completed = true; context._result.InvokeCallback(e); diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mime/MimePart.cs b/src/libraries/System.Net.Mail/src/System/Net/Mime/MimePart.cs index cf00bba..6b78fd2 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mime/MimePart.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mime/MimePart.cs @@ -160,10 +160,7 @@ namespace System.Net.Mime } catch (Exception ex) { - if (e == null) - { - e = ex; - } + e ??= ex; } context._completed = true; context._result.InvokeCallback(e); diff --git a/src/libraries/System.Net.Mail/src/System/Net/TrackingValidationObjectDictionary.cs b/src/libraries/System.Net.Mail/src/System/Net/TrackingValidationObjectDictionary.cs index e4ede0e..95da9b7 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/TrackingValidationObjectDictionary.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/TrackingValidationObjectDictionary.cs @@ -63,10 +63,7 @@ namespace System.Net // now that the value is valid, ensure that internalObjects exists since we have to // add to it - if (_internalObjects == null) - { - _internalObjects = new Dictionary(); - } + _internalObjects ??= new Dictionary(); if (addValue) { @@ -136,10 +133,7 @@ namespace System.Net { // InternalSet is only used with objects that belong in internalObjects so we must always // initialize it here - if (_internalObjects == null) - { - _internalObjects = new Dictionary(); - } + _internalObjects ??= new Dictionary(); // always replace the existing value when we set internally _internalObjects[key] = value; diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/BsdNetworkInterface.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/BsdNetworkInterface.cs index 20ffcaa..bbce06d 100644 --- a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/BsdNetworkInterface.cs +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/BsdNetworkInterface.cs @@ -64,10 +64,7 @@ namespace System.Net.NetworkInformation internal void AddException(Exception e) { - if (_exceptions == null) - { - _exceptions = new List(); - } + _exceptions ??= new List(); _exceptions.Add(e); } } diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/UnixIPGlobalProperties.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/UnixIPGlobalProperties.cs index 7a9be6b..9884d09 100644 --- a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/UnixIPGlobalProperties.cs +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/UnixIPGlobalProperties.cs @@ -62,10 +62,7 @@ namespace System.Net.NetworkInformation internal void AddException(Exception e) { - if (_exceptions == null) - { - _exceptions = new List(); - } + _exceptions ??= new List(); _exceptions.Add(e); } } diff --git a/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.Windows.cs b/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.Windows.cs index 73a38d9..f34c696 100644 --- a/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.Windows.cs +++ b/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.Windows.cs @@ -57,10 +57,7 @@ namespace System.Net.NetworkInformation // Cache correct handle. InitialiseIcmpHandle(); - if (_replyBuffer == null) - { - _replyBuffer = SafeLocalAllocHandle.LocalAlloc(MaxUdpPacket); - } + _replyBuffer ??= SafeLocalAllocHandle.LocalAlloc(MaxUdpPacket); int error; try diff --git a/src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs b/src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs index 86187da..829785b 100644 --- a/src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs +++ b/src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs @@ -849,12 +849,8 @@ namespace System.Net { while ((dot < last) && (dot = fqdnRemote.IndexOf('.', dot + 1)) != -1) { - if (domainAttributeMatchOnlyCookieVariantPlain == null) - { - domainAttributeMatchOnlyCookieVariantPlain = new System.Collections.Generic.List(); - } - // These candidates can only match CookieVariant.Plain cookies. + domainAttributeMatchOnlyCookieVariantPlain ??= new System.Collections.Generic.List(); domainAttributeMatchOnlyCookieVariantPlain.Add(fqdnRemote.Substring(dot)); } } @@ -985,10 +981,7 @@ namespace System.Net // In 'source' are already ordered. // If two same cookies come from different 'source' then they // will follow (not replace) each other. - if (destination == null) - { - destination = new CookieCollection(); - } + destination ??= new CookieCollection(); destination.InternalAdd(cookie, false); } } diff --git a/src/libraries/System.Net.Primitives/src/System/Net/CredentialCache.cs b/src/libraries/System.Net.Primitives/src/System/Net/CredentialCache.cs index 5369513..1065905 100644 --- a/src/libraries/System.Net.Primitives/src/System/Net/CredentialCache.cs +++ b/src/libraries/System.Net.Primitives/src/System/Net/CredentialCache.cs @@ -41,11 +41,7 @@ namespace System.Net if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Adding key:[{key}], cred:[{cred.Domain}],[{cred.UserName}]"); - if (_cache == null) - { - _cache = new Dictionary(); - } - + _cache ??= new Dictionary(); _cache.Add(key, cred); } @@ -74,11 +70,7 @@ namespace System.Net if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Adding key:[{key}], cred:[{credential.Domain}],[{credential.UserName}]"); - if (_cacheForHosts == null) - { - _cacheForHosts = new Dictionary(); - } - + _cacheForHosts ??= new Dictionary(); _cacheForHosts.Add(key, credential); } diff --git a/src/libraries/System.Net.Primitives/src/System/Net/IPAddress.cs b/src/libraries/System.Net.Primitives/src/System/Net/IPAddress.cs index a43c462..d1fefb0 100644 --- a/src/libraries/System.Net.Primitives/src/System/Net/IPAddress.cs +++ b/src/libraries/System.Net.Primitives/src/System/Net/IPAddress.cs @@ -362,17 +362,10 @@ namespace System.Net /// or standard IPv6 representation. /// /// - public override string ToString() - { - if (_toString == null) - { - _toString = IsIPv4 ? - IPAddressParser.IPv4AddressToString(PrivateAddress) : - IPAddressParser.IPv6AddressToString(_numbers!, PrivateScopeId); - } - - return _toString; - } + public override string ToString() => + _toString ??= IsIPv4 ? + IPAddressParser.IPv4AddressToString(PrivateAddress) : + IPAddressParser.IPv6AddressToString(_numbers!, PrivateScopeId); public bool TryFormat(Span destination, out int charsWritten) { diff --git a/src/libraries/System.Net.Requests/src/System/Net/FtpControlStream.cs b/src/libraries/System.Net.Requests/src/System/Net/FtpControlStream.cs index 5b21bd4..2394024 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/FtpControlStream.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/FtpControlStream.cs @@ -64,10 +64,7 @@ namespace System.Net } set { - if (_credentials == null) - { - _credentials = new WeakReference(null); - } + _credentials ??= new WeakReference(null); _credentials.Target = value; } } diff --git a/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs b/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs index 8bb7b99..79b050d 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs @@ -514,11 +514,8 @@ namespace System.Net } networkCredential = new NetworkCredential(username, password); } - if (networkCredential == null) - { - networkCredential = s_defaultFtpNetworkCredential; - } - _authInfo = networkCredential; + + _authInfo = networkCredential ?? s_defaultFtpNetworkCredential; } // @@ -997,8 +994,7 @@ namespace System.Net if (isAsync) { // non-null in the case of re-submit (recovery) - if (_requestCompleteAsyncResult == null) - _requestCompleteAsyncResult = new LazyAsyncResult(null, null, null); + _requestCompleteAsyncResult ??= new LazyAsyncResult(null, null, null); return _connection!.SubmitRequest(this, true, true)!; } @@ -1058,18 +1054,7 @@ namespace System.Net } } - private TimerThread.Queue TimerQueue - { - get - { - if (_timerQueue == null) - { - _timerQueue = TimerThread.GetOrCreateQueue(RemainingTimeout); - } - - return _timerQueue; - } - } + private TimerThread.Queue TimerQueue => _timerQueue ??= TimerThread.GetOrCreateQueue(RemainingTimeout); /// /// Returns true if we should restart the request after an error @@ -1578,18 +1563,8 @@ namespace System.Net public override WebHeaderCollection Headers { - get - { - if (_ftpRequestHeaders == null) - { - _ftpRequestHeaders = new WebHeaderCollection(); - } - return _ftpRequestHeaders; - } - set - { - _ftpRequestHeaders = value; - } + get => _ftpRequestHeaders ??= new WebHeaderCollection(); + set => _ftpRequestHeaders = value; } // NOT SUPPORTED method diff --git a/src/libraries/System.Net.Requests/src/System/Net/FtpWebResponse.cs b/src/libraries/System.Net.Requests/src/System/Net/FtpWebResponse.cs index 0c1b2de..a19f168 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/FtpWebResponse.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/FtpWebResponse.cs @@ -101,10 +101,7 @@ namespace System.Net { lock (this) { - if (_ftpRequestHeaders == null) - { - _ftpRequestHeaders = new WebHeaderCollection(); - } + _ftpRequestHeaders ??= new WebHeaderCollection(); } } return _ftpRequestHeaders; diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/NetEventSource.Security.cs b/src/libraries/System.Net.Security/src/System/Net/Security/NetEventSource.Security.cs index 684c481..c5875e6 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/NetEventSource.Security.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/NetEventSource.Security.cs @@ -76,10 +76,7 @@ namespace System.Net catch { }; } - if (localId == null) - { - localId = IdOf(innerStream); - } + localId ??= IdOf(innerStream); SslStreamCtor(IdOf(sslStream), localId, remoteId); } diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.IO.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.IO.cs index 3b01821..3845144 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.IO.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.IO.cs @@ -39,10 +39,7 @@ namespace System.Net.Security { Debug.Assert(e != null, $"Expected non-null Exception to be passed to {nameof(SetException)}"); - if (_exception == null) - { - _exception = ExceptionDispatchInfo.Capture(e); - } + _exception ??= ExceptionDispatchInfo.Capture(e); CloseContext(); } diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.Protocol.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.Protocol.cs index bc7b968..f815a86 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.Protocol.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.Protocol.cs @@ -251,10 +251,7 @@ namespace System.Net.Security { issuers = GetRequestCertificateAuthorities(); remoteCert = CertificateValidationPal.GetRemoteCertificate(_securityContext); - if (_sslAuthenticationOptions.ClientCertificates == null) - { - _sslAuthenticationOptions.ClientCertificates = new X509CertificateCollection(); - } + _sslAuthenticationOptions.ClientCertificates ??= new X509CertificateCollection(); clientCertificate = _sslAuthenticationOptions.CertSelectionDelegate(this, _sslAuthenticationOptions.TargetHost, _sslAuthenticationOptions.ClientCertificates, remoteCert, issuers); } finally @@ -946,11 +943,7 @@ namespace System.Net.Security } else { - if (chain == null) - { - chain = new X509Chain(); - } - + chain ??= new X509Chain(); chain.ChainPolicy.RevocationMode = _sslAuthenticationOptions.CertificateRevocationCheckMode; chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot; diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Windows.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Windows.cs index 3baab06..ba41243 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Windows.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Windows.cs @@ -493,10 +493,7 @@ namespace System.Net.Sockets PinSocketAddressBuffer(); // Create a WSAMessageBuffer if none exists yet. - if (_wsaMessageBufferPinned == null) - { - _wsaMessageBufferPinned = GC.AllocateUninitializedArray(sizeof(Interop.Winsock.WSAMsg), pinned: true); - } + _wsaMessageBufferPinned ??= GC.AllocateUninitializedArray(sizeof(Interop.Winsock.WSAMsg), pinned: true); // Create and pin an appropriately sized control buffer if none already IPAddress? ipAddress = (_socketAddress!.Family == AddressFamily.InterNetworkV6 ? _socketAddress.GetIPAddress() : null); @@ -517,10 +514,7 @@ namespace System.Net.Sockets uint wsaRecvMsgWSABufferCount; if (_bufferList == null) { - if (_wsaRecvMsgWSABufferArrayPinned == null) - { - _wsaRecvMsgWSABufferArrayPinned = GC.AllocateUninitializedArray(1, pinned: true); - } + _wsaRecvMsgWSABufferArrayPinned ??= GC.AllocateUninitializedArray(1, pinned: true); fixed (byte* bufferPtr = &MemoryMarshal.GetReference(_buffer.Span)) { diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/TCPClient.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/TCPClient.cs index d4a5013..83b10b0 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/TCPClient.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/TCPClient.cs @@ -244,12 +244,7 @@ namespace System.Net.Sockets throw new InvalidOperationException(SR.net_notconnected); } - if (_dataStream == null) - { - _dataStream = new NetworkStream(Client, true); - } - - return _dataStream; + return _dataStream ??= new NetworkStream(Client, true); } public void Close() => Dispose(); diff --git a/src/libraries/System.Net.WebClient/src/System/Net/WebClient.cs b/src/libraries/System.Net.WebClient/src/System/Net/WebClient.cs index 24584ac..a73a0be 100644 --- a/src/libraries/System.Net.WebClient/src/System/Net/WebClient.cs +++ b/src/libraries/System.Net.WebClient/src/System/Net/WebClient.cs @@ -1161,10 +1161,7 @@ namespace System.Net } // Do we have an encoding guess? If not, use default. - if (enc == null) - { - enc = Encoding; - } + enc ??= Encoding; // Calculate BOM length based on encoding guess. Then check for it in the data. if (bomLengthInData == -1) diff --git a/src/libraries/System.Net.WebHeaderCollection/src/System/Net/WebHeaderCollection.cs b/src/libraries/System.Net.WebHeaderCollection/src/System/Net/WebHeaderCollection.cs index 9956316..ef803b8 100644 --- a/src/libraries/System.Net.WebHeaderCollection/src/System/Net/WebHeaderCollection.cs +++ b/src/libraries/System.Net.WebHeaderCollection/src/System/Net/WebHeaderCollection.cs @@ -45,27 +45,9 @@ namespace System.Net } } - private static HeaderInfoTable HeaderInfo - { - get - { - if (_headerInfo == null) - { - _headerInfo = new HeaderInfoTable(); - } - return _headerInfo; - } - } + private static HeaderInfoTable HeaderInfo => _headerInfo ??= new HeaderInfoTable(); - private NameValueCollection InnerCollection - { - get - { - if (_innerCollection == null) - _innerCollection = new NameValueCollection(ApproxHighAvgNumHeaders, CaseInsensitiveAscii.StaticInstance); - return _innerCollection; - } - } + private NameValueCollection InnerCollection => _innerCollection ??= new NameValueCollection(ApproxHighAvgNumHeaders, CaseInsensitiveAscii.StaticInstance); private bool AllowHttpResponseHeader { diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs index 199bf2d..f17834f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs @@ -1706,13 +1706,10 @@ namespace System.Diagnostics.Tracing private static Guid GenerateGuidFromName(string name) { #if ES_BUILD_STANDALONE - if (namespaceBytes == null) - { - namespaceBytes = new byte[] { - 0x48, 0x2C, 0x2D, 0xB2, 0xC3, 0x90, 0x47, 0xC8, - 0x87, 0xF8, 0x1A, 0x15, 0xBF, 0xC1, 0x30, 0xFB, - }; - } + namespaceBytes ??= new byte[] { + 0x48, 0x2C, 0x2D, 0xB2, 0xC3, 0x90, 0x47, 0xC8, + 0x87, 0xF8, 0x1A, 0x15, 0xBF, 0xC1, 0x30, 0xFB, + }; #else ReadOnlySpan namespaceBytes = new byte[] // rely on C# compiler optimization to remove byte[] allocation { diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/DataCollector.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/DataCollector.cs index 19bf2e0..9c30fdd 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/DataCollector.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/DataCollector.cs @@ -147,10 +147,7 @@ namespace System.Diagnostics.Tracing internal void AddNullTerminatedString(string? value) { // Treat null strings as empty strings. - if (value == null) - { - value = string.Empty; - } + value ??= string.Empty; // Calculate the size of the string including the trailing NULL char. // Don't use value.Length here because string allows for embedded NULL characters. diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TypeAnalysis.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TypeAnalysis.cs index 6fdbe7b..051eef8 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TypeAnalysis.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TypeAnalysis.cs @@ -97,10 +97,7 @@ namespace System.Diagnostics.Tracing this.name = eventAttrib.Name; } - if (this.name == null) - { - this.name = dataType.Name; - } + this.name ??= dataType.Name; } } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormatInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormatInfo.cs index 8f9a555..e5c85f5 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormatInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormatInfo.cs @@ -260,22 +260,10 @@ namespace System.Globalization calendarWeekRule = cultureData.CalendarWeekRule; } - if (amDesignator == null) - { - amDesignator = cultureData.AMDesignator; - } - if (pmDesignator == null) - { - pmDesignator = cultureData.PMDesignator; - } - if (timeSeparator == null) - { - timeSeparator = cultureData.TimeSeparator; - } - if (dateSeparator == null) - { - dateSeparator = cultureData.DateSeparator(calendarId); - } + amDesignator ??= cultureData.AMDesignator; + pmDesignator ??= cultureData.PMDesignator; + timeSeparator ??= cultureData.TimeSeparator; + dateSeparator ??= cultureData.DateSeparator(calendarId); allLongTimePatterns = _cultureData.LongTimes; Debug.Assert(allLongTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long time patterns"); @@ -358,11 +346,7 @@ namespace System.Globalization { get { - if (amDesignator == null) - { - amDesignator = _cultureData.AMDesignator; - } - + amDesignator ??= _cultureData.AMDesignator; Debug.Assert(amDesignator != null, "DateTimeFormatInfo.AMDesignator, amDesignator != null"); return amDesignator; } @@ -599,10 +583,7 @@ namespace System.Globalization { get { - if (dateSeparator == null) - { - dateSeparator = _cultureData.DateSeparator(Calendar.ID); - } + dateSeparator ??= _cultureData.DateSeparator(Calendar.ID); Debug.Assert(dateSeparator != null, "DateTimeFormatInfo.DateSeparator, dateSeparator != null"); return dateSeparator; } @@ -796,11 +777,7 @@ namespace System.Globalization { get { - if (pmDesignator == null) - { - pmDesignator = _cultureData.PMDesignator; - } - + pmDesignator ??= _cultureData.PMDesignator; Debug.Assert(pmDesignator != null, "DateTimeFormatInfo.PMDesignator, pmDesignator != null"); return pmDesignator; } @@ -975,10 +952,7 @@ namespace System.Globalization { get { - if (timeSeparator == null) - { - timeSeparator = _cultureData.TimeSeparator; - } + timeSeparator ??= _cultureData.TimeSeparator; Debug.Assert(timeSeparator != null, "DateTimeFormatInfo.TimeSeparator, timeSeparator != null"); return timeSeparator; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/OrdinalCasing.Icu.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/OrdinalCasing.Icu.cs index 6a3851b..af44c2d 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/OrdinalCasing.Icu.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/OrdinalCasing.Icu.cs @@ -137,10 +137,7 @@ namespace System.Globalization return c; } - if (casingTable == null) - { - casingTable = InitOrdinalCasingPage(pageNumber); - } + casingTable ??= InitOrdinalCasingPage(pageNumber); return (char) casingTable[((int)c) & 0xFF]; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/TextInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/TextInfo.cs index 9edb161..547601d 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/TextInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/TextInfo.cs @@ -708,10 +708,7 @@ namespace System.Globalization i++; if (hasLowerCase) { - if (lowercaseData == null) - { - lowercaseData = ToLower(str); - } + lowercaseData ??= ToLower(str); result.Append(lowercaseData, lowercaseStart, i - lowercaseStart); } else @@ -740,10 +737,7 @@ namespace System.Globalization { if (hasLowerCase) { - if (lowercaseData == null) - { - lowercaseData = ToLower(str); - } + lowercaseData ??= ToLower(str); result.Append(lowercaseData, lowercaseStart, count); } else diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/BufferedStream.cs b/src/libraries/System.Private.CoreLib/src/System/IO/BufferedStream.cs index 5c25031..aabdf3c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/BufferedStream.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/BufferedStream.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -125,13 +126,13 @@ namespace System.IO _buffer = shadowBuffer; } + [MemberNotNull(nameof(_buffer))] private void EnsureBufferAllocated() { Debug.Assert(_bufferSize > 0); // BufferedStream is not intended for multi-threaded use, so no worries about the get/set race on _buffer. - if (_buffer == null) - _buffer = new byte[_bufferSize]; + _buffer ??= new byte[_bufferSize]; } public Stream UnderlyingStream @@ -510,7 +511,7 @@ namespace System.IO // Ok. We can fill the buffer: EnsureBufferAllocated(); - _readLen = _stream.Read(_buffer!, 0, _bufferSize); + _readLen = _stream.Read(_buffer, 0, _bufferSize); bytesFromBuffer = ReadFromBuffer(buffer, offset, count); @@ -564,7 +565,7 @@ namespace System.IO { // Otherwise, fill the buffer, then read from that. EnsureBufferAllocated(); - _readLen = _stream.Read(_buffer!, 0, _bufferSize); + _readLen = _stream.Read(_buffer, 0, _bufferSize); return ReadFromBuffer(destination) + bytesFromBuffer; } } @@ -753,13 +754,13 @@ namespace System.IO FlushWrite(); EnsureBufferAllocated(); - _readLen = _stream.Read(_buffer!, 0, _bufferSize); + _readLen = _stream.Read(_buffer, 0, _bufferSize); _readPos = 0; if (_readLen == 0) return -1; - return _buffer![_readPos++]; + return _buffer[_readPos++]; } private void WriteToBuffer(byte[] buffer, ref int offset, ref int count) @@ -770,7 +771,7 @@ namespace System.IO return; EnsureBufferAllocated(); - Buffer.BlockCopy(buffer, offset, _buffer!, _writePos, bytesToWrite); + Buffer.BlockCopy(buffer, offset, _buffer, _writePos, bytesToWrite); _writePos += bytesToWrite; count -= bytesToWrite; diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemEnumerator.Unix.cs b/src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemEnumerator.Unix.cs index 430088b..7262476 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemEnumerator.Unix.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemEnumerator.Unix.cs @@ -147,8 +147,7 @@ namespace System.IO.Enumeration if (_options.RecurseSubdirectories && _remainingRecursionDepth > 0 && ShouldRecurseIntoEntry(ref entry)) { // Recursion is on and the directory was accepted, Queue it - if (_pending == null) - _pending = new Queue<(string Path, int RemainingDepth)>(); + _pending ??= new Queue<(string Path, int RemainingDepth)>(); _pending.Enqueue((Path.Join(_currentPath, entry.FileName), _remainingRecursionDepth - 1)); } } diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemEnumerator.Windows.cs b/src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemEnumerator.Windows.cs index 30f447a..f183eae 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemEnumerator.Windows.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemEnumerator.Windows.cs @@ -248,8 +248,7 @@ namespace System.IO.Enumeration { try { - if (_pending == null) - _pending = new Queue<(IntPtr, string, int)>(); + _pending ??= new Queue<(IntPtr, string, int)>(); _pending.Enqueue((subDirectoryHandle, subDirectory, _remainingRecursionDepth - 1)); } catch diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/FileSystem.Windows.cs b/src/libraries/System.Private.CoreLib/src/System/IO/FileSystem.Windows.cs index c9ecc55..7336251 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/FileSystem.Windows.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/FileSystem.Windows.cs @@ -331,8 +331,7 @@ namespace System.IO } catch (Exception e) { - if (exception == null) - exception = e; + exception ??= e; } } else diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/StreamReader.cs b/src/libraries/System.Private.CoreLib/src/System/IO/StreamReader.cs index 2b88da7..b0d39ed 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/StreamReader.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/StreamReader.cs @@ -140,14 +140,12 @@ namespace System.IO { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.stream); } - if (encoding == null) - { - encoding = Encoding.UTF8; - } + if (!stream.CanRead) { throw new ArgumentException(SR.Argument_StreamNotReadable); } + if (bufferSize == -1) { bufferSize = DefaultBufferSize; @@ -158,7 +156,7 @@ namespace System.IO } _stream = stream; - _encoding = encoding; + _encoding = encoding ??= Encoding.UTF8; _decoder = encoding.GetDecoder(); if (bufferSize < MinBufferSize) { diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/StreamWriter.cs b/src/libraries/System.Private.CoreLib/src/System/IO/StreamWriter.cs index d3c4ded..0c0c6e1 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/StreamWriter.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/StreamWriter.cs @@ -97,14 +97,12 @@ namespace System.IO { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.stream); } - if (encoding == null) - { - encoding = UTF8NoBOM; - } + if (!stream.CanWrite) { throw new ArgumentException(SR.Argument_StreamNotWritable); } + if (bufferSize == -1) { bufferSize = DefaultBufferSize; @@ -115,7 +113,7 @@ namespace System.IO } _stream = stream; - _encoding = encoding; + _encoding = encoding ?? UTF8NoBOM; _encoder = _encoding.GetEncoder(); if (bufferSize < MinBufferSize) { diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/StringWriter.cs b/src/libraries/System.Private.CoreLib/src/System/IO/StringWriter.cs index eba845f..97584ac 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/StringWriter.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/StringWriter.cs @@ -57,17 +57,7 @@ namespace System.IO } - public override Encoding Encoding - { - get - { - if (s_encoding == null) - { - s_encoding = new UnicodeEncoding(false, false); - } - return s_encoding; - } - } + public override Encoding Encoding => s_encoding ??= new UnicodeEncoding(false, false); // Returns the underlying StringBuilder. This is either the StringBuilder // that was passed to the constructor, or the StringBuilder that was diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/TextWriter.cs b/src/libraries/System.Private.CoreLib/src/System/IO/TextWriter.cs index 131a019..a8ba471 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/TextWriter.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/TextWriter.cs @@ -110,10 +110,7 @@ namespace System.IO get => CoreNewLineStr; set { - if (value == null) - { - value = Environment.NewLineConst; - } + value ??= Environment.NewLineConst; CoreNewLineStr = value; CoreNewLine = value.ToCharArray(); diff --git a/src/libraries/System.Private.CoreLib/src/System/Net/WebUtility.cs b/src/libraries/System.Private.CoreLib/src/System/Net/WebUtility.cs index 257b0e1..56806be 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Net/WebUtility.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Net/WebUtility.cs @@ -722,8 +722,7 @@ namespace System.Net private void FlushBytes() { Debug.Assert(_numBytes > 0); - if (_charBuffer == null) - _charBuffer = new char[_bufferSize]; + _charBuffer ??= new char[_bufferSize]; _numChars += _encoding.GetChars(_byteBuffer!, 0, _numBytes, _charBuffer, _numChars); _numBytes = 0; @@ -746,16 +745,14 @@ namespace System.Net if (_numBytes > 0) FlushBytes(); - if (_charBuffer == null) - _charBuffer = new char[_bufferSize]; + _charBuffer ??= new char[_bufferSize]; _charBuffer[_numChars++] = ch; } internal void AddByte(byte b) { - if (_byteBuffer == null) - _byteBuffer = new byte[_bufferSize]; + _byteBuffer ??= new byte[_bufferSize]; _byteBuffer[_numBytes++] = b; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/Versioning/FrameworkName.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/Versioning/FrameworkName.cs index 5c492e7..ad22a86 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/Versioning/FrameworkName.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/Versioning/FrameworkName.cs @@ -50,12 +50,9 @@ namespace System.Runtime.Versioning { get { - if (_fullName == null) - { - _fullName = string.IsNullOrEmpty(Profile) ? - $"{Identifier}{ComponentSeparator + VersionKey + KeyValueSeparator + VersionValuePrefix}{Version}" : - $"{Identifier}{ComponentSeparator + VersionKey + KeyValueSeparator + VersionValuePrefix}{Version}{ComponentSeparator + ProfileKey + KeyValueSeparator}{Profile}"; - } + _fullName ??= string.IsNullOrEmpty(Profile) ? + $"{Identifier}{ComponentSeparator + VersionKey + KeyValueSeparator + VersionValuePrefix}{Version}" : + $"{Identifier}{ComponentSeparator + VersionKey + KeyValueSeparator + VersionValuePrefix}{Version}{ComponentSeparator + ProfileKey + KeyValueSeparator}{Profile}"; Debug.Assert(_fullName != null); return _fullName; diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs b/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs index 3b8f462..398bc70 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs @@ -129,10 +129,8 @@ namespace System.Text throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex); } - if (value == null) - { - value = string.Empty; - } + value ??= string.Empty; + if (startIndex > value.Length - length) { throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_IndexLength); @@ -212,10 +210,7 @@ namespace System.Text } // Check values and set defaults - if (persistedString == null) - { - persistedString = string.Empty; - } + persistedString ??= string.Empty; if (persistedMaxCapacity < 1 || persistedString.Length > persistedMaxCapacity) { throw new SerializationException(SR.Serialization_StringBuilderMaxCapacity); diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/PortableThreadPool.WaitThread.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/PortableThreadPool.WaitThread.cs index c5932c9..b9c1813 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/PortableThreadPool.WaitThread.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/PortableThreadPool.WaitThread.cs @@ -45,11 +45,7 @@ namespace System.Threading _waitThreadLock.Acquire(); try { - WaitThreadNode? current = _waitThreadsHead; - if (current == null) // Lazily create the first wait thread. - { - _waitThreadsHead = current = new WaitThreadNode(new WaitThread()); - } + WaitThreadNode? current = _waitThreadsHead ??= new WaitThreadNode(new WaitThread()); // Lazily create the first wait thread. // Register the wait handle on the first wait thread that is not at capacity. WaitThreadNode prev; diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskExceptionHolder.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskExceptionHolder.cs index a3277c5..4d9a68f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskExceptionHolder.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskExceptionHolder.cs @@ -145,9 +145,7 @@ namespace System.Threading.Tasks Debug.Assert(exceptionObject != null, "AddFaultException(): Expected a non-null exceptionObject"); // Initialize the exceptions list if necessary. The list should be non-null iff it contains exceptions. - List? exceptions = m_faultExceptions; - if (exceptions == null) m_faultExceptions = exceptions = new List(1); - else Debug.Assert(exceptions.Count > 0, "Expected existing exceptions list to have > 0 exceptions."); + List? exceptions = m_faultExceptions ??= new List(1); // Handle Exception by capturing it into an ExceptionDispatchInfo and storing that if (exceptionObject is Exception exception) diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/TimerQueue.Portable.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/TimerQueue.Portable.cs index 373f7ab..1177300 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/TimerQueue.Portable.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/TimerQueue.Portable.cs @@ -59,11 +59,7 @@ namespace System.Threading { if (!_isScheduled) { - List? timers = s_scheduledTimers; - if (timers == null) - { - timers = InitializeScheduledTimerManager_Locked(); - } + List timers = s_scheduledTimers ?? InitializeScheduledTimerManager_Locked(); timers.Add(this); _isScheduled = true; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ClassDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ClassDataContract.cs index beb3040..1200e4e 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ClassDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ClassDataContract.cs @@ -204,18 +204,7 @@ namespace System.Runtime.Serialization } private Func? _makeNewInstance; - private Func MakeNewInstance - { - get - { - if (_makeNewInstance == null) - { - _makeNewInstance = FastInvokerBuilder.GetMakeNewInstanceFunc(UnderlyingType); - } - - return _makeNewInstance; - } - } + private Func MakeNewInstance => _makeNewInstance ??= FastInvokerBuilder.GetMakeNewInstanceFunc(UnderlyingType); internal bool CreateNewInstanceViaDefaultConstructor([NotNullWhen(true)] out object? obj) { @@ -1487,15 +1476,7 @@ namespace System.Runtime.Serialization set { _childElementNamespaces = value; } } - private static Type[] SerInfoCtorArgs - { - get - { - if (s_serInfoCtorArgs == null) - s_serInfoCtorArgs = new Type[] { typeof(SerializationInfo), typeof(StreamingContext) }; - return s_serInfoCtorArgs; - } - } + private static Type[] SerInfoCtorArgs => s_serInfoCtorArgs ??= new Type[] { typeof(SerializationInfo), typeof(StreamingContext) }; internal struct Member { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CodeGenerator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CodeGenerator.cs index 0879bcd..b39d1af 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CodeGenerator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CodeGenerator.cs @@ -91,17 +91,8 @@ namespace System.Runtime.Serialization private Type _delegateType = null!; // initialized in BeginMethod private static Module? s_serializationModule; - private static Module SerializationModule - { - get - { - if (s_serializationModule == null) - { - s_serializationModule = typeof(CodeGenerator).Module; // could to be replaced by different dll that has SkipVerification set to false - } - return s_serializationModule; - } - } + private static Module SerializationModule => s_serializationModule ??= typeof(CodeGenerator).Module; // could to be replaced by different dll that has SkipVerification set to false + private DynamicMethod _dynamicMethod = null!; // initialized in BeginMethod private ILGenerator _ilGen = null!; // initialized in BeginMethod @@ -1470,8 +1461,7 @@ namespace System.Runtime.Serialization internal void CallStringFormat(string msg, params object[] values) { NewArray(typeof(object), values.Length); - if (_stringFormatArray == null) - _stringFormatArray = DeclareLocal(typeof(object[]), "stringFormatArray"); + _stringFormatArray ??= DeclareLocal(typeof(object[]), "stringFormatArray"); Stloc(_stringFormatArray); for (int i = 0; i < values.Length; i++) StoreArrayElement(_stringFormatArray, i, values[i]); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CollectionDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CollectionDataContract.cs index 41f0548..f566308 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CollectionDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CollectionDataContract.cs @@ -684,11 +684,9 @@ namespace System.Runtime.Serialization } else { - _itemContract = DataContract.GetDataContractFromGeneratedAssembly(ItemType); - if (_itemContract == null) - { - _itemContract = DataContract.GetDataContract(ItemType); - } + _itemContract = + DataContract.GetDataContractFromGeneratedAssembly(ItemType) ?? + DataContract.GetDataContract(ItemType); } } return _itemContract; @@ -857,25 +855,14 @@ namespace System.Runtime.Serialization private static MethodInfo? s_buildIncrementCollectionCountDelegateMethod; - private static MethodInfo BuildIncrementCollectionCountDelegateMethod - { - get - { - if (s_buildIncrementCollectionCountDelegateMethod == null) - { - s_buildIncrementCollectionCountDelegateMethod = typeof(CollectionDataContractCriticalHelper).GetMethod(nameof(BuildIncrementCollectionCountDelegate), Globals.ScanAllMembers)!; - } - - return s_buildIncrementCollectionCountDelegateMethod; - } - } + private static MethodInfo BuildIncrementCollectionCountDelegateMethod => + s_buildIncrementCollectionCountDelegateMethod ??= typeof(CollectionDataContractCriticalHelper).GetMethod(nameof(BuildIncrementCollectionCountDelegate), Globals.ScanAllMembers)!; private static IncrementCollectionCountDelegate BuildIncrementCollectionCountDelegate() { return (xmlwriter, obj, context) => { context.IncrementCollectionCountGeneric(xmlwriter, (ICollection)obj); - }; } @@ -965,18 +952,8 @@ namespace System.Runtime.Serialization private static MethodInfo? s_buildCreateGenericDictionaryEnumerator; - private static MethodInfo GetBuildCreateGenericDictionaryEnumeratorMethodInfo - { - get - { - if (s_buildCreateGenericDictionaryEnumerator == null) - { - s_buildCreateGenericDictionaryEnumerator = typeof(CollectionDataContractCriticalHelper).GetMethod(nameof(BuildCreateGenericDictionaryEnumerator), Globals.ScanAllMembers)!; - } - - return s_buildCreateGenericDictionaryEnumerator; - } - } + private static MethodInfo GetBuildCreateGenericDictionaryEnumeratorMethodInfo => + s_buildCreateGenericDictionaryEnumerator ??= typeof(CollectionDataContractCriticalHelper).GetMethod(nameof(BuildCreateGenericDictionaryEnumerator), Globals.ScanAllMembers)!; private static CreateGenericDictionaryEnumeratorDelegate BuildCreateGenericDictionaryEnumerator() { @@ -1439,9 +1416,9 @@ namespace System.Runtime.Serialization getEnumeratorMethod = type.GetMethod(Globals.GetEnumeratorMethodName, BindingFlags.Instance | BindingFlags.Public, Type.EmptyTypes); if (getEnumeratorMethod == null || !Globals.TypeOfIEnumerator.IsAssignableFrom(getEnumeratorMethod.ReturnType)) { - Type? ienumerableInterface = interfaceType.GetInterfaces().Where(t => t.FullName!.StartsWith("System.Collections.Generic.IEnumerable")).FirstOrDefault(); - if (ienumerableInterface == null) - ienumerableInterface = Globals.TypeOfIEnumerable; + Type? ienumerableInterface = + interfaceType.GetInterfaces().Where(t => t.FullName!.StartsWith("System.Collections.Generic.IEnumerable")).FirstOrDefault() ?? + Globals.TypeOfIEnumerable; getEnumeratorMethod = GetIEnumerableGetEnumeratorMethod(type, ienumerableInterface); } } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs index b2d2ab2..402b990 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs @@ -485,9 +485,7 @@ namespace System.Runtime.Serialization dataContract = s_dataContractCache[id]; if (dataContract == null) { - if (type == null) - type = Type.GetTypeFromHandle(typeHandle)!; - + type ??= Type.GetTypeFromHandle(typeHandle)!; type = UnwrapNullableType(type); dataContract = DataContract.GetDataContractFromGeneratedAssembly(type); @@ -569,8 +567,7 @@ namespace System.Runtime.Serialization dataContract = s_dataContractCache[id]; if (dataContract == null) { - if (type == null) - type = Type.GetTypeFromHandle(typeHandle)!; + type ??= Type.GetTypeFromHandle(typeHandle)!; type = UnwrapNullableType(type); type = GetDataContractAdapterType(type); if (!CollectionDataContract.TryCreateGetOnlyCollectionDataContract(type, out dataContract)) @@ -639,8 +636,7 @@ namespace System.Runtime.Serialization lock (s_initBuiltInContractsLock) { - if (s_typeToBuiltInContract == null) - s_typeToBuiltInContract = new Dictionary(); + s_typeToBuiltInContract ??= new Dictionary(); DataContract? dataContract; if (!s_typeToBuiltInContract.TryGetValue(type, out dataContract)) @@ -657,8 +653,7 @@ namespace System.Runtime.Serialization { lock (s_initBuiltInContractsLock) { - if (s_nameToBuiltInContract == null) - s_nameToBuiltInContract = new Dictionary(); + s_nameToBuiltInContract ??= new Dictionary(); DataContract? dataContract; XmlQualifiedName qname = new XmlQualifiedName(name, ns); @@ -679,8 +674,7 @@ namespace System.Runtime.Serialization lock (s_initBuiltInContractsLock) { - if (s_nameToBuiltInContract == null) - s_nameToBuiltInContract = new Dictionary(); + s_nameToBuiltInContract ??= new Dictionary(); DataContract? dataContract; XmlQualifiedName qname = new XmlQualifiedName(typeName); @@ -959,11 +953,12 @@ namespace System.Runtime.Serialization { lock (s_namespacesLock) { - if (s_namespaces == null) - s_namespaces = new Dictionary(); - string? value; - if (s_namespaces.TryGetValue(key, out value)) + s_namespaces ??= new Dictionary(); + if (s_namespaces.TryGetValue(key, out string? value)) + { return value; + } + try { s_namespaces.Add(key, key); @@ -1049,19 +1044,10 @@ namespace System.Runtime.Serialization internal Type OriginalUnderlyingType { - get - { - if (_originalUnderlyingType == null) - { - _originalUnderlyingType = GetDataContractOriginalType(this._underlyingType); - } - return _originalUnderlyingType; - } - set - { - _originalUnderlyingType = value; - } + get => _originalUnderlyingType ??= GetDataContractOriginalType(this._underlyingType); + set => _originalUnderlyingType = value; } + internal virtual bool IsBuiltInDataContract { get @@ -1569,17 +1555,20 @@ namespace System.Runtime.Serialization private static string GetDefaultDataContractNamespace(Type type) { - string? clrNs = type.Namespace; - if (clrNs == null) - clrNs = string.Empty; - string? ns = GetGlobalDataContractNamespace(clrNs, type.Module.GetCustomAttributes(typeof(ContractNamespaceAttribute)).ToArray()); - if (ns == null) - ns = GetGlobalDataContractNamespace(clrNs, type.Assembly.GetCustomAttributes(typeof(ContractNamespaceAttribute)).ToArray()); + string? clrNs = type.Namespace ?? string.Empty; + string? ns = + GetGlobalDataContractNamespace(clrNs, type.Module.GetCustomAttributes(typeof(ContractNamespaceAttribute)).ToArray()) ?? + GetGlobalDataContractNamespace(clrNs, type.Assembly.GetCustomAttributes(typeof(ContractNamespaceAttribute)).ToArray()); if (ns == null) + { ns = GetDefaultStableNamespace(type); + } else + { CheckExplicitDataContractNamespaceUri(ns, type); + } + return ns; } @@ -1636,8 +1625,7 @@ namespace System.Runtime.Serialization internal static string GetDefaultStableNamespace(string? clrNs) { - if (clrNs == null) clrNs = string.Empty; - return new Uri(Globals.DataContractXsdBaseNamespaceUri, clrNs).AbsoluteUri; + return new Uri(Globals.DataContractXsdBaseNamespaceUri, clrNs ?? string.Empty).AbsoluteUri; } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] @@ -1749,9 +1737,7 @@ namespace System.Runtime.Serialization for (int i = 0; i < nsAttributes.Length; i++) { ContractNamespaceAttribute nsAttribute = (ContractNamespaceAttribute)nsAttributes[i]; - string? clrNsInAttribute = nsAttribute.ClrNamespace; - if (clrNsInAttribute == null) - clrNsInAttribute = string.Empty; + string clrNsInAttribute = nsAttribute.ClrNamespace ?? string.Empty; if (clrNsInAttribute == clrNs) { if (nsAttribute.ContractNamespace == null) @@ -2059,10 +2045,7 @@ namespace System.Runtime.Serialization collectionDataContract.ItemType.GetGenericTypeDefinition() == Globals.TypeOfKeyValue) { DataContract itemDataContract = DataContract.GetDataContract(Globals.TypeOfKeyValuePair.MakeGenericType(collectionDataContract.ItemType.GetGenericArguments())); - if (knownDataContracts == null) - { - knownDataContracts = new DataContractDictionary(); - } + knownDataContracts ??= new DataContractDictionary(); knownDataContracts.TryAdd(itemDataContract.StableName, itemDataContract); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSerializer.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSerializer.cs index 4109703..c42b485 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSerializer.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSerializer.cs @@ -95,10 +95,7 @@ namespace System.Runtime.Serialization public DataContractSerializer(Type type, DataContractSerializerSettings? settings) { - if (settings == null) - { - settings = new DataContractSerializerSettings(); - } + settings ??= new DataContractSerializerSettings(); Initialize(type, settings.RootName, settings.RootNamespace, settings.KnownTypes, settings.MaxItemsInObjectGraph, false, settings.PreserveObjectReferences, settings.DataContractResolver, settings.SerializeReadOnlyTypes); } @@ -357,8 +354,7 @@ namespace System.Runtime.Serialization graph = SurrogateToDataContractType(_serializationSurrogateProvider, graph, declaredType, ref graphType); } - if (dataContractResolver == null) - dataContractResolver = this.DataContractResolver; + dataContractResolver ??= this.DataContractResolver; if (graph == null) { @@ -437,8 +433,7 @@ namespace System.Runtime.Serialization if (MaxItemsInObjectGraph == 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ExceededMaxItemsQuota, MaxItemsInObjectGraph))); - if (dataContractResolver == null) - dataContractResolver = this.DataContractResolver; + dataContractResolver ??= this.DataContractResolver; if (verifyObjectName) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSet.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSet.cs index 51588fc..41bae41 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSet.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSet.cs @@ -54,39 +54,14 @@ namespace System.Runtime.Serialization } } - private Dictionary Contracts - { - get - { - if (_contracts == null) - { - _contracts = new Dictionary(); - } - return _contracts; - } - } + private Dictionary Contracts => + _contracts ??= new Dictionary(); + + private Dictionary ProcessedContracts => + _processedContracts ??= new Dictionary(); - private Dictionary ProcessedContracts - { - get - { - if (_processedContracts == null) - { - _processedContracts = new Dictionary(); - } - return _processedContracts; - } - } #if SUPPORT_SURROGATE - private Hashtable SurrogateDataTable - { - get - { - if (_surrogateDataTable == null) - _surrogateDataTable = new Hashtable(); - return _surrogateDataTable; - } - } + private Hashtable SurrogateDataTable => _surrogateDataTable ??= new Hashtable(); #endif [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataMember.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataMember.cs index 5d2ccfa..251e896 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataMember.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataMember.cs @@ -122,32 +122,10 @@ namespace System.Runtime.Serialization } private FastInvokerBuilder.Getter? _getter; - internal FastInvokerBuilder.Getter Getter - { - get - { - if (_getter == null) - { - _getter = FastInvokerBuilder.CreateGetter(MemberInfo); - } - - return _getter; - } - } + internal FastInvokerBuilder.Getter Getter => _getter ??= FastInvokerBuilder.CreateGetter(MemberInfo); private FastInvokerBuilder.Setter? _setter; - internal FastInvokerBuilder.Setter Setter - { - get - { - if (_setter == null) - { - _setter = FastInvokerBuilder.CreateSetter(MemberInfo); - } - - return _setter; - } - } + internal FastInvokerBuilder.Setter Setter => _setter ??= FastInvokerBuilder.CreateSetter(MemberInfo); private sealed class CriticalHelper { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExportOptions.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExportOptions.cs index c1c60b5..435415d 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExportOptions.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExportOptions.cs @@ -23,16 +23,6 @@ namespace System.Runtime.Serialization } #endif - public Collection KnownTypes - { - get - { - if (_knownTypes == null) - { - _knownTypes = new Collection(); - } - return _knownTypes; - } - } + public Collection KnownTypes => _knownTypes ??= new Collection(); } } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExtensionDataReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExtensionDataReader.cs index 0fe6ffb..df8b296 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExtensionDataReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExtensionDataReader.cs @@ -466,7 +466,9 @@ namespace System.Runtime.Serialization private void GrowElementsIfNeeded() { if (_elements == null) + { _elements = new ElementData[8]; + } else if (_elements.Length == _depth) { ElementData[] newElements = new ElementData[_elements.Length * 2]; @@ -529,9 +531,7 @@ namespace System.Runtime.Serialization public void AddAttribute(string prefix, string ns, string name, string? value) { GrowAttributesIfNeeded(); - AttributeData attribute = attributes[attributeCount]; - if (attribute == null) - attributes[attributeCount] = attribute = new AttributeData(); + AttributeData attribute = attributes[attributeCount] ??= new AttributeData(); attribute.prefix = prefix; attribute.ns = ns; attribute.localName = name; @@ -543,7 +543,9 @@ namespace System.Runtime.Serialization private void GrowAttributesIfNeeded() { if (attributes == null) + { attributes = new AttributeData[4]; + } else if (attributes.Length == attributeCount) { AttributeData[] newAttributes = new AttributeData[attributes.Length * 2]; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/HybridObjectCache.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/HybridObjectCache.cs index 2e5368d..1ce12d3 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/HybridObjectCache.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/HybridObjectCache.cs @@ -19,8 +19,7 @@ namespace System.Runtime.Serialization internal void Add(string id, object? obj) { - if (_objectDictionary == null) - _objectDictionary = new Dictionary(); + _objectDictionary ??= new Dictionary(); if (_objectDictionary.ContainsKey(id)) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.MultipleIdDefinition, id))); @@ -29,21 +28,13 @@ namespace System.Runtime.Serialization internal void Remove(string id) { - if (_objectDictionary != null) - _objectDictionary.Remove(id); + _objectDictionary?.Remove(id); } internal object? GetObject(string id) { - if (_referencedObjectDictionary == null) - { - _referencedObjectDictionary = new Dictionary(); - _referencedObjectDictionary.Add(id, null); - } - else - { - _referencedObjectDictionary.TryAdd(id, null); - } + _referencedObjectDictionary ??= new Dictionary(); + _referencedObjectDictionary.TryAdd(id, null); if (_objectDictionary != null) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/DataContractJsonSerializer.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/DataContractJsonSerializer.cs index 6403867..beeb3fa 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/DataContractJsonSerializer.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/DataContractJsonSerializer.cs @@ -73,10 +73,7 @@ namespace System.Runtime.Serialization.Json [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public DataContractJsonSerializer(Type type, DataContractJsonSerializerSettings? settings) { - if (settings == null) - { - settings = new DataContractJsonSerializerSettings(); - } + settings ??= new DataContractJsonSerializerSettings(); XmlDictionaryString? rootName = (settings.RootName == null) ? null : new XmlDictionary(1).Add(settings.RootName); Initialize(type, rootName, settings.KnownTypes, settings.MaxItemsInObjectGraph, settings.IgnoreExtensionDataObject, diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonDataContract.cs index 472413f..4330703 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonDataContract.cs @@ -283,10 +283,7 @@ namespace System.Runtime.Serialization.Json while (collectionDataContract != null) { DataContract itemContract = collectionDataContract.ItemContract; - if (_knownDataContracts == null) - { - _knownDataContracts = new Dictionary(); - } + _knownDataContracts ??= new Dictionary(); _knownDataContracts.TryAdd(itemContract.StableName, itemContract); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonEncodingStreamWrapper.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonEncodingStreamWrapper.cs index f6a0516..74e85bc 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonEncodingStreamWrapper.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonEncodingStreamWrapper.cs @@ -400,10 +400,7 @@ namespace System.Runtime.Serialization.Json private void EnsureBuffers() { EnsureByteBuffer(); - if (_chars == null) - { - _chars = new char[BufferLength]; - } + _chars ??= new char[BufferLength]; } [MemberNotNull(nameof(_bytes))] diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatGeneratorStatics.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatGeneratorStatics.cs index bc47d9e..0df641f 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatGeneratorStatics.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatGeneratorStatics.cs @@ -318,17 +318,7 @@ namespace System.Runtime.Serialization return s_serializationExceptionCtor; } } - public static Type[] SerInfoCtorArgs - { - get - { - if (s_serInfoCtorArgs == null) - { - s_serInfoCtorArgs = new Type[] { typeof(SerializationInfo), typeof(StreamingContext) }; - } - return s_serInfoCtorArgs; - } - } + public static Type[] SerInfoCtorArgs => s_serInfoCtorArgs ??= new Type[] { typeof(SerializationInfo), typeof(StreamingContext) }; public static MethodInfo ThrowDuplicateMemberExceptionMethod { get diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatWriterGenerator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatWriterGenerator.cs index d8b391b..afe02b0 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatWriterGenerator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatWriterGenerator.cs @@ -274,8 +274,8 @@ namespace System.Runtime.Serialization.Json { WriteStartElement(nameLocal: null, nameIndex: i + _childElementIndex); } - if (memberValue == null) - memberValue = LoadMemberValue(member); + + memberValue ??= LoadMemberValue(member); WriteValue(memberValue); WriteEndElement(); } @@ -390,10 +390,8 @@ namespace System.Runtime.Serialization.Json { if (enumeratorType.IsInterface) { - if (moveNextMethod == null) - moveNextMethod = JsonFormatGeneratorStatics.MoveNextMethod; - if (getCurrentMethod == null) - getCurrentMethod = JsonFormatGeneratorStatics.GetCurrentMethod; + moveNextMethod ??= JsonFormatGeneratorStatics.MoveNextMethod; + getCurrentMethod ??= JsonFormatGeneratorStatics.GetCurrentMethod; } else { @@ -413,10 +411,9 @@ namespace System.Runtime.Serialization.Json } } } - if (moveNextMethod == null) - moveNextMethod = CollectionDataContract.GetTargetMethodWithName(Globals.MoveNextMethodName, enumeratorType, ienumeratorInterface)!; - if (getCurrentMethod == null) - getCurrentMethod = CollectionDataContract.GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface)!; + + moveNextMethod ??= CollectionDataContract.GetTargetMethodWithName(Globals.MoveNextMethodName, enumeratorType, ienumeratorInterface)!; + getCurrentMethod ??= CollectionDataContract.GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface)!; } } Type elementType = getCurrentMethod.ReturnType; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonReaderDelegator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonReaderDelegator.cs index e36a4fe..b9a545d 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonReaderDelegator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonReaderDelegator.cs @@ -24,32 +24,10 @@ namespace System.Runtime.Serialization.Json _dateTimeFormat = dateTimeFormat; } - internal XmlDictionaryReaderQuotas? ReaderQuotas - { - get - { - if (this.dictionaryReader == null) - { - return null; - } - else - { - return dictionaryReader.Quotas; - } - } - } + internal XmlDictionaryReaderQuotas? ReaderQuotas => dictionaryReader?.Quotas; - private DateTimeArrayJsonHelperWithString DateTimeArrayHelper - { - get - { - if (_dateTimeArrayHelper == null) - { - _dateTimeArrayHelper = new DateTimeArrayJsonHelperWithString(_dateTimeFormat); - } - return _dateTimeArrayHelper; - } - } + private DateTimeArrayJsonHelperWithString DateTimeArrayHelper => + _dateTimeArrayHelper ??= new DateTimeArrayJsonHelperWithString(_dateTimeFormat); internal static XmlQualifiedName ParseQualifiedName(string qname) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ReflectionJsonFormatWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ReflectionJsonFormatWriter.cs index a65a474..74fbefe 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ReflectionJsonFormatWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ReflectionJsonFormatWriter.cs @@ -239,10 +239,7 @@ namespace System.Runtime.Serialization.Json if (shouldWriteValue) { - if (memberValue == null) - { - memberValue = ReflectionGetMemberValue(obj, member); - } + memberValue ??= ReflectionGetMemberValue(obj, member); bool requiresNameAttribute = DataContractJsonSerializer.CheckIfXmlNameRequiresMapping(classContract.MemberNames![i]); PrimitiveDataContract? primitiveContract = member.MemberPrimitiveContract; if (requiresNameAttribute || !ReflectionTryWritePrimitive(xmlWriter, context, memberType, memberValue, memberNames[i + childElementIndex] /*name*/, null/*ns*/, primitiveContract)) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonReader.cs index b7edc56..fc508ff 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonReader.cs @@ -1613,10 +1613,7 @@ namespace System.Runtime.Serialization.Json if (val[i] == '\\') { i++; - if (sb == null) - { - sb = new StringBuilder(); - } + sb ??= new StringBuilder(); sb.Append(val, startIndex, count); Fx.Assert(i < val.Length, "Found that an '\' was the last character in a string. ReadServerTypeAttriute validates that the escape sequence is valid when it calls ReadQuotedText and ReadEscapedCharacter"); if (i >= val.Length) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonWriter.cs index 2852f76..7b54448 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonWriter.cs @@ -166,17 +166,8 @@ namespace System.Runtime.Serialization.Json get { return XmlSpace.None; } } - private static BinHexEncoding BinHexEncoding - { - get - { - if (s_binHexEncoding == null) - { - s_binHexEncoding = new BinHexEncoding(); - } - return s_binHexEncoding; - } - } + private static BinHexEncoding BinHexEncoding => + s_binHexEncoding ??= new BinHexEncoding(); private bool HasOpenAttribute => (_isWritingDataTypeAttribute || _isWritingServerTypeAttribute || IsWritingNameAttribute || _isWritingXmlnsAttribute); @@ -260,10 +251,8 @@ namespace System.Runtime.Serialization.Json { encoding = null!; } - if (_nodeWriter == null) - { - _nodeWriter = new JsonNodeWriter(); - } + + _nodeWriter ??= new JsonNodeWriter(); _nodeWriter.SetOutput(stream, ownsStream, encoding); InitializeWriter(); @@ -712,12 +701,8 @@ namespace System.Runtime.Serialization.Json { throw new ArgumentException(SR.JsonInvalidLocalNameEmpty, nameof(localName)); } - if (ns == null) - { - ns = string.Empty; - } - base.WriteQualifiedName(localName, ns); + base.WriteQualifiedName(localName, ns ?? string.Empty); } public override void WriteRaw(string data) @@ -989,10 +974,7 @@ namespace System.Runtime.Serialization.Json } else { - if (text == null) - { - text = string.Empty; - } + text ??= string.Empty; // do work only when not indenting whitespace if (!((_dataType == JsonDataType.Array || _dataType == JsonDataType.Object || _nodeType == JsonNodeType.EndElement) && XmlConverter.IsWhitespace(text))) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlObjectSerializerReadContextComplexJson.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlObjectSerializerReadContextComplexJson.cs index fe7ad57..9c61887 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlObjectSerializerReadContextComplexJson.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlObjectSerializerReadContextComplexJson.cs @@ -140,8 +140,7 @@ namespace System.Runtime.Serialization.Json internal override void ReadAttributes(XmlReaderDelegator xmlReader) { - if (attributes == null) - attributes = new Attributes(); + attributes ??= new Attributes(); attributes.Reset(); if (xmlReader.MoveToAttribute(JsonGlobals.typeString) && xmlReader.Value == JsonGlobals.nullString) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ObjectReferenceStack.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ObjectReferenceStack.cs index 7945a64..c6993ad 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ObjectReferenceStack.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ObjectReferenceStack.cs @@ -33,8 +33,7 @@ namespace System.Runtime.Serialization } else { - if (_objectDictionary == null) - _objectDictionary = new Dictionary(); + _objectDictionary ??= new Dictionary(); _objectDictionary.Add(obj, null); _count++; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/PrimitiveDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/PrimitiveDataContract.cs index b5bfbbb..8cd388f 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/PrimitiveDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/PrimitiveDataContract.cs @@ -86,17 +86,8 @@ namespace System.Runtime.Serialization } } - internal MethodInfo XmlFormatReaderMethod - { - get - { - if (_helper.XmlFormatReaderMethod == null) - { - _helper.XmlFormatReaderMethod = typeof(XmlReaderDelegator).GetMethod(ReadMethodName, Globals.ScanAllMembers)!; - } - return _helper.XmlFormatReaderMethod; - } - } + internal MethodInfo XmlFormatReaderMethod => + _helper.XmlFormatReaderMethod ??= typeof(XmlReaderDelegator).GetMethod(ReadMethodName, Globals.ScanAllMembers)!; [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext? context) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionReader.cs index dcffdbc..b28f417 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionReader.cs @@ -26,17 +26,8 @@ namespace System.Runtime.Serialization private static readonly Type[] s_arrayConstructorParameters = new Type[] { Globals.TypeOfInt }; private static readonly object[] s_arrayConstructorArguments = new object[] { 32 }; - private static MethodInfo CollectionSetItemDelegateMethod - { - get - { - if (s_getCollectionSetItemDelegateMethod == null) - { - s_getCollectionSetItemDelegateMethod = typeof(ReflectionReader).GetMethod(nameof(GetCollectionSetItemDelegate), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)!; - } - return s_getCollectionSetItemDelegateMethod!; - } - } + private static MethodInfo CollectionSetItemDelegateMethod => + s_getCollectionSetItemDelegateMethod ??= typeof(ReflectionReader).GetMethod(nameof(GetCollectionSetItemDelegate), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)!; [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public object ReflectionReadClass(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext? context, XmlDictionaryString[]? memberNames, XmlDictionaryString[]? memberNamespaces, ClassDataContract classContract) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionXmlFormatWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionXmlFormatWriter.cs index 6350fc0..dc70a9c 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionXmlFormatWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionXmlFormatWriter.cs @@ -173,10 +173,7 @@ namespace System.Runtime.Serialization if (shouldWriteValue) { bool writeXsiType = CheckIfMemberHasConflict(member, classContract, derivedMostClassContract); - if (memberValue == null) - { - memberValue = ReflectionGetMemberValue(obj, member); - } + memberValue ??= ReflectionGetMemberValue(obj, member); PrimitiveDataContract? primitiveContract = member.MemberPrimitiveContract; if (writeXsiType || !ReflectionTryWritePrimitive(xmlWriter, context, memberType, memberValue, memberNames[i + childElementIndex] /*name*/, ns, primitiveContract)) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaExporter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaExporter.cs index 8b6a976..1c76e57 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaExporter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaExporter.cs @@ -33,15 +33,7 @@ namespace System.Runtime.Serialization get { return _schemas; } } - private XmlDocument XmlDoc - { - get - { - if (_xmlDoc == null) - _xmlDoc = new XmlDocument(); - return _xmlDoc; - } - } + private XmlDocument XmlDoc => _xmlDoc ??= new XmlDocument(); [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal void Export() @@ -654,9 +646,7 @@ namespace System.Runtime.Serialization { if ((object)schemaItem == (object)providerXsdType) { - typeNs = schema.TargetNamespace; - if (typeNs == null) - typeNs = string.Empty; + typeNs = schema.TargetNamespace ?? string.Empty; break; } } @@ -857,103 +847,31 @@ namespace System.Runtime.Serialization } private static XmlQualifiedName? s_anytypeQualifiedName; - internal static XmlQualifiedName AnytypeQualifiedName - { - get - { - if (s_anytypeQualifiedName == null) - s_anytypeQualifiedName = new XmlQualifiedName(Globals.AnyTypeLocalName, Globals.SchemaNamespace); - return s_anytypeQualifiedName; - } - } + internal static XmlQualifiedName AnytypeQualifiedName => s_anytypeQualifiedName ??= new XmlQualifiedName(Globals.AnyTypeLocalName, Globals.SchemaNamespace); private static XmlQualifiedName? s_stringQualifiedName; - internal static XmlQualifiedName StringQualifiedName - { - get - { - if (s_stringQualifiedName == null) - s_stringQualifiedName = new XmlQualifiedName(Globals.StringLocalName, Globals.SchemaNamespace); - return s_stringQualifiedName; - } - } + internal static XmlQualifiedName StringQualifiedName => s_stringQualifiedName ??= new XmlQualifiedName(Globals.StringLocalName, Globals.SchemaNamespace); private static XmlQualifiedName? s_defaultEnumBaseTypeName; - internal static XmlQualifiedName DefaultEnumBaseTypeName - { - get - { - if (s_defaultEnumBaseTypeName == null) - s_defaultEnumBaseTypeName = new XmlQualifiedName(Globals.IntLocalName, Globals.SchemaNamespace); - return s_defaultEnumBaseTypeName; - } - } + internal static XmlQualifiedName DefaultEnumBaseTypeName => s_defaultEnumBaseTypeName ??= new XmlQualifiedName(Globals.IntLocalName, Globals.SchemaNamespace); private static XmlQualifiedName? s_enumerationValueAnnotationName; - internal static XmlQualifiedName EnumerationValueAnnotationName - { - get - { - if (s_enumerationValueAnnotationName == null) - s_enumerationValueAnnotationName = new XmlQualifiedName(Globals.EnumerationValueLocalName, Globals.SerializationNamespace); - return s_enumerationValueAnnotationName; - } - } + internal static XmlQualifiedName EnumerationValueAnnotationName => s_enumerationValueAnnotationName ??= new XmlQualifiedName(Globals.EnumerationValueLocalName, Globals.SerializationNamespace); private static XmlQualifiedName? s_surrogateDataAnnotationName; - internal static XmlQualifiedName SurrogateDataAnnotationName - { - get - { - if (s_surrogateDataAnnotationName == null) - s_surrogateDataAnnotationName = new XmlQualifiedName(Globals.SurrogateDataLocalName, Globals.SerializationNamespace); - return s_surrogateDataAnnotationName; - } - } + internal static XmlQualifiedName SurrogateDataAnnotationName => s_surrogateDataAnnotationName ??= new XmlQualifiedName(Globals.SurrogateDataLocalName, Globals.SerializationNamespace); private static XmlQualifiedName? s_defaultValueAnnotation; - internal static XmlQualifiedName DefaultValueAnnotation - { - get - { - if (s_defaultValueAnnotation == null) - s_defaultValueAnnotation = new XmlQualifiedName(Globals.DefaultValueLocalName, Globals.SerializationNamespace); - return s_defaultValueAnnotation; - } - } + internal static XmlQualifiedName DefaultValueAnnotation => s_defaultValueAnnotation ??= new XmlQualifiedName(Globals.DefaultValueLocalName, Globals.SerializationNamespace); private static XmlQualifiedName? s_actualTypeAnnotationName; - internal static XmlQualifiedName ActualTypeAnnotationName - { - get - { - if (s_actualTypeAnnotationName == null) - s_actualTypeAnnotationName = new XmlQualifiedName(Globals.ActualTypeLocalName, Globals.SerializationNamespace); - return s_actualTypeAnnotationName; - } - } + internal static XmlQualifiedName ActualTypeAnnotationName => s_actualTypeAnnotationName ??= new XmlQualifiedName(Globals.ActualTypeLocalName, Globals.SerializationNamespace); private static XmlQualifiedName? s_isDictionaryAnnotationName; - internal static XmlQualifiedName IsDictionaryAnnotationName - { - get - { - if (s_isDictionaryAnnotationName == null) - s_isDictionaryAnnotationName = new XmlQualifiedName(Globals.IsDictionaryLocalName, Globals.SerializationNamespace); - return s_isDictionaryAnnotationName; - } - } + internal static XmlQualifiedName IsDictionaryAnnotationName => s_isDictionaryAnnotationName ??= new XmlQualifiedName(Globals.IsDictionaryLocalName, Globals.SerializationNamespace); private static XmlQualifiedName? s_isValueTypeName; - internal static XmlQualifiedName IsValueTypeName - { - get - { - if (s_isValueTypeName == null) - s_isValueTypeName = new XmlQualifiedName(Globals.IsValueTypeLocalName, Globals.SerializationNamespace); - return s_isValueTypeName; - } - } + internal static XmlQualifiedName IsValueTypeName => s_isValueTypeName ??= new XmlQualifiedName(Globals.IsValueTypeLocalName, Globals.SerializationNamespace); // Property is not stored in a local because XmlSchemaAttribute is mutable. // The schema export process should not expose objects that may be modified later. diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaHelper.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaHelper.cs index 8a07b0e..da820ba 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaHelper.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaHelper.cs @@ -68,7 +68,7 @@ namespace System.Runtime.Serialization internal static XmlSchema GetSchema(string ns, XmlSchemaSet schemas) { - if (ns == null) { ns = string.Empty; } + ns ??= string.Empty; ICollection currentSchemas = schemas.Schemas(); foreach (XmlSchema schema in currentSchemas) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ScopedKnownTypes.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ScopedKnownTypes.cs index 47fed53..727fc4e 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ScopedKnownTypes.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ScopedKnownTypes.cs @@ -14,9 +14,14 @@ namespace System.Runtime.Serialization internal void Push(DataContractDictionary dataContractDictionary) { if (dataContractDictionaries == null) + { dataContractDictionaries = new DataContractDictionary[4]; + } else if (_count == dataContractDictionaries.Length) + { Array.Resize(ref dataContractDictionaries, dataContractDictionaries.Length * 2); + } + dataContractDictionaries[_count++] = dataContractDictionary; } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SurrogateDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SurrogateDataContract.cs index dce6f2a..02b82aa 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SurrogateDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SurrogateDataContract.cs @@ -72,9 +72,7 @@ namespace System.Runtime.Serialization context.AddNewObject(obj); string objectId = context.GetObjectId(); SerializationInfo serInfo = context.ReadSerializationInfo(xmlReader, objType); - object? newObj = SerializationSurrogateSetObjectData(obj, serInfo, context.GetStreamingContext()); - if (newObj == null) - newObj = obj; + object? newObj = SerializationSurrogateSetObjectData(obj, serInfo, context.GetStreamingContext()) ?? obj; if (newObj is IDeserializationCallback) ((IDeserializationCallback)newObj).OnDeserialization(null); if (newObj is IObjectReference) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatGeneratorStatics.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatGeneratorStatics.cs index a6371c4..6791ee9 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatGeneratorStatics.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatGeneratorStatics.cs @@ -840,14 +840,7 @@ namespace System.Runtime.Serialization internal static MethodInfo WriteExtensionDataMethod { [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - get - { - if (s_writeExtensionDataMethod == null) - { - s_writeExtensionDataMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("WriteExtensionData", Globals.ScanAllMembers)!; - } - return s_writeExtensionDataMethod; - } + get => s_writeExtensionDataMethod ??= typeof(XmlObjectSerializerWriteContext).GetMethod("WriteExtensionData", Globals.ScanAllMembers)!; } private static MethodInfo? s_writeXmlValueMethod; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatWriterGenerator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatWriterGenerator.cs index 165e0ab..b510882 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatWriterGenerator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatWriterGenerator.cs @@ -302,8 +302,8 @@ namespace System.Runtime.Serialization _ilg.LoadArrayElement(_childElementNamespacesLocal!, i + _childElementIndex); _ilg.Call(methodInfo: XmlFormatGeneratorStatics.WriteNamespaceDeclMethod); } - if (memberValue == null) - memberValue = LoadMemberValue(member); + + memberValue ??= LoadMemberValue(member); WriteValue(memberValue, writeXsiType); WriteEndElement(); } @@ -431,10 +431,8 @@ namespace System.Runtime.Serialization { if (enumeratorType.IsInterface) { - if (moveNextMethod == null) - moveNextMethod = XmlFormatGeneratorStatics.MoveNextMethod; - if (getCurrentMethod == null) - getCurrentMethod = XmlFormatGeneratorStatics.GetCurrentMethod; + moveNextMethod ??= XmlFormatGeneratorStatics.MoveNextMethod; + getCurrentMethod ??= XmlFormatGeneratorStatics.GetCurrentMethod; } else { @@ -454,10 +452,9 @@ namespace System.Runtime.Serialization } } } - if (moveNextMethod == null) - moveNextMethod = CollectionDataContract.GetTargetMethodWithName(Globals.MoveNextMethodName, enumeratorType, ienumeratorInterface)!; - if (getCurrentMethod == null) - getCurrentMethod = CollectionDataContract.GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface)!; + + moveNextMethod ??= CollectionDataContract.GetTargetMethodWithName(Globals.MoveNextMethodName, enumeratorType, ienumeratorInterface)!; + getCurrentMethod ??= CollectionDataContract.GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface)!; } } Type elementType = getCurrentMethod.ReturnType; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializer.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializer.cs index a5f70d7..8ba00fd 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializer.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializer.cs @@ -435,17 +435,6 @@ namespace System.Runtime.Serialization } private static IFormatterConverter? s_formatterConverter; - internal static IFormatterConverter FormatterConverter - { - get - { - if (s_formatterConverter == null) - { - s_formatterConverter = new FormatterConverter(); - } - - return s_formatterConverter; - } - } + internal static IFormatterConverter FormatterConverter => s_formatterConverter ??= new FormatterConverter(); } } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerContext.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerContext.cs index fd87805..66ce7c6 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerContext.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerContext.cs @@ -95,17 +95,8 @@ namespace System.Runtime.Serialization get { return _dataContractResolver; } } - protected KnownTypeDataContractResolver KnownTypeResolver - { - get - { - if (_knownTypeResolver == null) - { - _knownTypeResolver = new KnownTypeDataContractResolver(this); - } - return _knownTypeResolver; - } - } + protected KnownTypeDataContractResolver KnownTypeResolver => + _knownTypeResolver ??= new KnownTypeDataContractResolver(this); [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal DataContract GetDataContract(Type type) @@ -240,19 +231,10 @@ namespace System.Runtime.Serialization } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - private DataContract? ResolveDataContractFromKnownTypes(XmlQualifiedName typeName) - { - DataContract? dataContract = PrimitiveDataContract.GetPrimitiveDataContract(typeName.Name, typeName.Namespace); - if (dataContract == null) - { - dataContract = scopedKnownTypes.GetDataContract(typeName); - if (dataContract == null) - { - dataContract = GetDataContractFromSerializerKnownTypes(typeName); - } - } - return dataContract; - } + private DataContract? ResolveDataContractFromKnownTypes(XmlQualifiedName typeName) => + PrimitiveDataContract.GetPrimitiveDataContract(typeName.Name, typeName.Namespace) ?? + scopedKnownTypes.GetDataContract(typeName) ?? + GetDataContractFromSerializerKnownTypes(typeName); [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] protected DataContract? ResolveDataContractFromKnownTypes(string typeName, string? typeNs, DataContract? memberTypeContract, Type? declaredType) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContext.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContext.cs index dc9f5c0..09fb6e2 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContext.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContext.cs @@ -24,19 +24,10 @@ namespace System.Runtime.Serialization private object? _getOnlyCollectionValue; private bool _isGetOnlyCollection; - private HybridObjectCache DeserializedObjects - { - get - { - if (_deserializedObjects == null) - _deserializedObjects = new HybridObjectCache(); - return _deserializedObjects; - } - } + private HybridObjectCache DeserializedObjects => _deserializedObjects ??= new HybridObjectCache(); private XmlDocument Document => _xmlDocument ??= new XmlDocument(); - internal override bool IsGetOnlyCollection { get { return _isGetOnlyCollection; } @@ -107,8 +98,7 @@ namespace System.Runtime.Serialization [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal virtual object? InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract? dataContract, string? name, string? ns) { - if (dataContract == null) - dataContract = GetDataContract(declaredType); + dataContract ??= GetDataContract(declaredType); return InternalDeserialize(xmlReader, name, ns, declaredType, ref dataContract); } @@ -276,8 +266,7 @@ namespace System.Runtime.Serialization [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal void HandleUnknownElement(XmlReaderDelegator xmlReader, ExtensionDataObject extensionData, int memberIndex) { - if (extensionData.Members == null) - extensionData.Members = new List(); + extensionData.Members ??= new List(); extensionData.Members.Add(ReadExtensionDataMember(xmlReader, memberIndex)); } @@ -310,15 +299,13 @@ namespace System.Runtime.Serialization [MemberNotNull(nameof(attributes))] internal virtual void ReadAttributes(XmlReaderDelegator xmlReader) { - if (attributes == null) - attributes = new Attributes(); + attributes ??= new Attributes(); attributes.Read(xmlReader); } internal void ResetAttributes() { - if (attributes != null) - attributes.Reset(); + attributes?.Reset(); } internal string GetObjectId() @@ -468,8 +455,7 @@ namespace System.Runtime.Serialization [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal object? ReadIXmlSerializable(XmlReaderDelegator xmlReader, XmlDataContract xmlDataContract, bool isMemberType) { - if (_xmlSerializableReader == null) - _xmlSerializableReader = new XmlSerializableReader(); + _xmlSerializableReader ??= new XmlSerializableReader(); return ReadIXmlSerializable(_xmlSerializableReader, xmlReader, xmlDataContract, isMemberType); } @@ -759,8 +745,7 @@ namespace System.Runtime.Serialization if (nodeType != XmlNodeType.Element) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader)); - if (dataNode.Members == null) - dataNode.Members = new List(); + dataNode.Members ??= new List(); dataNode.Members.Add(ReadExtensionDataMember(xmlReader, memberIndex++)); } xmlReader.ReadEndElement(); @@ -789,8 +774,7 @@ namespace System.Runtime.Serialization } if (xmlReader.IsStartElement(dataNode.ItemName, dataNode.ItemNamespace!)) { - if (dataNode.Items == null) - dataNode.Items = new List(); + dataNode.Items ??= new List(); dataNode.Items.Add(ReadExtensionDataValue(xmlReader)); } else @@ -849,8 +833,7 @@ namespace System.Runtime.Serialization var member = new ISerializableDataMember(xmlReader.LocalName); member.Value = ReadExtensionDataValue(xmlReader); - if (dataNode.Members == null) - dataNode.Members = new List(); + dataNode.Members ??= new List(); dataNode.Members.Add(member); } xmlReader.ReadEndElement(); @@ -877,8 +860,7 @@ namespace System.Runtime.Serialization string ns = xmlReader.NamespaceURI; if (ns != Globals.SerializationNamespace && ns != Globals.SchemaInstanceNamespace) { - if (xmlAttributes == null) - xmlAttributes = new List(); + xmlAttributes ??= new List(); xmlAttributes.Add((XmlAttribute)Document.ReadNode(xmlReader.UnderlyingReader)!); } } @@ -890,8 +872,7 @@ namespace System.Runtime.Serialization if (xmlReader.EOF) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.UnexpectedEndOfFile)); - if (xmlChildNodes == null) - xmlChildNodes = new List(); + xmlChildNodes ??= new List(); xmlChildNodes.Add(Document.ReadNode(xmlReader.UnderlyingReader)!); } xmlReader.ReadEndElement(); @@ -941,8 +922,10 @@ namespace System.Runtime.Serialization elementNs = ns; } else + { couldBeCollectionData = (string.CompareOrdinal(elementName, name) == 0) && (string.CompareOrdinal(elementNs, ns) == 0); + } } } else if (xmlReader.EOF) @@ -950,7 +933,7 @@ namespace System.Runtime.Serialization else if (IsContentNode(xmlReader.NodeType)) couldBeClassData = couldBeISerializableData = couldBeCollectionData = false; - if (_attributesInXmlData == null) _attributesInXmlData = new Attributes(); + _attributesInXmlData ??= new Attributes(); _attributesInXmlData.Read(xmlReader); XmlNode childNode = Document.ReadNode(xmlReader.UnderlyingReader)!; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerWriteContext.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerWriteContext.cs index 4e7ebc9..00abd38 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerWriteContext.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerWriteContext.cs @@ -51,15 +51,7 @@ namespace System.Runtime.Serialization _unsafeTypeForwardingEnabled = true; } - protected ObjectToIdCache SerializedObjects - { - get - { - if (_serializedObjects == null) - _serializedObjects = new ObjectToIdCache(); - return _serializedObjects; - } - } + protected ObjectToIdCache SerializedObjects => _serializedObjects ??= new ObjectToIdCache(); internal override bool IsGetOnlyCollection { @@ -177,10 +169,7 @@ namespace System.Runtime.Serialization dataContract = GetDataContract(declaredTypeHandle, declaredType); if (!WriteClrTypeInfo(xmlWriter, dataContract) && DataContractResolver != null) { - if (objectType == null) - { - objectType = Type.GetTypeFromHandle(objectTypeHandle)!; - } + objectType ??= Type.GetTypeFromHandle(objectTypeHandle)!; WriteResolvedTypeInfo(xmlWriter, objectType, declaredType); } } @@ -466,8 +455,7 @@ namespace System.Runtime.Serialization internal void WriteIXmlSerializable(XmlWriterDelegator xmlWriter, object obj) { - if (_xmlSerializableWriter == null) - _xmlSerializableWriter = new XmlSerializableWriter(); + _xmlSerializableWriter ??= new XmlSerializableWriter(); WriteIXmlSerializable(xmlWriter, obj, _xmlSerializableWriter); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/EncodingStreamWrapper.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/EncodingStreamWrapper.cs index 29036c7..0d9437d 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/EncodingStreamWrapper.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/EncodingStreamWrapper.cs @@ -291,8 +291,7 @@ namespace System.Xml private void EnsureBuffers() { EnsureByteBuffer(); - if (_chars == null) - _chars = new char[BufferLength]; + _chars ??= new char[BufferLength]; } [MemberNotNull(nameof(_bytes))] diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/UniqueId.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/UniqueId.cs index d09c801..4bc3d07 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/UniqueId.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/UniqueId.cs @@ -313,7 +313,6 @@ namespace System.Xml if (id1 is null || id2 is null) return false; -#pragma warning suppress 56506 // Microsoft, checks for whether id1 and id2 are null done above. if (id1.IsGuid && id2.IsGuid) { return id1._idLow == id2._idLow && id1._idHigh == id2._idHigh; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseReader.cs index 0790825..38e29e8 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseReader.cs @@ -77,25 +77,9 @@ namespace System.Xml } - private static Base64Encoding Base64Encoding - { - get - { - if (s_base64Encoding == null) - s_base64Encoding = new Base64Encoding(); - return s_base64Encoding; - } - } + private static Base64Encoding Base64Encoding => s_base64Encoding ??= new Base64Encoding(); - private static BinHexEncoding BinHexEncoding - { - get - { - if (s_binHexEncoding == null) - s_binHexEncoding = new BinHexEncoding(); - return s_binHexEncoding; - } - } + private static BinHexEncoding BinHexEncoding => s_binHexEncoding ??= new BinHexEncoding(); protected XmlBufferReader BufferReader { @@ -173,10 +157,7 @@ namespace System.Xml } } - if (_declarationNode == null) - { - _declarationNode = new XmlDeclarationNode(_bufferReader); - } + _declarationNode ??= new XmlDeclarationNode(_bufferReader); MoveToNode(_declarationNode); return _declarationNode; } @@ -212,20 +193,14 @@ namespace System.Xml } protected XmlCommentNode MoveToComment() { - if (_commentNode == null) - { - _commentNode = new XmlCommentNode(_bufferReader); - } + _commentNode ??= new XmlCommentNode(_bufferReader); MoveToNode(_commentNode); return _commentNode; } protected XmlCDataNode MoveToCData() { - if (_cdataNode == null) - { - _cdataNode = new XmlCDataNode(_bufferReader); - } + _cdataNode ??= new XmlCDataNode(_bufferReader); MoveToNode(_cdataNode); return _cdataNode; } @@ -239,20 +214,14 @@ namespace System.Xml protected XmlComplexTextNode MoveToComplexText() { - if (_complexTextNode == null) - { - _complexTextNode = new XmlComplexTextNode(_bufferReader); - } + _complexTextNode ??= new XmlComplexTextNode(_bufferReader); MoveToNode(_complexTextNode); return _complexTextNode; } protected XmlTextNode MoveToWhitespaceText() { - if (_whitespaceTextNode == null) - { - _whitespaceTextNode = new XmlWhitespaceTextNode(_bufferReader); - } + _whitespaceTextNode ??= new XmlWhitespaceTextNode(_bufferReader); if (_nsMgr.XmlSpace == XmlSpace.Preserve) _whitespaceTextNode.NodeType = XmlNodeType.SignificantWhitespace; else @@ -593,10 +562,10 @@ namespace System.Xml { ArgumentNullException.ThrowIfNull(localName); - if (namespaceUri == null) - namespaceUri = string.Empty; + namespaceUri ??= string.Empty; if (!_node.CanGetAttribute) return null; + XmlAttributeNode[]? attributeNodes = _attributeNodes; int attributeCount = _attributeCount; int attributeIndex = _attributeStart; @@ -620,10 +589,10 @@ namespace System.Xml { ArgumentNullException.ThrowIfNull(localName); - if (namespaceUri == null) - namespaceUri = XmlDictionaryString.Empty; + namespaceUri ??= XmlDictionaryString.Empty; if (!_node.CanGetAttribute) return null; + XmlAttributeNode[]? attributeNodes = _attributeNodes; int attributeCount = _attributeCount; int attributeIndex = _attributeStart; @@ -801,8 +770,7 @@ namespace System.Xml private void CheckAttributes(XmlAttributeNode[] attributeNodes, int attributeCount) { // For large numbers of attributes, sorting the attributes (n * lg(n)) is faster - if (_attributeSorter == null) - _attributeSorter = new AttributeSorter(); + _attributeSorter ??= new AttributeSorter(); if (!_attributeSorter.Sort(attributeNodes, attributeCount)) { @@ -1483,8 +1451,7 @@ namespace System.Xml _trailCharCount = (charCount % charBlock); if (_trailCharCount > 0) { - if (_trailChars == null) - _trailChars = new char[4]; + _trailChars ??= new char[4]; charCount -= _trailCharCount; Array.Copy(chars, charCount, _trailChars, 0, _trailCharCount); } @@ -1493,8 +1460,7 @@ namespace System.Xml { if (byteCount < byteBlock) { - if (_trailBytes == null) - _trailBytes = new byte[3]; + _trailBytes ??= new byte[3]; _trailByteCount = encoding.GetBytes(chars, 0, charCount, _trailBytes, 0); int actual = Math.Min(_trailByteCount, byteCount); Buffer.BlockCopy(_trailBytes, 0, buffer, offset, actual); @@ -1752,18 +1718,7 @@ namespace System.Xml } } - public override string Value - { - get - { - if (_value == null) - { - _value = _node.ValueAsString; - } - - return _value; - } - } + public override string Value => _value ??= _node.ValueAsString; public override Type ValueType { @@ -2029,8 +1984,7 @@ namespace System.Xml if (_signing) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlCanonicalizationStarted)); - if (_signingWriter == null) - _signingWriter = CreateSigningNodeWriter(); + _signingWriter ??= CreateSigningNodeWriter(); _signingWriter.SetOutput(XmlNodeWriter.Null, stream, includeComments, inclusivePrefixes); _nsMgr.Sign(_signingWriter); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseWriter.cs index d37fb67..f009bcc 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseWriter.cs @@ -115,15 +115,7 @@ namespace System.Xml throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlWriterClosed)); } - private static BinHexEncoding BinHexEncoding - { - get - { - if (_binhexEncoding == null) - _binhexEncoding = new BinHexEncoding(); - return _binhexEncoding; - } - } + private static BinHexEncoding BinHexEncoding => _binhexEncoding ??= new BinHexEncoding(); public override string? XmlLang { @@ -476,8 +468,7 @@ namespace System.Xml if (_writeState == WriteState.Attribute) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlInvalidWriteState, "WriteCData", WriteState.ToString()))); - if (text == null) - text = string.Empty; + text ??= string.Empty; if (text.Length > 0) { @@ -511,8 +502,7 @@ namespace System.Xml Element element = EnterScope(); if (ns == null) { - if (prefix == null) - prefix = string.Empty; + prefix ??= string.Empty; ns = _nsMgr.LookupNamespace(prefix); @@ -562,8 +552,7 @@ namespace System.Xml Element element = EnterScope(); if (ns == null) { - if (prefix == null) - prefix = string.Empty; + prefix ??= string.Empty; ns = _nsMgr.LookupNamespace(prefix); @@ -843,8 +832,7 @@ namespace System.Xml if (IsClosed) ThrowClosed(); ArgumentException.ThrowIfNullOrEmpty(localName); - if (namespaceUri == null) - namespaceUri = string.Empty; + namespaceUri ??= string.Empty; string prefix = GetQualifiedNamePrefix(namespaceUri, null); if (prefix.Length != 0) { @@ -861,8 +849,7 @@ namespace System.Xml ArgumentNullException.ThrowIfNull(localName); if (localName.Value.Length == 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.InvalidLocalNameEmpty, nameof(localName))); - if (namespaceUri == null) - namespaceUri = XmlDictionaryString.Empty; + namespaceUri ??= XmlDictionaryString.Empty; string prefix = GetQualifiedNamePrefix(namespaceUri.Value, namespaceUri); FlushBase64(); @@ -980,8 +967,7 @@ namespace System.Xml if (IsClosed) ThrowClosed(); - if (value == null) - value = string.Empty; + value ??= string.Empty; if (value.Length > 0 || _inList) { @@ -1059,8 +1045,7 @@ namespace System.Xml if (IsClosed) ThrowClosed(); - if (value == null) - value = string.Empty; + value ??= string.Empty; if (value.Length > 0) { @@ -1482,10 +1467,7 @@ namespace System.Xml int totalByteCount = _trailByteCount + count; int actualByteCount = totalByteCount - (totalByteCount % 3); - if (_trailBytes == null) - { - _trailBytes = new byte[3]; - } + _trailBytes ??= new byte[3]; if (actualByteCount >= 3) { @@ -1551,10 +1533,7 @@ namespace System.Xml int totalByteCount = _trailByteCount + count; int actualByteCount = totalByteCount - (totalByteCount % 3); - if (_trailBytes == null) - { - _trailBytes = new byte[3]; - } + _trailBytes ??= new byte[3]; if (actualByteCount >= 3) { @@ -1609,8 +1588,7 @@ namespace System.Xml if (Signing) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlCanonicalizationStarted)); FlushElement(); - if (_signingWriter == null) - _signingWriter = CreateSigningNodeWriter(); + _signingWriter ??= CreateSigningNodeWriter(); _signingWriter.SetOutput(_writer, stream, includeComments, inclusivePrefixes); _writer = _signingWriter; SignScope(_signingWriter.CanonicalWriter); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReaderSession.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReaderSession.cs index 5f8a487..2ecc252 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReaderSession.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReaderSession.cs @@ -32,8 +32,7 @@ namespace System.Xml xmlString = new XmlDictionaryString(this, value, id); if (id >= MaxArrayEntries) { - if (_stringDict == null) - _stringDict = new Dictionary(); + _stringDict ??= new Dictionary(); _stringDict.Add(id, xmlString); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriter.cs index 7ed8b8e..ef401fd 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriter.cs @@ -1030,8 +1030,7 @@ namespace System.Xml } else { - if (_captureStream == null) - _captureStream = new MemoryStream(); + _captureStream ??= new MemoryStream(); if (trailByteCount > 0) _captureStream.Write(trailBytes!, 0, trailByteCount); @@ -1079,8 +1078,7 @@ namespace System.Xml { ArgumentNullException.ThrowIfNull(stream); - if (_writer == null) - _writer = new XmlBinaryNodeWriter(); + _writer ??= new XmlBinaryNodeWriter(); _writer.SetOutput(stream, dictionary, session, ownsStream); SetOutput(_writer); } @@ -1104,10 +1102,7 @@ namespace System.Xml { if (reader.CanReadValueChunk) { - if (_chars == null) - { - _chars = new char[256]; - } + _chars ??= new char[256]; int count; while ((count = reader.ReadValueChunk(_chars, 0, _chars.Length)) > 0) { @@ -1129,10 +1124,7 @@ namespace System.Xml if (reader.CanReadBinaryContent) { // Its best to read in buffers that are a multiple of 3 so we don't break base64 boundaries when converting text - if (_bytes == null) - { - _bytes = new byte[384]; - } + _bytes ??= new byte[384]; int count; while ((count = reader.ReadValueAsBase64(_bytes, 0, _bytes.Length)) > 0) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriterSession.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriterSession.cs index cfdaacd..aa52a87 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriterSession.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriterSession.cs @@ -88,10 +88,7 @@ namespace System.Xml if (_strings.TryGetValue(s.Value, out key)) { - if (keys == null) - { - keys = AddKeys(s.Dictionary, s.Key + 1); - } + keys ??= AddKeys(s.Dictionary, s.Key + 1); keys[s.Key] = (key + 1); return true; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBufferReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBufferReader.cs index b72baab..fab4fb85 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBufferReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBufferReader.cs @@ -72,10 +72,7 @@ namespace System.Xml public void SetBuffer(Stream stream, IXmlDictionary? dictionary, XmlBinaryReaderSession? session) { - if (_streamBuffer == null) - { - _streamBuffer = new byte[128]; - } + _streamBuffer ??= new byte[128]; SetBuffer(stream, _streamBuffer, 0, 0, dictionary, session); _windowOffset = 0; _windowOffsetMax = _streamBuffer.Length; @@ -1079,8 +1076,7 @@ namespace System.Xml public Guid GetGuid(int offset) { - if (_guid == null) - _guid = new byte[16]; + _guid ??= new byte[16]; System.Buffer.BlockCopy(_buffer, offset, _guid, 0, _guid.Length); return new Guid(_guid); } @@ -1287,10 +1283,7 @@ namespace System.Xml private void ReadList(ValueHandle value) { - if (_listValue == null) - { - _listValue = new ValueHandle(this); - } + _listValue ??= new ValueHandle(this); int count = 0; int offset = this.Offset; while (true) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlCanonicalWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlCanonicalWriter.cs index 7af5afb..7ebc16d 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlCanonicalWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlCanonicalWriter.cs @@ -58,21 +58,11 @@ namespace System.Xml { ArgumentNullException.ThrowIfNull(stream); - if (_writer == null) - { - _writer = new XmlUTF8NodeWriter(s_isEscapedAttributeChar, s_isEscapedElementChar); - } + _writer ??= new XmlUTF8NodeWriter(s_isEscapedAttributeChar, s_isEscapedElementChar); _writer.SetOutput(stream, false, null); - if (_elementStream == null) - { - _elementStream = new MemoryStream(); - } - - if (_elementWriter == null) - { - _elementWriter = new XmlUTF8NodeWriter(s_isEscapedAttributeChar, s_isEscapedElementChar); - } + _elementStream ??= new MemoryStream(); + _elementWriter ??= new XmlUTF8NodeWriter(s_isEscapedAttributeChar, s_isEscapedElementChar); _elementWriter.SetOutput(_elementStream, false, null); if (_xmlnsAttributes == null) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlConverter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlConverter.cs index f58260c..e50ec38 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlConverter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlConverter.cs @@ -35,35 +35,11 @@ namespace System.Xml private static Base64Encoding? s_base64Encoding; - public static Base64Encoding Base64Encoding - { - get - { - if (s_base64Encoding == null) - s_base64Encoding = new Base64Encoding(); - return s_base64Encoding; - } - } + public static Base64Encoding Base64Encoding => s_base64Encoding ??= new Base64Encoding(); - private static UTF8Encoding UTF8Encoding - { - get - { - if (s_utf8Encoding == null) - s_utf8Encoding = new UTF8Encoding(false, true); - return s_utf8Encoding; - } - } + private static UTF8Encoding UTF8Encoding => s_utf8Encoding ??= new UTF8Encoding(false, true); - private static UnicodeEncoding UnicodeEncoding - { - get - { - if (s_unicodeEncoding == null) - s_unicodeEncoding = new UnicodeEncoding(false, false, true); - return s_unicodeEncoding; - } - } + private static UnicodeEncoding UnicodeEncoding => s_unicodeEncoding ??= new UnicodeEncoding(false, false, true); public static bool ToBoolean(string value) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionary.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionary.cs index 869d2bc..e07bd76 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionary.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionary.cs @@ -20,15 +20,7 @@ namespace System.Xml private XmlDictionaryString[]? _strings; private int _nextId; - public static IXmlDictionary Empty - { - get - { - if (s_empty == null) - s_empty = new EmptyDictionary(); - return s_empty; - } - } + public static IXmlDictionary Empty => s_empty ??= new EmptyDictionary(); public XmlDictionary() { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryReader.cs index 2eb1a86..92b5bb6 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryReader.cs @@ -23,14 +23,7 @@ namespace System.Xml { ArgumentNullException.ThrowIfNull(reader); - XmlDictionaryReader? dictionaryReader = reader as XmlDictionaryReader; - - if (dictionaryReader == null) - { - dictionaryReader = new XmlWrappedReader(reader, null); - } - - return dictionaryReader; + return reader as XmlDictionaryReader ?? new XmlWrappedReader(reader, null); } public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, XmlDictionaryReaderQuotas quotas) @@ -411,8 +404,7 @@ namespace System.Xml } else { - if (sb == null) - sb = new StringBuilder(result); + sb ??= new StringBuilder(result); if (sb.Length > maxStringContentLength - value.Length) XmlExceptionHelper.ThrowMaxStringContentLengthExceeded(this, maxStringContentLength); sb.Append(value); @@ -481,8 +473,7 @@ namespace System.Xml } else { - if (sb == null) - sb = new StringBuilder(result); + sb ??= new StringBuilder(result); if (sb.Length > maxStringContentLength - value.Length) XmlExceptionHelper.ThrowMaxStringContentLengthExceeded(this, maxStringContentLength); sb.Append(value); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryString.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryString.cs index 97b285f..b98dfdc 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryString.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryString.cs @@ -75,9 +75,7 @@ namespace System.Xml internal byte[] ToUTF8() { - if (_buffer == null) - _buffer = System.Text.Encoding.UTF8.GetBytes(_value); - return _buffer; + return _buffer ??= System.Text.Encoding.UTF8.GetBytes(_value); } public override string ToString() diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryWriter.cs index 091df90..b39afc2 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryWriter.cs @@ -72,14 +72,7 @@ namespace System.Xml { ArgumentNullException.ThrowIfNull(writer); - XmlDictionaryWriter? dictionaryWriter = writer as XmlDictionaryWriter; - - if (dictionaryWriter == null) - { - dictionaryWriter = new XmlWrappedWriter(writer); - } - - return dictionaryWriter; + return writer as XmlDictionaryWriter ?? new XmlWrappedWriter(writer); } public override Task WriteBase64Async(byte[] buffer, int index, int count) @@ -169,9 +162,7 @@ namespace System.Xml { ArgumentNullException.ThrowIfNull(localName); - if (namespaceUri == null) - namespaceUri = XmlDictionaryString.Empty; -#pragma warning suppress 56506 // Microsoft, XmlDictionaryString.Empty is never null + namespaceUri ??= XmlDictionaryString.Empty; WriteQualifiedName(localName.Value, namespaceUri.Value); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlNodeWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlNodeWriter.cs index 88fb622..3cd4abc 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlNodeWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlNodeWriter.cs @@ -16,15 +16,7 @@ namespace System.Xml { private static XmlNodeWriter? s_nullNodeWriter; - public static XmlNodeWriter Null - { - get - { - if (s_nullNodeWriter == null) - s_nullNodeWriter = new XmlNullNodeWriter(); - return s_nullNodeWriter; - } - } + public static XmlNodeWriter Null => s_nullNodeWriter ??= new XmlNullNodeWriter(); public abstract void Flush(); public virtual Task FlushAsync() diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlSigningNodeWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlSigningNodeWriter.cs index a01ee61..7fb89ae 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlSigningNodeWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlSigningNodeWriter.cs @@ -23,8 +23,7 @@ namespace System.Xml public void SetOutput(XmlNodeWriter writer, Stream stream, bool includeComments, string[]? inclusivePrefixes) { _writer = writer; - if (_signingWriter == null) - _signingWriter = new XmlCanonicalWriter(); + _signingWriter ??= new XmlCanonicalWriter(); _signingWriter.SetOutput(stream, includeComments, inclusivePrefixes); _chars = new byte[XmlConverter.MaxPrimitiveChars]; _base64Chars = null; @@ -353,8 +352,7 @@ namespace System.Xml private void WriteBase64Text(byte[] buffer, int offset, int count) { - if (_base64Chars == null) - _base64Chars = new byte[512]; + _base64Chars ??= new byte[512]; Base64Encoding encoding = XmlConverter.Base64Encoding; while (count >= 3) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextReader.cs index 0ee99f4..30a6fb5 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextReader.cs @@ -1427,10 +1427,7 @@ namespace System.Xml private void GetPosition(out int row, out int column) { - if (_rowOffsets == null) - { - _rowOffsets = BufferReader.GetRows(); - } + _rowOffsets ??= BufferReader.GetRows(); int offset = BufferReader.Offset; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextWriter.cs index 5728503..2a1314d 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextWriter.cs @@ -26,10 +26,7 @@ namespace System.Xml stream = new EncodingStreamWrapper(stream, encoding, true); } - if (_writer == null) - { - _writer = new XmlUTF8NodeWriter(); - } + _writer ??= new XmlUTF8NodeWriter(); _writer.SetOutput(stream, ownsStream, encoding); SetOutput(_writer); } @@ -97,14 +94,7 @@ namespace System.Xml _inAttribute = false; } - private byte[] GetCharEntityBuffer() - { - if (_entityChars == null) - { - _entityChars = new byte[maxEntityLength]; - } - return _entityChars; - } + private byte[] GetCharEntityBuffer() => _entityChars ??= new byte[maxEntityLength]; private char[] GetCharBuffer(int charCount) { diff --git a/src/libraries/System.Private.Uri/src/System/DomainNameHelper.cs b/src/libraries/System.Private.Uri/src/System/DomainNameHelper.cs index 2304b40..6c93827 100644 --- a/src/libraries/System.Private.Uri/src/System/DomainNameHelper.cs +++ b/src/libraries/System.Private.Uri/src/System/DomainNameHelper.cs @@ -32,10 +32,7 @@ namespace System end = i; } - if (res == null) - { - res = str.Substring(start, end - start); - } + res ??= str.Substring(start, end - start); if (res == Localhost || res == Loopback) { diff --git a/src/libraries/System.Private.Uri/src/System/UriExt.cs b/src/libraries/System.Private.Uri/src/System/UriExt.cs index fba947f..05a3f5d 100644 --- a/src/libraries/System.Private.Uri/src/System/UriExt.cs +++ b/src/libraries/System.Private.Uri/src/System/UriExt.cs @@ -323,8 +323,7 @@ namespace System return false; } - if (result is null) - result = CreateHelper(newUriString!, dontEscape, UriKind.Absolute, ref e); + result ??= CreateHelper(newUriString!, dontEscape, UriKind.Absolute, ref e); result?.DebugSetLeftCtor(); return e is null && result != null && result.IsAbsoluteUri; diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XContainer.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XContainer.cs index d656e8f..cec8795 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XContainer.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XContainer.cs @@ -920,10 +920,7 @@ namespace System.Xml.Linq } break; case XmlNodeType.EndElement: - if (_currentContainer.content == null) - { - _currentContainer.content = string.Empty; - } + _currentContainer.content ??= string.Empty; if (_currentContainer == rootContainer) return false; _currentContainer = _currentContainer.parent!; break; @@ -979,10 +976,7 @@ namespace System.Xml.Linq } break; case XmlNodeType.EndElement: - if (_currentContainer.content == null) - { - _currentContainer.content = string.Empty; - } + _currentContainer.content ??= string.Empty; if (_currentContainer == rootContainer) return false; _currentContainer = _currentContainer.parent!; break; @@ -1059,10 +1053,7 @@ namespace System.Xml.Linq } case XmlNodeType.EndElement: { - if (_currentContainer.content == null) - { - _currentContainer.content = string.Empty; - } + _currentContainer.content ??= string.Empty; // Store the line info of the end element tag. // Note that since we've got EndElement the current container must be an XElement XElement? e = _currentContainer as XElement; @@ -1178,10 +1169,7 @@ namespace System.Xml.Linq } case XmlNodeType.EndElement: { - if (_currentContainer.content == null) - { - _currentContainer.content = string.Empty; - } + _currentContainer.content ??= string.Empty; // Store the line info of the end element tag. // Note that since we've got EndElement the current container must be an XElement XElement? e = _currentContainer as XElement; diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNode.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNode.cs index 5e64253..88efc58 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNode.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNode.cs @@ -78,26 +78,12 @@ namespace System.Xml.Linq /// /// Gets a comparer that can compare the relative position of two nodes. /// - public static XNodeDocumentOrderComparer DocumentOrderComparer - { - get - { - if (s_documentOrderComparer == null) s_documentOrderComparer = new XNodeDocumentOrderComparer(); - return s_documentOrderComparer; - } - } + public static XNodeDocumentOrderComparer DocumentOrderComparer => s_documentOrderComparer ??= new XNodeDocumentOrderComparer(); /// /// Gets a comparer that can compare two nodes for value equality. /// - public static XNodeEqualityComparer EqualityComparer - { - get - { - if (s_equalityComparer == null) s_equalityComparer = new XNodeEqualityComparer(); - return s_equalityComparer; - } - } + public static XNodeEqualityComparer EqualityComparer => s_equalityComparer ??= new XNodeEqualityComparer(); /// /// Adds the specified content immediately after this node. The diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNodeBuilder.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNodeBuilder.cs index 1826064..812c1d5 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNodeBuilder.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNodeBuilder.cs @@ -208,10 +208,7 @@ namespace System.Xml.Linq private void Add(object o) { - if (_content == null) - { - _content = new List(); - } + _content ??= new List(); _content.Add(o); } diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNodeReader.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNodeReader.cs index 4540cee..930dd70 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNodeReader.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNodeReader.cs @@ -731,11 +731,11 @@ namespace System.Xml.Linq { return false; } - XAttribute? a = _source as XAttribute; - if (a == null) - { - a = _parent as XAttribute; - } + + XAttribute? a = + _source as XAttribute ?? + _parent as XAttribute; + if (a != null) { if (a.parent != null) @@ -813,11 +813,11 @@ namespace System.Xml.Linq } return false; } - XAttribute? a = _source as XAttribute; - if (a == null) - { - a = _parent as XAttribute; - } + + XAttribute? a = + _source as XAttribute ?? + _parent as XAttribute; + if (a != null) { if (a.parent != null && ((XElement)a.parent).lastAttr != a) diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Schema/XNodeValidator.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Schema/XNodeValidator.cs index 372c606..5c98957 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Schema/XNodeValidator.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Schema/XNodeValidator.cs @@ -153,10 +153,7 @@ namespace System.Xml.Schema private void ReplaceSchemaInfo(XObject o, XmlSchemaInfo schemaInfo) { - if (schemaInfos == null) - { - schemaInfos = new Dictionary(new XmlSchemaInfoEqualityComparer()); - } + schemaInfos ??= new Dictionary(new XmlSchemaInfoEqualityComparer()); XmlSchemaInfo? si = o.Annotation(); if (si != null) { diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/XPath/XNodeNavigator.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/XPath/XNodeNavigator.cs index 881ddb9..ea7d1f2 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/XPath/XNodeNavigator.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/XPath/XNodeNavigator.cs @@ -431,11 +431,8 @@ namespace System.Xml.XPath } break; case XPathNamespaceScope.All: - a = GetFirstNamespaceDeclarationGlobal(e); - if (a == null) - { - a = GetXmlNamespaceDeclaration(); - } + a = GetFirstNamespaceDeclarationGlobal(e) ?? + GetXmlNamespaceDeclaration(); break; } if (a != null) diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/XPath/XObjectExtensions.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/XPath/XObjectExtensions.cs index 829b2e3..a6444ad 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/XPath/XObjectExtensions.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/XPath/XObjectExtensions.cs @@ -9,11 +9,7 @@ namespace System.Xml.XPath { public static XContainer? GetParent(this XObject obj) { - XContainer? ret = obj.Parent; - if (ret == null) - { - ret = obj.Document; - } + XContainer? ret = (XContainer?)obj.Parent ?? obj.Document; if (ret == obj) { return null; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Base64Encoder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Base64Encoder.cs index 2900713..720b5d4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Base64Encoder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Base64Encoder.cs @@ -66,10 +66,7 @@ namespace System.Xml if (_leftOverBytesCount > 0) { count -= _leftOverBytesCount; - if (_leftOverBytes == null) - { - _leftOverBytes = new byte[3]; - } + _leftOverBytes ??= new byte[3]; for (int i = 0; i < _leftOverBytesCount; i++) { _leftOverBytes[i] = buffer[index + count + i]; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Base64EncoderAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Base64EncoderAsync.cs index 0b4a3d2..3eb3a87 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Base64EncoderAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Base64EncoderAsync.cs @@ -50,10 +50,7 @@ namespace System.Xml if (_leftOverBytesCount > 0) { count -= _leftOverBytesCount; - if (_leftOverBytes == null) - { - _leftOverBytes = new byte[3]; - } + _leftOverBytes ??= new byte[3]; for (int i = 0; i < _leftOverBytesCount; i++) { _leftOverBytes[i] = buffer[index + count + i]; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/BinaryXml/XmlBinaryReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/BinaryXml/XmlBinaryReader.cs index fddf94c..6bba053 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/BinaryXml/XmlBinaryReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/BinaryXml/XmlBinaryReader.cs @@ -2766,11 +2766,7 @@ namespace System.Xml while (PeekToken() == BinXmlToken.CData) { _pos++; // skip over token byte - if (sb == null) - { - sb = new StringBuilder(value.Length + value.Length / 2); - sb.Append(value); - } + sb ??= new StringBuilder(value.Length + value.Length / 2).Append(value); sb.Append(ParseText()); } if (sb != null) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/BitStack.cs b/src/libraries/System.Private.Xml/src/System/Xml/BitStack.cs index 5482a32..913257a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/BitStack.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/BitStack.cs @@ -80,10 +80,7 @@ namespace System.Xml { int len; - if (_bitStack == null) - { - _bitStack = new uint[16]; - } + _bitStack ??= new uint[16]; // Push current unsigned int (which has been filled) onto a stack // and initialize this.curr to be used for future pushes. diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathDocumentBuilder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathDocumentBuilder.cs index c8ec2d3..388852f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathDocumentBuilder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathDocumentBuilder.cs @@ -600,13 +600,12 @@ namespace MS.Internal.Xml.Cache IDtdAttributeInfo? idAttribute = attrList.LookupIdAttribute(); if (idAttribute != null) { - if (_elemIdMap == null) - _elemIdMap = new Hashtable(); + _elemIdMap ??= new Hashtable(); // Id was defined in DTD and DTD doesn't have notion of namespace so we should // use prefix instead of namespace here. Schema already does this for us. _elemIdMap.Add(new XmlQualifiedName(attrList.LocalName, attrList.Prefix), - new XmlQualifiedName(idAttribute.LocalName, idAttribute.Prefix)); + new XmlQualifiedName(idAttribute.LocalName, idAttribute.Prefix)); } } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathDocumentNavigator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathDocumentNavigator.cs index d097357..493eee1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathDocumentNavigator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathDocumentNavigator.cs @@ -126,11 +126,7 @@ namespace MS.Internal.Xml.Cache } else { - if (bldr == null) - { - bldr = new StringBuilder(); - bldr.Append(s); - } + bldr ??= new StringBuilder().Append(s); bldr.Append(value); } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/HtmlEncodedRawTextWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/HtmlEncodedRawTextWriter.cs index e30d1c8..fd11ea2 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/HtmlEncodedRawTextWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/HtmlEncodedRawTextWriter.cs @@ -451,10 +451,7 @@ namespace System.Xml { base.RawText(" 0) { CheckNCName(prefix); - if (ns == null) - { - ns = LookupNamespace(prefix); - } + ns ??= LookupNamespace(prefix); if (ns == null || (ns != null && ns.Length == 0)) { throw new ArgumentException(SR.Xml_PrefixForEmptyNs); @@ -640,10 +634,7 @@ namespace System.Xml prefix = LookupPrefix(namespaceName); } - if (prefix == null) - { - prefix = string.Empty; - } + prefix ??= string.Empty; } if (namespaceName == null) { @@ -651,10 +642,7 @@ namespace System.Xml { namespaceName = LookupNamespace(prefix); } - if (namespaceName == null) - { - namespaceName = string.Empty; - } + namespaceName ??= string.Empty; } if (prefix.Length == 0) @@ -873,10 +861,7 @@ namespace System.Xml { try { - if (text == null) - { - text = string.Empty; - } + text ??= string.Empty; AdvanceState(Token.CData); _writer.WriteCData(text); } @@ -891,10 +876,7 @@ namespace System.Xml { try { - if (text == null) - { - text = string.Empty; - } + text ??= string.Empty; AdvanceState(Token.Comment); _writer.WriteComment(text); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterAsync.cs index 1129fad..3770909 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterAsync.cs @@ -217,18 +217,12 @@ namespace System.Xml { prefix = LookupPrefix(ns); } - if (prefix == null) - { - prefix = string.Empty; - } + prefix ??= string.Empty; } else if (prefix.Length > 0) { CheckNCName(prefix); - if (ns == null) - { - ns = LookupNamespace(prefix); - } + ns ??= LookupNamespace(prefix); if (ns == null || (ns != null && ns.Length == 0)) { throw new ArgumentException(SR.Xml_PrefixForEmptyNs); @@ -498,10 +492,7 @@ namespace System.Xml if (!(localName == "xmlns" && namespaceName == XmlReservedNs.NsXmlNs)) prefix = LookupPrefix(namespaceName); } - if (prefix == null) - { - prefix = string.Empty; - } + prefix ??= string.Empty; } if (namespaceName == null) @@ -510,10 +501,7 @@ namespace System.Xml { namespaceName = LookupNamespace(prefix); } - if (namespaceName == null) - { - namespaceName = string.Empty; - } + namespaceName ??= string.Empty; } if (prefix.Length == 0) @@ -792,10 +780,7 @@ namespace System.Xml { try { - if (text == null) - { - text = string.Empty; - } + text ??= string.Empty; await AdvanceStateAsync(Token.Comment).ConfigureAwait(false); await _writer.WriteCommentAsync(text).ConfigureAwait(false); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdCachingReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdCachingReader.cs index 2d3660b..0e026f8 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdCachingReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdCachingReader.cs @@ -667,13 +667,7 @@ namespace System.Xml Array.Copy(_attributeEvents, newAttributeEvents, _attributeEvents.Length); _attributeEvents = newAttributeEvents; } - attInfo = _attributeEvents[attIndex]; - if (attInfo == null) - { - attInfo = new ValidatingReaderNodeData(XmlNodeType.Attribute); - _attributeEvents[attIndex] = attInfo; - } - return attInfo; + return _attributeEvents[attIndex] ??= new ValidatingReaderNodeData(XmlNodeType.Attribute); } private ValidatingReaderNodeData AddContent(XmlNodeType nodeType) @@ -692,12 +686,7 @@ namespace System.Xml Array.Copy(_contentEvents, newContentEvents, _contentEvents.Length); _contentEvents = newContentEvents; } - contentInfo = _contentEvents[_contentIndex]; - if (contentInfo == null) - { - contentInfo = new ValidatingReaderNodeData(nodeType); - _contentEvents[_contentIndex] = contentInfo; - } + contentInfo = _contentEvents[_contentIndex] ??= new ValidatingReaderNodeData(nodeType); _contentIndex++; return contentInfo; } @@ -764,10 +753,7 @@ namespace System.Xml private ValidatingReaderNodeData CreateDummyTextNode(string attributeValue, int depth) { - if (_textNode == null) - { - _textNode = new ValidatingReaderNodeData(XmlNodeType.Text); - } + _textNode ??= new ValidatingReaderNodeData(XmlNodeType.Text); _textNode.Depth = depth; _textNode.RawValue = attributeValue; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReader.cs index c43f4b1..5176203 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReader.cs @@ -2321,14 +2321,7 @@ namespace System.Xml _attributePSVINodes = newPSVINodes; } - attInfo = _attributePSVINodes[attIndex]; - if (attInfo == null) - { - attInfo = new AttributePSVIInfo(); - _attributePSVINodes[attIndex] = attInfo; - } - - return attInfo; + return _attributePSVINodes[attIndex] ??= new AttributePSVIInfo(); } private bool IsXSDRoot(string localName, string ns) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/DiagnosticsSwitches.cs b/src/libraries/System.Private.Xml/src/System/Xml/DiagnosticsSwitches.cs index e8277ad..3359f31 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/DiagnosticsSwitches.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/DiagnosticsSwitches.cs @@ -10,30 +10,10 @@ namespace System.Xml private static volatile BooleanSwitch? s_keepTempFiles; private static volatile BooleanSwitch? s_nonRecursiveTypeLoading; - public static BooleanSwitch KeepTempFiles - { - get - { - if (s_keepTempFiles == null) - { - s_keepTempFiles = new BooleanSwitch("XmlSerialization.Compilation", "Keep XmlSerialization generated (temp) files."); - } + public static BooleanSwitch KeepTempFiles => + s_keepTempFiles ??= new BooleanSwitch("XmlSerialization.Compilation", "Keep XmlSerialization generated (temp) files."); - return s_keepTempFiles; - } - } - - public static BooleanSwitch NonRecursiveTypeLoading - { - get - { - if (s_nonRecursiveTypeLoading == null) - { - s_nonRecursiveTypeLoading = new BooleanSwitch("XmlSerialization.NonRecursiveTypeLoading", "Turn on non-recursive algorithm generating XmlMappings for CLR types."); - } - - return s_nonRecursiveTypeLoading; - } - } + public static BooleanSwitch NonRecursiveTypeLoading => + s_nonRecursiveTypeLoading ??= new BooleanSwitch("XmlSerialization.NonRecursiveTypeLoading", "Turn on non-recursive algorithm generating XmlMappings for CLR types."); } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentSchemaValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentSchemaValidator.cs index d1ffd7a..e7e2210 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentSchemaValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentSchemaValidator.cs @@ -157,10 +157,8 @@ namespace System.Xml CreateValidator(partialValidationType, validationFlags); if (_psviAugmentation) { - if (_schemaInfo == null) - { //Might have created it during FindSchemaInfo - _schemaInfo = new XmlSchemaInfo(); - } + //Might have created it during FindSchemaInfo + _schemaInfo ??= new XmlSchemaInfo(); _attributeSchemaInfo = new XmlSchemaInfo(); } ValidateNode(nodeToValidate); @@ -221,27 +219,13 @@ namespace System.Xml return dictionary; } - public string? LookupNamespace(string prefix) - { - string? namespaceName = _nsManager.LookupNamespace(prefix); - if (namespaceName == null) - { - namespaceName = _startNode!.GetNamespaceOfPrefixStrict(prefix); - } - - return namespaceName; - } + public string? LookupNamespace(string prefix) => + _nsManager.LookupNamespace(prefix) ?? + _startNode!.GetNamespaceOfPrefixStrict(prefix); - public string? LookupPrefix(string namespaceName) - { - string? prefix = _nsManager.LookupPrefix(namespaceName); - if (prefix == null) - { - prefix = _startNode!.GetPrefixOfNamespaceStrict(namespaceName); - } - - return prefix; - } + public string? LookupPrefix(string namespaceName) => + _nsManager.LookupPrefix(namespaceName) ?? + _startNode!.GetPrefixOfNamespaceStrict(namespaceName); private IXmlNamespaceResolver NamespaceResolver { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/DomNameTable.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/DomNameTable.cs index 069d4d5..28296c0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/DomNameTable.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/DomNameTable.cs @@ -28,14 +28,8 @@ namespace System.Xml public XmlName? GetName(string? prefix, string localName, string? ns, IXmlSchemaInfo? schemaInfo) { - if (prefix == null) - { - prefix = string.Empty; - } - if (ns == null) - { - ns = string.Empty; - } + prefix ??= string.Empty; + ns ??= string.Empty; int hashCode = XmlName.GetHashCode(localName); @@ -58,14 +52,8 @@ namespace System.Xml public XmlName AddName(string? prefix, string localName, string? ns, IXmlSchemaInfo? schemaInfo) { - if (prefix == null) - { - prefix = string.Empty; - } - if (ns == null) - { - ns = string.Empty; - } + prefix ??= string.Empty; + ns ??= string.Empty; int hashCode = XmlName.GetHashCode(localName); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocument.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocument.cs index ae6a6c3..0f42ece 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocument.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocument.cs @@ -255,8 +255,7 @@ namespace System.Xml //string.Empty) because in DTD, the namespace is not supported if (_htElementIDAttrDecl == null || _htElementIDAttrDecl[eleName] == null) { - if (_htElementIDAttrDecl == null) - _htElementIDAttrDecl = new Hashtable(); + _htElementIDAttrDecl ??= new Hashtable(); _htElementIDAttrDecl.Add(eleName, attrName); return true; } @@ -312,8 +311,7 @@ namespace System.Xml { if (_htElementIdMap == null || !_htElementIdMap.Contains(id)) { - if (_htElementIdMap == null) - _htElementIdMap = new Hashtable(); + _htElementIdMap ??= new Hashtable(); ArrayList elementList = new ArrayList(); elementList.Add(new WeakReference(elem)); _htElementIdMap.Add(id, elementList); @@ -427,19 +425,8 @@ namespace System.Xml public XmlSchemaSet Schemas { - get - { - if (_schemas == null) - { - _schemas = new XmlSchemaSet(NameTable); - } - return _schemas; - } - - set - { - _schemas = value; - } + get => _schemas ??= new XmlSchemaSet(NameTable); + set => _schemas = value; } internal bool CanReportValidity @@ -538,8 +525,7 @@ namespace System.Xml internal override bool CanInsertBefore(XmlNode newChild, XmlNode? refChild) { - if (refChild == null) - refChild = FirstChild; + refChild ??= FirstChild; if (refChild == null) return true; @@ -581,8 +567,7 @@ namespace System.Xml internal override bool CanInsertAfter(XmlNode newChild, XmlNode? refChild) { - if (refChild == null) - refChild = LastChild; + refChild ??= LastChild; if (refChild == null) return true; @@ -1107,13 +1092,8 @@ namespace System.Xml internal XmlNamedNodeMap Entities { - get - { - if (_entities == null) - _entities = new XmlNamedNodeMap(this); - return _entities; - } - set { _entities = value; } + get => _entities ??= new XmlNamedNodeMap(this); + set => _entities = value; } internal bool IsLoading diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocumentType.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocumentType.cs index 4d468eb..fffb34a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocumentType.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocumentType.cs @@ -76,28 +76,10 @@ namespace System.Xml } // Gets the collection of XmlEntity nodes declared in the document type declaration. - public XmlNamedNodeMap Entities - { - get - { - if (_entities == null) - _entities = new XmlNamedNodeMap(this); - - return _entities; - } - } + public XmlNamedNodeMap Entities => _entities ??= new XmlNamedNodeMap(this); // Gets the collection of XmlNotation nodes present in the document type declaration. - public XmlNamedNodeMap Notations - { - get - { - if (_notations == null) - _notations = new XmlNamedNodeMap(this); - - return _notations; - } - } + public XmlNamedNodeMap Notations => _notations ??= new XmlNamedNodeMap(this); // // DOM Level 2 diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElement.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElement.cs index 15193b4..44a32c3 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElement.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElement.cs @@ -242,10 +242,7 @@ namespace System.Xml { lock (OwnerDocument.objLock) { - if (_attributes == null) - { - _attributes = new XmlAttributeCollection(this); - } + _attributes ??= new XmlAttributeCollection(this); } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElementList.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElementList.cs index 83fdf7c..c251362 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElementList.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElementList.cs @@ -133,8 +133,10 @@ namespace System.Xml private XmlNode? PrevElemInPreOrder(XmlNode curNode) { Debug.Assert(curNode != null); + //For preorder walking, the previous node will be the right-most node in the tree of PreviousSibling of the curNode XmlNode? retNode = curNode.PreviousSibling; + // so if the PreviousSibling is not null, going through the tree down to find the right-most node while (retNode != null) { @@ -142,9 +144,10 @@ namespace System.Xml break; retNode = retNode.LastChild; } + // if no PreviousSibling, the previous node will be the curNode's parentNode - if (retNode == null) - retNode = curNode.ParentNode; + retNode ??= curNode.ParentNode; + // if the final retNode is rootNode, consider having walked through the tree and no more previous node if (retNode == _rootNode) retNode = null; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlName.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlName.cs index 4d9ee0d..be0897f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlName.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlName.cs @@ -94,10 +94,7 @@ namespace System.Xml string n = $"{_prefix}:{_localName}"; lock (ownerDoc.NameTable) { - if (_name == null) - { - _name = ownerDoc.NameTable.Add(n); - } + _name ??= ownerDoc.NameTable.Add(n); } } else diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNode.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNode.cs index c5386af..46faa53 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNode.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNode.cs @@ -581,11 +581,7 @@ namespace System.Xml // Adds the specified node to the end of the list of children of this node. public virtual XmlNode? AppendChild(XmlNode newChild) { - XmlDocument? thisDoc = OwnerDocument; - if (thisDoc == null) - { - thisDoc = this as XmlDocument; - } + XmlDocument? thisDoc = OwnerDocument ?? this as XmlDocument; if (!IsContainer) throw new InvalidOperationException(SR.Xdom_Node_Insert_Contain); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeReader.cs index 3e311a6..e3ec143 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeReader.cs @@ -865,13 +865,10 @@ namespace System.Xml } // construct the name of the xmlns attribute - string attrName; - if (prefix == null) - prefix = string.Empty; - if (prefix.Length == 0) - attrName = "xmlns"; - else - attrName = $"xmlns:{prefix}"; + prefix ??= string.Empty; + string attrName = prefix.Length == 0 ? + "xmlns" : + $"xmlns:{prefix}"; // walk up the XmlNode parent chain, looking for the xmlns attribute XmlNode? node = _curNode; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/BaseProcessor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/BaseProcessor.cs index e63a9e0..10fa6f1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/BaseProcessor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/BaseProcessor.cs @@ -35,17 +35,7 @@ namespace System.Xml.Schema get { return _nameTable; } } - protected SchemaNames SchemaNames - { - get - { - if (_schemaNames == null) - { - _schemaNames = new SchemaNames(_nameTable); - } - return _schemaNames; - } - } + protected SchemaNames SchemaNames => _schemaNames ??= new SchemaNames(_nameTable); protected ValidationEventHandler? EventHandler { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/ContentValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/ContentValidator.cs index c730929..4a2f2ea 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/ContentValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/ContentValidator.cs @@ -1630,10 +1630,7 @@ namespace System.Xml.Schema { if (transition[i] != -1) { - if (names == null) - { - names = new ArrayList(); - } + names ??= new ArrayList(); XmlSchemaParticle? p = (XmlSchemaParticle?)_symbols.GetParticle(i); if (p == null) @@ -1783,10 +1780,7 @@ namespace System.Xml.Schema BitSet curpos = context.CurPos[context.CurrentState.CurPosIndex]; for (int pos = curpos.NextSet(-1); pos != -1; pos = curpos.NextSet(pos)) { - if (names == null) - { - names = new ArrayList(); - } + names ??= new ArrayList(); XmlSchemaParticle? p = (XmlSchemaParticle?)_positions[pos].particle; if (p == null) { @@ -1992,10 +1986,7 @@ namespace System.Xml.Schema } RangePositionInfo newRPosInfo = runningPositions[matchCount]; - if (newRPosInfo.rangeCounters == null) - { - newRPosInfo.rangeCounters = new decimal[_minMaxNodesCount]; - } + newRPosInfo.rangeCounters ??= new decimal[_minMaxNodesCount]; Array.Copy(rposInfo.rangeCounters, newRPosInfo.rangeCounters, rposInfo.rangeCounters.Length); decimal count = ++newRPosInfo.rangeCounters[lrNode.Pos]; @@ -2020,10 +2011,7 @@ namespace System.Xml.Schema runningPositions[matchCount] = newRPosInfo; j = matchCount + 1; newRPosInfo = runningPositions[j]; - if (newRPosInfo.rangeCounters == null) - { - newRPosInfo.rangeCounters = new decimal[_minMaxNodesCount]; - } + newRPosInfo.rangeCounters ??= new decimal[_minMaxNodesCount]; Array.Copy(rposInfo.rangeCounters, newRPosInfo.rangeCounters, rposInfo.rangeCounters.Length); newRPosInfo.curpos = _followpos[cPos]; newRPosInfo.rangeCounters[lrNode.Pos] = 0; @@ -2066,10 +2054,7 @@ namespace System.Xml.Schema } for (int pos = expectedPos.NextSet(-1); pos != -1; pos = expectedPos.NextSet(pos)) { - if (names == null) - { - names = new ArrayList(); - } + names ??= new ArrayList(); int symbol = _positions[pos].symbol; if (symbol >= 0) { //non range nodes diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DataTypeImplementation.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DataTypeImplementation.cs index cb155a7..7ff823d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DataTypeImplementation.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DataTypeImplementation.cs @@ -471,17 +471,8 @@ namespace System.Xml.Schema internal override FacetsChecker FacetsChecker { get { return miscFacetsChecker; } } - internal override XmlValueConverter ValueConverter - { - get - { - if (_valueConverter == null) - { - _valueConverter = CreateValueConverter(_parentSchemaType!); - } - return _valueConverter; - } - } + internal override XmlValueConverter ValueConverter => + _valueConverter ??= CreateValueConverter(_parentSchemaType!); public override XmlTokenizedType TokenizedType { get { return XmlTokenizedType.None; } } @@ -944,10 +935,8 @@ namespace System.Xml.Schema } while (simpleType != null && simpleType != DatatypeImplementation.AnySimpleType); } - if (listItemType == null) - { //Get built-in simple type for the typecode - listItemType = DatatypeImplementation.GetSimpleTypeFromTypeCode(schemaType!.Datatype!.TypeCode); - } + //Get built-in simple type for the typecode + listItemType ??= DatatypeImplementation.GetSimpleTypeFromTypeCode(schemaType!.Datatype!.TypeCode); return XmlListConverter.Create(listItemType.ValueConverter); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParser.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParser.cs index 551e977..b490e2b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParser.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParser.cs @@ -1358,10 +1358,7 @@ namespace System.Xml private void AddUndeclaredNotation(string notationName) { - if (_undeclaredNotations == null) - { - _undeclaredNotations = new Dictionary(); - } + _undeclaredNotations ??= new Dictionary(); UndeclaredNotation un = new UndeclaredNotation(notationName, LineNo, LinePos - notationName.Length); UndeclaredNotation? loggedUn; if (_undeclaredNotations.TryGetValue(notationName, out loggedUn)) @@ -3593,10 +3590,7 @@ namespace System.Xml } if (j > i + 1) { - if (norValue == null) - { - norValue = new StringBuilder(len); - } + norValue ??= new StringBuilder(len); norValue.Append(value, startPos, i - startPos + 1); startPos = j; i = j - 1; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdValidator.cs index 4c0964a..fefc1fd 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdValidator.cs @@ -417,11 +417,7 @@ namespace System.Xml.Schema // Note: It used to be true that we only called this if _fValidate was true, // but due to the fact that you can now dynamically type somethign as an ID // that is no longer true. - if (_IDs == null) - { - _IDs = new Hashtable(); - } - + _IDs ??= new Hashtable(); _IDs.Add(name, node); } @@ -570,10 +566,7 @@ namespace System.Xml.Schema { try { - if (baseUriStr == null) - { - baseUriStr = string.Empty; - } + baseUriStr ??= string.Empty; XmlSchemaDatatype dtype = attdef.Datatype; if (dtype == null) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/FacetChecker.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/FacetChecker.cs index cd109ff..8e0219f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/FacetChecker.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/FacetChecker.cs @@ -171,10 +171,7 @@ namespace System.Xml.Schema internal void CompileEnumerationFacet(XmlSchemaFacet facet, IXmlNamespaceResolver nsmgr, XmlNameTable nameTable) { CheckProhibitedFlag(facet, RestrictionFlags.Enumeration, SR.Sch_EnumerationFacetProhibited); - if (_derivedRestriction.Enumeration == null) - { - _derivedRestriction.Enumeration = new ArrayList(); - } + _derivedRestriction.Enumeration ??= new ArrayList(); _derivedRestriction.Enumeration.Add(ParseFacetValue(_datatype, facet, SR.Sch_EnumerationFacetInvalid, nsmgr, nameTable)); SetFlag(facet, RestrictionFlags.Enumeration); } @@ -357,10 +354,7 @@ namespace System.Xml.Schema //needs to be converted to a RegEx if (_firstPattern == false) { - if (_derivedRestriction.Patterns == null) - { - _derivedRestriction.Patterns = new ArrayList(); - } + _derivedRestriction.Patterns ??= new ArrayList(); try { _regStr!.Append(')'); @@ -604,10 +598,7 @@ namespace System.Xml.Schema if ((_baseFlags & RestrictionFlags.Enumeration) != 0) { - if (_derivedRestriction.Enumeration == null) - { - _derivedRestriction.Enumeration = baseRestriction.Enumeration; - } + _derivedRestriction.Enumeration ??= baseRestriction.Enumeration; SetFlag(RestrictionFlags.Enumeration); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Inference/Infer.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Inference/Infer.cs index c5a5a88..3f0d065 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Inference/Infer.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Inference/Infer.cs @@ -168,10 +168,7 @@ namespace System.Xml.Schema public XmlSchemaSet InferSchema(XmlReader instanceDocument, XmlSchemaSet schemas) { - if (schemas == null) - { - schemas = new XmlSchemaSet(_nametable); - } + schemas ??= new XmlSchemaSet(_nametable); return InferSchema1(instanceDocument, schemas); } @@ -1011,15 +1008,10 @@ namespace System.Xml.Schema } else if (elem.SchemaTypeName != XmlQualifiedName.Empty) { - effectiveSchemaType = _schemaSet!.GlobalTypes[elem.SchemaTypeName] as XmlSchemaType; - if (effectiveSchemaType == null) - { - effectiveSchemaType = XmlSchemaType.GetBuiltInSimpleType(elem.SchemaTypeName); - } - if (effectiveSchemaType == null) - { - effectiveSchemaType = XmlSchemaType.GetBuiltInComplexType(elem.SchemaTypeName); - } + effectiveSchemaType = + _schemaSet!.GlobalTypes[elem.SchemaTypeName] as XmlSchemaType ?? + (XmlSchemaType?)XmlSchemaType.GetBuiltInSimpleType(elem.SchemaTypeName) ?? + (XmlSchemaType?)XmlSchemaType.GetBuiltInComplexType(elem.SchemaTypeName); } } return effectiveSchemaType; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Preprocessor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Preprocessor.cs index 88b9949..fd6222a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Preprocessor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Preprocessor.cs @@ -206,19 +206,8 @@ namespace System.Xml.Schema internal XmlReaderSettings ReaderSettings { - get - { - if (_readerSettings == null) - { - _readerSettings = new XmlReaderSettings(); - _readerSettings.DtdProcessing = DtdProcessing.Prohibit; - } - return _readerSettings; - } - set - { - _readerSettings = value; - } + get => _readerSettings ??= new XmlReaderSettings() { DtdProcessing = DtdProcessing.Prohibit }; + set => _readerSettings = value; } //internal Dictionary SchemaLocations { @@ -509,11 +498,7 @@ namespace System.Xml.Schema } //Add the schema's targetnamespace - string? tns = schema.TargetNamespace; - if (tns == null) - { - tns = string.Empty; - } + string tns = schema.TargetNamespace ?? string.Empty; if (_referenceNamespaces[tns] == null) { _referenceNamespaces.Add(tns, tns); @@ -690,10 +675,7 @@ namespace System.Xml.Schema break; case Compositor.Redefine: - if (_redefinedList == null) - { - _redefinedList = new ArrayList(); - } + _redefinedList ??= new ArrayList(); _redefinedList.Add(new RedefineEntry((external as XmlSchemaRedefine)!, _rootSchemaForRedefine!)); if (_processedExternals[includedSchema] != null) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionCompiler.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionCompiler.cs index 345b81e..436da7c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionCompiler.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionCompiler.cs @@ -513,10 +513,7 @@ namespace System.Xml.Schema else { group.IsProcessing = true; - if (group.CanonicalParticle == null) - { - group.CanonicalParticle = CannonicalizeParticle(group.Particle, true, true); - } + group.CanonicalParticle ??= CannonicalizeParticle(group.Particle, true, true); Debug.Assert(group.CanonicalParticle != null); group.IsProcessing = false; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaDeclBase.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaDeclBase.cs index c46f062..2b6eae8 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaDeclBase.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaDeclBase.cs @@ -97,10 +97,7 @@ namespace System.Xml.Schema internal void AddValue(string value) { - if (values == null) - { - values = new List(); - } + values ??= new List(); values.Add(value); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaElementDecl.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaElementDecl.cs index 0e7d7b4..72b3645 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaElementDecl.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaElementDecl.cs @@ -194,10 +194,7 @@ namespace System.Xml.Schema } if (attdef.Presence == SchemaDeclBase.Use.Default || attdef.Presence == SchemaDeclBase.Use.Fixed) { //Not adding RequiredFixed here - if (_defaultAttdefs == null) - { - _defaultAttdefs = new List(); - } + _defaultAttdefs ??= new List(); _defaultAttdefs.Add(attdef); } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaInfo.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaInfo.cs index f85e435..7fc94acb 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaInfo.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaInfo.cs @@ -70,29 +70,11 @@ namespace System.Xml.Schema get { return _undeclaredElementDecls; } } - internal Dictionary GeneralEntities - { - get - { - if (_generalEntities == null) - { - _generalEntities = new Dictionary(); - } - return _generalEntities; - } - } + internal Dictionary GeneralEntities => + _generalEntities ??= new Dictionary(); - internal Dictionary ParameterEntities - { - get - { - if (_parameterEntities == null) - { - _parameterEntities = new Dictionary(); - } - return _parameterEntities; - } - } + internal Dictionary ParameterEntities => + _parameterEntities ??= new Dictionary(); internal SchemaType SchemaType { @@ -115,17 +97,8 @@ namespace System.Xml.Schema get { return _attributeDecls; } } - internal Dictionary Notations - { - get - { - if (_notations == null) - { - _notations = new Dictionary(); - } - return _notations; - } - } + internal Dictionary Notations => + _notations ??= new Dictionary(); internal int ErrorCount { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaSetCompiler.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaSetCompiler.cs index 2d53454..d74f357 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaSetCompiler.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaSetCompiler.cs @@ -143,12 +143,7 @@ namespace System.Xml.Schema string? tns; foreach (XmlSchema? schema in _schemasToCompile.Values) { - tns = schema!.TargetNamespace; - if (tns == null) - { - tns = string.Empty; - } - + tns = schema!.TargetNamespace ?? string.Empty; schemaInfo.TargetNamespaces[tns] = true; } @@ -534,10 +529,7 @@ namespace System.Xml.Schema { if (g.Members[j] != element) { //Exclude the head - if (newMembers == null) - { - newMembers = new ArrayList(); - } + newMembers ??= new ArrayList(); newMembers.Add(g.Members[j]); } } @@ -570,15 +562,8 @@ namespace System.Xml.Schema if (redefinedGroup.SelfReferenceCount == 0) { - if (baseGroup.CanonicalParticle == null) - { - baseGroup.CanonicalParticle = CannonicalizeParticle(baseGroup.Particle, true); - } - - if (redefinedGroup.CanonicalParticle == null) - { - redefinedGroup.CanonicalParticle = CannonicalizeParticle(redefinedGroup.Particle, true); - } + baseGroup.CanonicalParticle ??= CannonicalizeParticle(baseGroup.Particle, true); + redefinedGroup.CanonicalParticle ??= CannonicalizeParticle(redefinedGroup.Particle, true); CompileParticleElements(redefinedGroup.CanonicalParticle); CompileParticleElements(baseGroup.CanonicalParticle); @@ -1884,10 +1869,8 @@ namespace System.Xml.Schema } else if (skipEmptableOnly && !IsParticleEmptiable(baseParticle)) { - if (_restrictionErrorMsg == null) - { //If restriction failed on previous check, do not overwrite error - _restrictionErrorMsg = SR.Sch_GroupBaseRestNotEmptiable; - } + //If restriction failed on previous check, do not overwrite error + _restrictionErrorMsg ??= SR.Sch_GroupBaseRestNotEmptiable; return false; } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrBuilder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrBuilder.cs index 1c7ba68..17825cd 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrBuilder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrBuilder.cs @@ -1244,8 +1244,7 @@ namespace System.Xml.Schema private static void XDR_InitAttribute(XdrBuilder builder, object obj) { - if (builder._BaseDecl == null) - builder._BaseDecl = new DeclBaseInfo(); + builder._BaseDecl ??= new DeclBaseInfo(); builder._BaseDecl._MinOccurs = 0; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrValidator.cs index 71a81d7..7ee3d20 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrValidator.cs @@ -641,10 +641,7 @@ namespace System.Xml.Schema // Note: It used to be true that we only called this if _fValidate was true, // but due to the fact that you can now dynamically type somethign as an ID // that is no longer true. - if (_IDs == null) - { - _IDs = new Hashtable(); - } + _IDs ??= new Hashtable(); _IDs.Add(name, node); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchema.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchema.cs index 383f372..9698559 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchema.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchema.cs @@ -316,56 +316,16 @@ namespace System.Xml.Schema } [XmlIgnore] - public XmlSchemaObjectTable Attributes - { - get - { - if (_attributes == null) - { - _attributes = new XmlSchemaObjectTable(); - } - return _attributes; - } - } + public XmlSchemaObjectTable Attributes => _attributes ??= new XmlSchemaObjectTable(); [XmlIgnore] - public XmlSchemaObjectTable AttributeGroups - { - get - { - if (_attributeGroups == null) - { - _attributeGroups = new XmlSchemaObjectTable(); - } - return _attributeGroups; - } - } + public XmlSchemaObjectTable AttributeGroups => _attributeGroups ??= new XmlSchemaObjectTable(); [XmlIgnore] - public XmlSchemaObjectTable SchemaTypes - { - get - { - if (_types == null) - { - _types = new XmlSchemaObjectTable(); - } - return _types; - } - } + public XmlSchemaObjectTable SchemaTypes => _types ??= new XmlSchemaObjectTable(); [XmlIgnore] - public XmlSchemaObjectTable Elements - { - get - { - if (_elements == null) - { - _elements = new XmlSchemaObjectTable(); - } - return _elements; - } - } + public XmlSchemaObjectTable Elements => _elements ??= new XmlSchemaObjectTable(); [XmlAttribute("id", DataType = "ID")] public string? Id @@ -442,10 +402,7 @@ namespace System.Xml.Schema } [XmlIgnore] - internal XmlDocument Document - { - get { if (_document == null) _document = new XmlDocument(); return _document; } - } + internal XmlDocument Document => _document ??= new XmlDocument(); [XmlIgnore] internal int ErrorCount @@ -547,34 +504,11 @@ namespace System.Xml.Schema _items.Add(annotation); } - internal XmlNameTable NameTable - { - get { if (_nameTable == null) _nameTable = new System.Xml.NameTable(); return _nameTable; } - } + internal XmlNameTable NameTable => _nameTable ??= new System.Xml.NameTable(); - internal ArrayList ImportedSchemas - { - get - { - if (_importedSchemas == null) - { - _importedSchemas = new ArrayList(); - } - return _importedSchemas; - } - } + internal ArrayList ImportedSchemas => _importedSchemas ??= new ArrayList(); - internal ArrayList ImportedNamespaces - { - get - { - if (_importedNamespaces == null) - { - _importedNamespaces = new ArrayList(); - } - return _importedNamespaces; - } - } + internal ArrayList ImportedNamespaces => _importedNamespaces ??= new ArrayList(); internal void GetExternalSchemasList(IList extList, XmlSchema schema) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAttributeGroup.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAttributeGroup.cs index 4397a92..65960d5 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAttributeGroup.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAttributeGroup.cs @@ -45,17 +45,7 @@ namespace System.Xml.Schema } [XmlIgnore] - internal XmlSchemaObjectTable AttributeUses - { - get - { - if (_attributeUses == null) - { - _attributeUses = new XmlSchemaObjectTable(); - } - return _attributeUses; - } - } + internal XmlSchemaObjectTable AttributeUses => _attributeUses ??= new XmlSchemaObjectTable(); [XmlIgnore] internal XmlSchemaAnyAttribute? AttributeWildcard diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaCollection.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaCollection.cs index 7f18467..2dc4d66 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaCollection.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaCollection.cs @@ -290,11 +290,7 @@ namespace System.Xml.Schema } else { - if (_schemaNames == null) - { - _schemaNames = new SchemaNames(_nameTable); - } - return _schemaNames; + return _schemaNames ??= new SchemaNames(_nameTable); } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaComplexType.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaComplexType.cs index 0837f29..b2f8534 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaComplexType.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaComplexType.cs @@ -188,17 +188,8 @@ namespace System.Xml.Schema [XmlElement("attribute", typeof(XmlSchemaAttribute)), XmlElement("attributeGroup", typeof(XmlSchemaAttributeGroupRef))] - public XmlSchemaObjectCollection Attributes - { - get - { - if (_attributes == null) - { - _attributes = new XmlSchemaObjectCollection(); - } - return _attributes; - } - } + public XmlSchemaObjectCollection Attributes => + _attributes ??= new XmlSchemaObjectCollection(); [XmlElement("anyAttribute")] public XmlSchemaAnyAttribute? AnyAttribute @@ -227,17 +218,8 @@ namespace System.Xml.Schema } [XmlIgnore] - public XmlSchemaObjectTable AttributeUses - { - get - { - if (_attributeUses == null) - { - _attributeUses = new XmlSchemaObjectTable(); - } - return _attributeUses; - } - } + public XmlSchemaObjectTable AttributeUses => + _attributeUses ??= new XmlSchemaObjectTable(); [XmlIgnore] public XmlSchemaAnyAttribute? AttributeWildcard @@ -246,17 +228,8 @@ namespace System.Xml.Schema } [XmlIgnore] - internal XmlSchemaObjectTable LocalElements - { - get - { - if (_localElements == null) - { - _localElements = new XmlSchemaObjectTable(); - } - return _localElements; - } - } + internal XmlSchemaObjectTable LocalElements => + _localElements ??= new XmlSchemaObjectTable(); internal void SetContentTypeParticle(XmlSchemaParticle value) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaElement.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaElement.cs index aa22f5e..375ee27 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaElement.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaElement.cs @@ -145,17 +145,8 @@ namespace System.Xml.Schema [XmlElement("key", typeof(XmlSchemaKey)), XmlElement("keyref", typeof(XmlSchemaKeyref)), XmlElement("unique", typeof(XmlSchemaUnique))] - public XmlSchemaObjectCollection Constraints - { - get - { - if (_constraints == null) - { - _constraints = new XmlSchemaObjectCollection(); - } - return _constraints; - } - } + public XmlSchemaObjectCollection Constraints => + _constraints ??= new XmlSchemaObjectCollection(); [XmlIgnore] public XmlQualifiedName QualifiedName diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaObject.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaObject.cs index 7a2882e..62c070b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaObject.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaObject.cs @@ -48,13 +48,8 @@ namespace System.Xml.Schema [XmlNamespaceDeclarations] public XmlSerializerNamespaces Namespaces { - get - { - if (_namespaces == null) - _namespaces = new XmlSerializerNamespaces(); - return _namespaces; - } - set { _namespaces = value; } + get => _namespaces ??= new XmlSerializerNamespaces(); + set => _namespaces = value; } internal virtual void OnAdd(XmlSchemaObjectCollection container, object? item) { } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSet.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSet.cs index 5bf1358..3bee462 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSet.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSet.cs @@ -134,18 +134,12 @@ namespace System.Xml.Schema { _eventHandler -= _internalEventHandler; _eventHandler += value; - if (_eventHandler == null) - { - _eventHandler = _internalEventHandler; - } + _eventHandler ??= _internalEventHandler; } remove { _eventHandler -= value; - if (_eventHandler == null) - { - _eventHandler = _internalEventHandler; - } + _eventHandler ??= _internalEventHandler; } } @@ -191,53 +185,13 @@ namespace System.Xml.Schema } } - public XmlSchemaObjectTable GlobalElements - { - get - { - if (elements == null) - { - elements = new XmlSchemaObjectTable(); - } - return elements; - } - } + public XmlSchemaObjectTable GlobalElements => elements ??= new XmlSchemaObjectTable(); - public XmlSchemaObjectTable GlobalAttributes - { - get - { - if (attributes == null) - { - attributes = new XmlSchemaObjectTable(); - } - return attributes; - } - } + public XmlSchemaObjectTable GlobalAttributes => attributes ??= new XmlSchemaObjectTable(); - public XmlSchemaObjectTable GlobalTypes - { - get - { - if (schemaTypes == null) - { - schemaTypes = new XmlSchemaObjectTable(); - } - return schemaTypes; - } - } + public XmlSchemaObjectTable GlobalTypes => schemaTypes ??= new XmlSchemaObjectTable(); - internal XmlSchemaObjectTable SubstitutionGroups - { - get - { - if (substitutionGroups == null) - { - substitutionGroups = new XmlSchemaObjectTable(); - } - return substitutionGroups; - } - } + internal XmlSchemaObjectTable SubstitutionGroups => substitutionGroups ??= new XmlSchemaObjectTable(); /// /// Table of all types extensions @@ -253,17 +207,8 @@ namespace System.Xml.Schema /// /// Table of all types extensions /// - internal XmlSchemaObjectTable TypeExtensions - { - get - { - if (_typeExtensions == null) - { - _typeExtensions = new XmlSchemaObjectTable(); - } - return _typeExtensions; - } - } + internal XmlSchemaObjectTable TypeExtensions => _typeExtensions ??= new XmlSchemaObjectTable(); + //Public Methods /// @@ -287,11 +232,7 @@ namespace System.Xml.Schema lock (InternalSyncObject) { //Check if schema from url has already been added - XmlResolver? tempResolver = _readerSettings.GetXmlResolver(); - if (tempResolver == null) - { - tempResolver = new XmlUrlResolver(); - } + XmlResolver tempResolver = _readerSettings.GetXmlResolver() ?? new XmlUrlResolver(); Uri tempSchemaUri = tempResolver.ResolveUri(null, schemaUri); if (IsSchemaLoaded(tempSchemaUri, targetNamespace, out schema)) { @@ -397,11 +338,7 @@ namespace System.Xml.Schema string? tns = null; foreach (XmlSchema? schema in schemas.SortedSchemas.Values) { - tns = schema!.TargetNamespace; - if (tns == null) - { - tns = string.Empty; - } + tns = schema!.TargetNamespace ?? string.Empty; if (_schemas.ContainsKey(schema.SchemaId) || FindSchemaByNSAndUrl(schema.BaseUri, tns, null) != null) { //Do not already existing url continue; @@ -528,10 +465,7 @@ namespace System.Xml.Schema public bool Contains(string? targetNamespace) { - if (targetNamespace == null) - { - targetNamespace = string.Empty; - } + targetNamespace ??= string.Empty; return _targetNamespaces[targetNamespace] != null; } @@ -745,10 +679,7 @@ namespace System.Xml.Schema { ArrayList tnsSchemas = new ArrayList(); XmlSchema currentSchema; - if (targetNamespace == null) - { - targetNamespace = string.Empty; - } + targetNamespace ??= string.Empty; for (int i = 0; i < _schemas.Count; i++) { currentSchema = (XmlSchema)_schemas.GetByIndex(i)!; @@ -826,9 +757,7 @@ namespace System.Xml.Schema } XmlQualifiedName head = element.SubstitutionGroup; if (!head.IsEmpty) { - if (substTable == null) { - substTable = new XmlSchemaObjectTable(); - } + substTable ??= new XmlSchemaObjectTable(); XmlSchemaSubstitutionGroup substitutionGroup = (XmlSchemaSubstitutionGroup)substTable[head]; if (substitutionGroup == null) { substitutionGroup = new XmlSchemaSubstitutionGroup(); @@ -864,10 +793,7 @@ namespace System.Xml.Schema { ArgumentNullException.ThrowIfNull(reader); - if (targetNamespace == null) - { - targetNamespace = string.Empty; - } + targetNamespace ??= string.Empty; if (validatedNamespaces[targetNamespace] != null) { if (FindSchemaByNSAndUrl(new Uri(reader.BaseURI!, UriKind.RelativeOrAbsolute), targetNamespace, null) != null) @@ -902,11 +828,7 @@ namespace System.Xml.Schema for (int i = 0; i < schema.ImportedSchemas.Count; ++i) { XmlSchema impSchema = (XmlSchema)schema.ImportedSchemas[i]!; - tns = impSchema.TargetNamespace; - if (tns == null) - { - tns = string.Empty; - } + tns = impSchema.TargetNamespace ?? string.Empty; if (validatedNamespaces[tns] != null && (FindSchemaByNSAndUrl(impSchema.BaseUri, tns, oldLocations) == null)) { RemoveRecursive(schema); @@ -1077,10 +999,7 @@ namespace System.Xml.Schema XmlSchemaElement element1 = (XmlSchemaElement)g.Members[j]!; if (element1 != element) { //Exclude the head - if (newMembers == null) - { - newMembers = new List(); - } + newMembers ??= new List(); newMembers.Add(element1); } } @@ -1311,20 +1230,13 @@ namespace System.Xml.Schema } else { - if (_schemaNames == null) - { - _schemaNames = new SchemaNames(_nameTable); - } - return _schemaNames; + return _schemaNames ??= new SchemaNames(_nameTable); } } internal bool IsSchemaLoaded(Uri schemaUri, string? targetNamespace, out XmlSchema? schema) { - if (targetNamespace == null) - { - targetNamespace = string.Empty; - } + targetNamespace ??= string.Empty; if (GetSchemaByUri(schemaUri, out schema)) { if (_schemas.ContainsKey(schema.SchemaId) && (targetNamespace.Length == 0 || targetNamespace == schema.TargetNamespace)) @@ -1525,22 +1437,10 @@ namespace System.Xml.Schema private void VerifyTables() { - if (elements == null) - { - elements = new XmlSchemaObjectTable(); - } - if (attributes == null) - { - attributes = new XmlSchemaObjectTable(); - } - if (schemaTypes == null) - { - schemaTypes = new XmlSchemaObjectTable(); - } - if (substitutionGroups == null) - { - substitutionGroups = new XmlSchemaObjectTable(); - } + elements ??= new XmlSchemaObjectTable(); + attributes ??= new XmlSchemaObjectTable(); + schemaTypes ??= new XmlSchemaObjectTable(); + substitutionGroups ??= new XmlSchemaObjectTable(); } private void InternalValidationCallback(object? sender, ValidationEventArgs e) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidator.cs index f3f8193..ce3757b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidator.cs @@ -327,11 +327,7 @@ namespace System.Xml.Schema { //Do not process schema if processInlineSchema is not set return; } - string? tns = schema.TargetNamespace; - if (tns == null) - { - tns = string.Empty; - } + string? tns = schema.TargetNamespace ?? string.Empty; //Store the previous locations Hashtable schemaLocations = _schemaSet.SchemaLocations; DictionaryEntry[] oldLocations = new DictionaryEntry[schemaLocations.Count]; @@ -356,11 +352,7 @@ namespace System.Xml.Schema for (int i = 0; i < schema.ImportedSchemas.Count; ++i) { //Check for its imports XmlSchema impSchema = (XmlSchema)schema.ImportedSchemas[i]!; - tns = impSchema.TargetNamespace; - if (tns == null) - { - tns = string.Empty; - } + tns = impSchema.TargetNamespace ?? string.Empty; if (_validatedNamespaces[tns] != null && _schemaSet.FindSchemaByNSAndUrl(impSchema.BaseUri, tns, oldLocations) == null) { SendValidationEvent(SR.Sch_ComponentAlreadySeenForNS, tns, XmlSeverityType.Error); @@ -1476,11 +1468,7 @@ namespace System.Xml.Schema Exception? exception = dtype.TryParseValue(parsedValue, _nameTable, _nsResolver, out typedValue); if (exception != null) { - string? stringValue = parsedValue as string; - if (stringValue == null) - { - stringValue = XmlSchemaDatatype.ConcatenatedToString(parsedValue); - } + string stringValue = parsedValue as string ?? XmlSchemaDatatype.ConcatenatedToString(parsedValue); SendValidationEvent(SR.Sch_ElementValueDataTypeDetailed, new string[] { QNameString(_context.LocalName!, _context.Namespace!), stringValue, GetTypeName(decl), exception.Message }, exception); return null; @@ -1913,10 +1901,7 @@ namespace System.Xml.Schema } else { - if (_IDs == null) - { - _IDs = new Hashtable(); - } + _IDs ??= new Hashtable(); _IDs.Add(name, _context.LocalName); } @@ -1974,10 +1959,7 @@ namespace System.Xml.Schema Error: _attrValid = false; - if (stringValue == null) - { - stringValue = XmlSchemaDatatype.ConcatenatedToString(value); - } + stringValue ??= XmlSchemaDatatype.ConcatenatedToString(value); SendValidationEvent(SR.Sch_AttributeValueDataTypeDetailed, new string[] { attdef.Name.ToString(), stringValue, GetTypeName(decl), exception.Message }, exception); return null; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlValueConverter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlValueConverter.cs index 9a9e08e..7fc4393 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlValueConverter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlValueConverter.cs @@ -236,10 +236,7 @@ namespace System.Xml.Schema { schemaType = schemaType.BaseXmlSchemaType!; } - if (schemaType == null) - { //Did not find any simple type in the parent chain - schemaType = XmlSchemaType.GetBuiltInSimpleType(datatype.TypeCode); - } + schemaType ??= XmlSchemaType.GetBuiltInSimpleType(datatype.TypeCode); //Did not find any simple type in the parent chain Debug.Assert(schemaType.Datatype!.Variety != XmlSchemaDatatypeVariety.List, "schemaType must be list's item type, not list itself"); _schemaType = schemaType; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdBuilder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdBuilder.cs index 85898fa..7d148ec 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdBuilder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdBuilder.cs @@ -125,17 +125,8 @@ namespace System.Xml.Schema _reader = reader; } - public override string? LookupNamespace(string prefix) - { - string? ns = _nsMgr.LookupNamespace(prefix); - - if (ns == null) - { - ns = _reader.LookupNamespace(prefix); - } - - return ns; - } + public override string? LookupNamespace(string prefix) => + _nsMgr.LookupNamespace(prefix) ?? _reader.LookupNamespace(prefix); } ////////////////////////////////////////////////////////////////////////////////////////////// @@ -757,10 +748,7 @@ namespace System.Xml.Schema { if (ns == _schemaNames.NsXmlNs) { - if (_namespaces == null) - { - _namespaces = new List(); - } + _namespaces ??= new List(); _namespaces.Add(new XmlQualifiedName((name == _schemaNames.QnXmlNs.Name) ? string.Empty : name, value)); } else diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdValidator.cs index 65e6798..3e892ab 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdValidator.cs @@ -379,10 +379,7 @@ namespace System.Xml.Schema private SchemaElementDecl? ThoroughGetElementDecl(SchemaElementDecl? elementDecl, XmlQualifiedName xsiType, string? xsiNil) { - if (elementDecl == null) - { - elementDecl = schemaInfo!.GetElementDecl(elementName); - } + elementDecl ??= schemaInfo!.GetElementDecl(elementName); if (elementDecl != null) { if (xsiType.IsEmpty) @@ -762,10 +759,7 @@ namespace System.Xml.Schema // Note: It used to be true that we only called this if _fValidate was true, // but due to the fact that you can now dynamically type somethign as an ID // that is no longer true. - if (_IDs == null) - { - _IDs = new Hashtable(); - } + _IDs ??= new Hashtable(); _IDs.Add(name, node); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerator.cs index d0cfe8c..493a5ca 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerator.cs @@ -140,15 +140,7 @@ namespace System.Xml.Serialization internal LocalBuilder? retLocal; internal Label retLabel; - internal LocalBuilder ReturnLocal - { - get - { - if (retLocal == null) - retLocal = DeclareLocal(_methodBuilder!.ReturnType, "_ret"); - return retLocal; - } - } + internal LocalBuilder ReturnLocal => retLocal ??= DeclareLocal(_methodBuilder!.ReturnType, "_ret"); internal Label ReturnLabel { get { return retLabel; } @@ -556,12 +548,7 @@ namespace System.Xml.Serialization memberType = property.PropertyType; if (property != null) { - MethodInfo? getMethod = property.GetMethod; - - if (getMethod == null) - { - getMethod = GetPropertyMethodFromBaseType(property, true); - } + MethodInfo? getMethod = property.GetMethod ?? GetPropertyMethodFromBaseType(property, true); System.Diagnostics.Debug.Assert(getMethod != null); Call(getMethod); @@ -594,12 +581,7 @@ namespace System.Xml.Serialization memberType = property.PropertyType; if (property != null) { - MethodInfo? getMethod = property.GetMethod; - - if (getMethod == null) - { - getMethod = GetPropertyMethodFromBaseType(property, true); - } + MethodInfo? getMethod = property.GetMethod ?? GetPropertyMethodFromBaseType(property, true); System.Diagnostics.Debug.Assert(getMethod != null); Call(getMethod); @@ -633,12 +615,7 @@ namespace System.Xml.Serialization PropertyInfo property = (PropertyInfo)memberInfo; if (property != null) { - MethodInfo? setMethod = property.SetMethod; - - if (setMethod == null) - { - setMethod = GetPropertyMethodFromBaseType(property, false); - } + MethodInfo? setMethod = property.SetMethod ?? GetPropertyMethodFromBaseType(property, false); System.Diagnostics.Debug.Assert(setMethod != null); Call(setMethod); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compilation.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compilation.cs index bb49980..3870118 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compilation.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compilation.cs @@ -105,14 +105,7 @@ namespace System.Xml.Serialization internal XmlSerializerImplementation Contract { [RequiresUnreferencedCode("calls GetTypeFromAssembly")] - get - { - if (_contract == null) - { - _contract = (XmlSerializerImplementation)Activator.CreateInstance(GetTypeFromAssembly(_assembly!, "XmlSerializerContract"))!; - } - return _contract; - } + get => _contract ??= (XmlSerializerImplementation)Activator.CreateInstance(GetTypeFromAssembly(_assembly!, "XmlSerializerContract"))!; } internal void InitAssemblyMethods(XmlMapping[] xmlMappings) @@ -623,10 +616,7 @@ namespace System.Xml.Serialization reader.Init(xmlReader, events, encodingStyle, this); if (_methods![mapping.Key!].readMethod == null) { - if (_readerMethods == null) - { - _readerMethods = Contract.ReadMethods; - } + _readerMethods ??= Contract.ReadMethods; string? methodName = (string?)_readerMethods[mapping.Key!]; if (methodName == null) { @@ -653,10 +643,7 @@ namespace System.Xml.Serialization writer.Init(xmlWriter, namespaces, encodingStyle, id, this); if (_methods![mapping.Key!].writeMethod == null) { - if (_writerMethods == null) - { - _writerMethods = Contract.WriteMethods; - } + _writerMethods ??= Contract.WriteMethods; string? methodName = (string?)_writerMethods[mapping.Key!]; if (methodName == null) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ImportContext.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ImportContext.cs index 9dd6582..1a09c21 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ImportContext.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ImportContext.cs @@ -29,45 +29,13 @@ namespace System.Xml.Serialization internal ImportContext() : this(null, false) { } - internal SchemaObjectCache Cache - { - get - { - if (_cache == null) - _cache = new SchemaObjectCache(); - return _cache; - } - } + internal SchemaObjectCache Cache => _cache ??= new SchemaObjectCache(); - internal Hashtable Elements - { - get - { - if (_elements == null) - _elements = new Hashtable(); - return _elements; - } - } + internal Hashtable Elements => _elements ??= new Hashtable(); - internal Hashtable Mappings - { - get - { - if (_mappings == null) - _mappings = new Hashtable(); - return _mappings; - } - } + internal Hashtable Mappings => _mappings ??= new Hashtable(); - public CodeIdentifiers TypeIdentifiers - { - get - { - if (_typeIdentifiers == null) - _typeIdentifiers = new CodeIdentifiers(); - return _typeIdentifiers; - } - } + public CodeIdentifiers TypeIdentifiers => _typeIdentifiers ??= new CodeIdentifiers(); public bool ShareTypes { @@ -88,45 +56,13 @@ namespace System.Xml.Serialization private StringCollection? _warnings; // UNDONE remove me soon, this is debug only code internal Hashtable looks = new Hashtable(); - private Hashtable Graph - { - get - { - if (_graph == null) - _graph = new Hashtable(); - return _graph; - } - } + private Hashtable Graph => _graph ??= new Hashtable(); - private Hashtable Hash - { - get - { - if (_hash == null) - _hash = new Hashtable(); - return _hash; - } - } + private Hashtable Hash => _hash ??= new Hashtable(); - private Hashtable ObjectCache - { - get - { - if (_objectCache == null) - _objectCache = new Hashtable(); - return _objectCache; - } - } + private Hashtable ObjectCache => _objectCache ??= new Hashtable(); - internal StringCollection Warnings - { - get - { - if (_warnings == null) - _warnings = new StringCollection(); - return _warnings; - } - } + internal StringCollection Warnings => _warnings ??= new StringCollection(); internal XmlSchemaObject? AddItem(XmlSchemaObject? item, XmlQualifiedName? qname, XmlSchemas schemas) { @@ -170,8 +106,8 @@ namespace System.Xml.Serialization return true; if (o1.GetType() != o2.GetType()) return false; - if (Hash[o1] == null) - Hash[o1] = GetHash(o1); + + Hash[o1] ??= GetHash(o1); int hash1 = (int)Hash[o1]!; int hash2 = GetHash(o2); if (hash1 != hash2) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Mappings.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Mappings.cs index 6b09354..20db540 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Mappings.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Mappings.cs @@ -514,24 +514,8 @@ namespace System.Xml.Serialization get { return _baseMapping != null && Members != null; } } - internal NameTable LocalElements - { - get - { - if (_elements == null) - _elements = new NameTable(); - return _elements; - } - } - internal NameTable LocalAttributes - { - get - { - if (_attributes == null) - _attributes = new NameTable(); - return _attributes; - } - } + internal NameTable LocalElements => _elements ??= new NameTable(); + internal NameTable LocalAttributes => _attributes ??= new NameTable(); object? INameScope.this[string? name, string? ns] { get @@ -593,13 +577,8 @@ namespace System.Xml.Serialization internal CodeIdentifiers Scope { - get - { - if (_scope == null) - _scope = new CodeIdentifiers(); - return _scope; - } - set { _scope = value; } + get => _scope ??= new CodeIdentifiers(); + set => _scope = value; } internal MemberMapping? FindDeclaringMapping(MemberMapping member, out StructMapping? declaringMapping, string? parent) @@ -1295,8 +1274,7 @@ namespace System.Xml.Serialization if (_getSchemaMethod != null) { // get the type info - if (_schemas == null) - _schemas = new XmlSchemaSet(); + _schemas ??= new XmlSchemaSet(); object? typeInfo = _getSchemaMethod.Invoke(null, new object[] { _schemas }); _xsiType = XmlQualifiedName.Empty; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationReader.cs index 08e4c7d..8208a68 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationReader.cs @@ -585,10 +585,7 @@ namespace System.Xml.Serialization } else { - if (collection == null) - { - collection = ReflectionCreateObject(collectionType)!; - } + collection ??= ReflectionCreateObject(collectionType)!; AddObjectsIntoTargetCollection(collection, collectionMember, collectionType); } @@ -1668,10 +1665,7 @@ namespace System.Xml.Serialization { member.Source = (item) => { - if (member.Collection == null) - { - member.Collection = new CollectionMember(); - } + member.Collection ??= new CollectionMember(); member.Collection.Add(item); }; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs index 1d7a207..3fbfc26 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs @@ -212,9 +212,13 @@ namespace System.Xml.Serialization { anyCount++; if (element.Name != null && element.Name.Length > 0) + { namedAnys.Add(element); - else if (unnamedAny == null) - unnamedAny = element; + } + else + { + unnamedAny ??= element; + } } else if (choice != null) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaImporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaImporter.cs index ef7a31f..65de47c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaImporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaImporter.cs @@ -44,15 +44,7 @@ namespace System.Xml.Serialization Schemas.SetCache(Context.Cache, Context.ShareTypes); } - internal ImportContext Context - { - get - { - if (_context == null) - _context = new ImportContext(); - return _context; - } - } + internal ImportContext Context => _context ??= new ImportContext(); internal Hashtable ImportedElements { @@ -69,45 +61,13 @@ namespace System.Xml.Serialization get { return Context.TypeIdentifiers; } } - internal XmlSchemas Schemas - { - get - { - if (_schemas == null) - _schemas = new XmlSchemas(); - return _schemas; - } - } + internal XmlSchemas Schemas => _schemas ??= new XmlSchemas(); - internal TypeScope Scope - { - get - { - if (_scope == null) - _scope = new TypeScope(); - return _scope; - } - } + internal TypeScope Scope => _scope ??= new TypeScope(); - internal NameTable GroupsInUse - { - get - { - if (_groupsInUse == null) - _groupsInUse = new NameTable(); - return _groupsInUse; - } - } + internal NameTable GroupsInUse => _groupsInUse ??= new NameTable(); - internal NameTable TypesInUse - { - get - { - if (_typesInUse == null) - _typesInUse = new NameTable(); - return _typesInUse; - } - } + internal NameTable TypesInUse => _typesInUse ??= new NameTable(); internal CodeGenerationOptions Options { @@ -160,12 +120,7 @@ namespace System.Xml.Serialization } [RequiresUnreferencedCode("calls CreateRootMapping")] - internal StructMapping GetRootMapping() - { - if (_root == null) - _root = CreateRootMapping(); - return _root; - } + internal StructMapping GetRootMapping() => _root ??= CreateRootMapping(); [RequiresUnreferencedCode("calls GetRootMapping")] internal StructMapping ImportRootMapping() diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapReflectionImporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapReflectionImporter.cs index 286a8ba..ad97d7e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapReflectionImporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapReflectionImporter.cs @@ -38,12 +38,8 @@ namespace System.Xml.Serialization public SoapReflectionImporter(SoapAttributeOverrides? attributeOverrides, string? defaultNamespace) { - if (defaultNamespace == null) - defaultNamespace = string.Empty; - if (attributeOverrides == null) - attributeOverrides = new SoapAttributeOverrides(); - _attributeOverrides = attributeOverrides; - _defaultNs = defaultNamespace; + _defaultNs = defaultNamespace ?? string.Empty; + _attributeOverrides = attributeOverrides ?? new SoapAttributeOverrides(); _typeScope = new TypeScope(); _modelScope = new ModelScope(_typeScope); } @@ -205,9 +201,9 @@ namespace System.Xml.Serialization typeNs = baseAttributes.SoapType.Namespace; TypeDesc valueTypeDesc = string.IsNullOrEmpty(dataType) ? model.TypeDesc.BaseTypeDesc! : TypeScope.GetTypeDesc(dataType, XmlSchema.Namespace)!; string xsdTypeName = string.IsNullOrEmpty(dataType) ? model.TypeDesc.BaseTypeDesc!.Name : dataType; - TypeMapping? baseMapping = GetTypeMapping(xsdTypeName, typeNs, valueTypeDesc); - if (baseMapping == null) - baseMapping = ImportTypeMapping(_modelScope.GetTypeModel(baseTypeDesc.Type!), dataType, limiter); + TypeMapping baseMapping = + GetTypeMapping(xsdTypeName, typeNs, valueTypeDesc) ?? + ImportTypeMapping(_modelScope.GetTypeModel(baseTypeDesc.Type!), dataType, limiter); return CreateNullableMapping(baseMapping, model.TypeDesc.Type!); } else @@ -408,7 +404,7 @@ namespace System.Xml.Serialization members.Add(member); } mapping.Members = members.ToArray(); - if (mapping.BaseMapping == null) mapping.BaseMapping = GetRootMapping(); + mapping.BaseMapping ??= GetRootMapping(); IncludeTypes(model.Type, limiter); return true; @@ -592,8 +588,7 @@ namespace System.Xml.Serialization if (a.SoapIgnore) return null; if ((a.GetSoapFlags() & ~SoapAttributeFlags.Enum) != 0) throw new InvalidOperationException(SR.XmlInvalidEnumAttribute); - if (a.SoapEnum == null) - a.SoapEnum = new SoapEnumAttribute(); + a.SoapEnum ??= new SoapEnumAttribute(); ConstantMapping constant = new ConstantMapping(); constant.XmlName = a.SoapEnum.Name.Length == 0 ? model.Name : a.SoapEnum.Name; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Types.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Types.cs index c1f868c..e7b6c39 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Types.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Types.cs @@ -166,17 +166,8 @@ namespace System.Xml.Serialization get { return _fullName; } } - internal string CSharpName - { - get - { - if (_cSharpName == null) - { - _cSharpName = _type == null ? CodeIdentifier.GetCSharpName(_fullName) : CodeIdentifier.GetCSharpName(_type); - } - return _cSharpName; - } - } + internal string CSharpName => + _cSharpName ??= _type == null ? CodeIdentifier.GetCSharpName(_fullName) : CodeIdentifier.GetCSharpName(_type); internal XmlSchemaType? DataType { @@ -419,12 +410,7 @@ namespace System.Xml.Serialization get { return _weight; } } - internal TypeDesc CreateArrayTypeDesc() - { - if (_arrayTypeDesc == null) - _arrayTypeDesc = new TypeDesc(null, $"{_name}[]", $"{_fullName}[]", TypeKind.Array, null, TypeFlags.Reference | (_flags & TypeFlags.UseReflection), this); - return _arrayTypeDesc; - } + internal TypeDesc CreateArrayTypeDesc() => _arrayTypeDesc ??= new TypeDesc(null, $"{_name}[]", $"{_fullName}[]", TypeKind.Array, null, TypeFlags.Reference | (_flags & TypeFlags.UseReflection), this); internal TypeDesc? BaseTypeDesc { @@ -735,19 +721,15 @@ namespace System.Xml.Serialization { throw new InvalidOperationException(SR.Format(SR.XmlUnsupportedOpenGenericType, type)); } - TypeDesc? typeDesc = (TypeDesc?)s_primitiveTypes[type]; - if (typeDesc == null) - { - typeDesc = (TypeDesc?)_typeDescs[type]; - if (typeDesc == null) - { - typeDesc = ImportTypeDesc(type, source, directReference); - } - } + + TypeDesc typeDesc = + (TypeDesc?)s_primitiveTypes[type] ?? + (TypeDesc?)_typeDescs[type] ?? + ImportTypeDesc(type, source, directReference); + if (throwOnError) typeDesc.CheckSupported(); - return typeDesc; } @@ -824,10 +806,7 @@ namespace System.Xml.Serialization { kind = TypeKind.Enum; flags |= TypeFlags.Unsupported; - if (exception == null) - { - exception = new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, type.FullName)); - } + exception ??= new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, type.FullName)); } else if (type == typeof(void)) { @@ -845,10 +824,7 @@ namespace System.Xml.Serialization if (type.GetArrayRank() > 1) { flags |= TypeFlags.Unsupported; - if (exception == null) - { - exception = new NotSupportedException(SR.Format(SR.XmlUnsupportedRank, type.FullName)); - } + exception ??= new NotSupportedException(SR.Format(SR.XmlUnsupportedRank, type.FullName)); } arrayElementType = type.GetElementType(); flags |= TypeFlags.HasDefaultConstructor; @@ -867,10 +843,7 @@ namespace System.Xml.Serialization { kind = TypeKind.Primitive; flags |= TypeFlags.Unsupported; - if (exception == null) - { - exception = new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, type.FullName)); - } + exception ??= new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, type.FullName)); } else if (type.IsEnum) { @@ -1176,10 +1149,7 @@ namespace System.Xml.Serialization { if (ShouldBeReplaced(pair.Value, structMapping.TypeDesc!.Type!, out replacedInfo)) { - if (replaceList == null) - { - replaceList = new Dictionary(); - } + replaceList ??= new Dictionary(); replaceList.Add(pair.Key, replacedInfo); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMapping.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMapping.cs index 771dfb7..efd4335 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMapping.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMapping.cs @@ -113,10 +113,7 @@ namespace System.Xml.Serialization internal static string GenerateKey(Type type, XmlRootAttribute? root, string? ns) { - if (root == null) - { - root = (XmlRootAttribute?)XmlAttributes.GetAttr(type, typeof(XmlRootAttribute)); - } + root ??= (XmlRootAttribute?)XmlAttributes.GetAttr(type, typeof(XmlRootAttribute)); return $"{type.FullName}:{(root == null ? string.Empty : root.GetKey())}:{ns ?? string.Empty}"; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs index 8ff088b..13f679a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs @@ -74,12 +74,8 @@ namespace System.Xml.Serialization /// public XmlReflectionImporter(XmlAttributeOverrides? attributeOverrides, string? defaultNamespace) { - if (defaultNamespace == null) - defaultNamespace = string.Empty; - if (attributeOverrides == null) - attributeOverrides = new XmlAttributeOverrides(); - _attributeOverrides = attributeOverrides; - _defaultNs = defaultNamespace; + _defaultNs = defaultNamespace ?? string.Empty; + _attributeOverrides = attributeOverrides ?? new XmlAttributeOverrides(); _typeScope = new TypeScope(); _modelScope = new ModelScope(_typeScope); } @@ -260,11 +256,8 @@ namespace System.Xml.Serialization { XmlAttributes a = GetAttributes(model.Type, true); - if (root == null) - root = a.XmlRoot; - string? ns = root?.Namespace; - if (ns == null) ns = defaultNamespace; - if (ns == null) ns = _defaultNs; + root ??= a.XmlRoot; + string ns = root?.Namespace ?? defaultNamespace ?? _defaultNs; _arrayNestingLevel = -1; _savedArrayItemAttributes = null; @@ -409,8 +402,7 @@ namespace System.Xml.Serialization } } - if (a == null) - a = GetAttributes(model.Type, false); + a ??= GetAttributes(model.Type, false); if ((a.XmlFlags & ~(XmlAttributeFlags.Type | XmlAttributeFlags.Root)) != 0) throw new InvalidOperationException(SR.Format(SR.XmlInvalidTypeAttributes, model.Type.FullName)); @@ -439,9 +431,9 @@ namespace System.Xml.Serialization { TypeDesc valueTypeDesc = string.IsNullOrEmpty(dataType) ? model.TypeDesc.BaseTypeDesc! : TypeScope.GetTypeDesc(dataType, XmlSchema.Namespace)!; string? xsdTypeName = valueTypeDesc.DataType == null ? valueTypeDesc.Name : valueTypeDesc.DataType.Name; - TypeMapping? baseMapping = GetTypeMapping(xsdTypeName, ns, valueTypeDesc, _types, null); - if (baseMapping == null) - baseMapping = ImportTypeMapping(_modelScope.GetTypeModel(model.TypeDesc.BaseTypeDesc!.Type!), ns, context, dataType, null, repeats, openModel, limiter); + TypeMapping baseMapping = + GetTypeMapping(xsdTypeName, ns, valueTypeDesc, _types, null) ?? + ImportTypeMapping(_modelScope.GetTypeModel(model.TypeDesc.BaseTypeDesc!.Type!), ns, context, dataType, null, repeats, openModel, limiter); return CreateNullableMapping(baseMapping, model.TypeDesc.Type!); } else @@ -501,8 +493,7 @@ namespace System.Xml.Serialization [RequiresUnreferencedCode("calls IncludeTypes")] private SpecialMapping ImportSpecialMapping(Type type, TypeDesc typeDesc, string? ns, ImportContext context, RecursionLimiter limiter) { - if (_specials == null) - _specials = new Hashtable(); + _specials ??= new Hashtable(); SpecialMapping? mapping = (SpecialMapping?)_specials[type]; if (mapping != null) { @@ -525,8 +516,7 @@ namespace System.Xml.Serialization XmlQualifiedName? qname = serializableMapping.XsiType; if (qname != null && !qname.IsEmpty) { - if (_serializables == null) - _serializables = new NameTable(); + _serializables ??= new NameTable(); SerializableMapping? existingMapping = (SerializableMapping?)_serializables[qname]; if (existingMapping != null) { @@ -721,8 +711,7 @@ namespace System.Xml.Serialization private StructMapping ImportStructLikeMapping(StructModel model, string? ns, bool openModel, XmlAttributes? a, RecursionLimiter limiter) { if (model.TypeDesc.Kind == TypeKind.Root) return GetRootMapping(); - if (a == null) - a = GetAttributes(model.Type, false); + a ??= GetAttributes(model.Type, false); string? typeNs = ns; if (a.XmlType != null && a.XmlType.Namespace != null) @@ -918,7 +907,7 @@ namespace System.Xml.Serialization } mapping.Members = members.ToArray(); - if (mapping.BaseMapping == null) mapping.BaseMapping = GetRootMapping(); + mapping.BaseMapping ??= GetRootMapping(); if (mapping.XmlnsMember != null && mapping.BaseMapping.HasXmlnsMember) throw new InvalidOperationException(SR.Format(SR.XmlMultipleXmlns, model.Type.FullName)); @@ -1053,14 +1042,12 @@ namespace System.Xml.Serialization name = $"Choice{(_choiceNum++)}"; } - if (name == null) - name = "Any"; + name ??= "Any"; if (element != null) ns = element.Namespace; - if (ns == null) - ns = defaultNs; + ns ??= defaultNs; string uniqueName = name = generateTypeName ? $"ArrayOf{CodeIdentifier.MakePascal(name)}" : name; int i = 1; @@ -1089,8 +1076,7 @@ namespace System.Xml.Serialization ArrayMapping mapping = new ArrayMapping(); mapping.TypeDesc = model.TypeDesc; - if (_savedArrayItemAttributes == null) - _savedArrayItemAttributes = new XmlArrayItemAttributes(); + _savedArrayItemAttributes ??= new XmlArrayItemAttributes(); if (CountAtLevel(_savedArrayItemAttributes, _arrayNestingLevel) == 0) _savedArrayItemAttributes.Add(CreateArrayItemAttribute(_typeScope.GetTypeDesc(model.Element.Type), _arrayNestingLevel)); CreateArrayElementsFromAttributes(mapping, _savedArrayItemAttributes, model.Element.Type, _savedArrayNamespace ?? ns, limiter); @@ -1228,8 +1214,7 @@ namespace System.Xml.Serialization if (a.XmlIgnore) return null; if ((a.XmlFlags & ~XmlAttributeFlags.Enum) != 0) throw new InvalidOperationException(SR.XmlInvalidConstantAttribute); - if (a.XmlEnum == null) - a.XmlEnum = new XmlEnumAttribute(); + a.XmlEnum ??= new XmlEnumAttribute(); ConstantMapping constant = new ConstantMapping(); constant.XmlName = a.XmlEnum.Name ?? model.Name; @@ -1603,8 +1588,7 @@ namespace System.Xml.Serialization attribute.Any = (a.XmlAnyAttribute != null); if (attribute.Form == XmlSchemaForm.Qualified && attribute.Namespace != ns) { - if (_xsdAttributes == null) - _xsdAttributes = new NameTable(); + _xsdAttributes ??= new NameTable(); attribute = (AttributeAccessor)ReconcileAccessor(attribute, _xsdAttributes); } accessor.Attribute = attribute; @@ -1727,8 +1711,7 @@ namespace System.Xml.Serialization } TypeDesc arrayElementTypeDesc = _typeScope.GetTypeDesc(arrayElementType); - if (a.XmlArray == null) - a.XmlArray = CreateArrayAttribute(accessor.TypeDesc); + a.XmlArray ??= CreateArrayAttribute(accessor.TypeDesc); if (CountAtLevel(a.XmlArrayItems, _arrayNestingLevel) == 0) a.XmlArrayItems.Add(CreateArrayItemAttribute(arrayElementTypeDesc, _arrayNestingLevel)); ElementAccessor arrayElement = new ElementAccessor(); @@ -1783,8 +1766,7 @@ namespace System.Xml.Serialization attribute.Any = a.XmlAnyAttribute != null; if (attribute.Form == XmlSchemaForm.Qualified && attribute.Namespace != ns) { - if (_xsdAttributes == null) - _xsdAttributes = new NameTable(); + _xsdAttributes ??= new NameTable(); attribute = (AttributeAccessor)ReconcileAccessor(attribute, _xsdAttributes); } accessor.Attribute = attribute; @@ -2358,16 +2340,6 @@ namespace System.Xml.Serialization internal bool IsExceededLimit { get { return _depth > _maxDepth; } } internal int Depth { get { return _depth; } set { _depth = value; } } - internal WorkItems DeferredWorkItems - { - get - { - if (_deferredWorkItems == null) - { - _deferredWorkItems = new WorkItems(); - } - return _deferredWorkItems; - } - } + internal WorkItems DeferredWorkItems => _deferredWorkItems ??= new WorkItems(); } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs index cef6c76..682c011 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs @@ -279,11 +279,7 @@ namespace System.Xml.Serialization private void AddSchemaItem(XmlSchemaObject item, string? ns, string? referencingNs) { - XmlSchema? schema = _schemas[ns]; - if (schema == null) - { - schema = AddSchema(ns); - } + XmlSchema schema = _schemas[ns] ?? AddSchema(ns); if (item is XmlSchemaElement e) { @@ -305,11 +301,7 @@ namespace System.Xml.Serialization { if (referencingNs == null) return; if (NamespacesEqual(ns, referencingNs)) return; - XmlSchema? schema = _schemas[referencingNs]; - if (schema == null) - { - schema = AddSchema(referencingNs); - } + XmlSchema schema = _schemas[referencingNs] ?? AddSchema(referencingNs); if (FindImport(schema, ns) == null) { XmlSchemaImport import = new XmlSchemaImport(); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs index f619247..7a1a454 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs @@ -798,8 +798,9 @@ namespace System.Xml.Serialization break; typeDescs[i] = ((ElementAccessor)enumerator.Current).Mapping!.TypeDesc!; } - member.TypeDesc = TypeDesc.FindCommonBaseTypeDesc(typeDescs); - if (member.TypeDesc == null) member.TypeDesc = Scope.GetTypeDesc(typeof(object)); + member.TypeDesc = + TypeDesc.FindCommonBaseTypeDesc(typeDescs) ?? + Scope.GetTypeDesc(typeof(object)); } if (groupRepeats) @@ -808,10 +809,7 @@ namespace System.Xml.Serialization if (membersScope != null) { member.Name = membersScope.AddUnique(groupRepeats ? "Items" : "Item", member); - if (members != null) - { - members.Add(member.Name, member); - } + members?.Add(member.Name, member); } if (duplicateTypes) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs index 154d804..50eecb8 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs @@ -55,35 +55,11 @@ namespace System.Xml.Serialization return (IList)SchemaSet.Schemas(ns); } - internal SchemaObjectCache Cache - { - get - { - if (_cache == null) - _cache = new SchemaObjectCache(); - return _cache; - } - } + internal SchemaObjectCache Cache => _cache ??= new SchemaObjectCache(); - internal Hashtable MergedSchemas - { - get - { - if (_mergedSchemas == null) - _mergedSchemas = new Hashtable(); - return _mergedSchemas; - } - } + internal Hashtable MergedSchemas => _mergedSchemas ??= new Hashtable(); - internal Hashtable References - { - get - { - if (_references == null) - _references = new Hashtable(); - return _references; - } - } + internal Hashtable References => _references ??= new Hashtable(); internal XmlSchemaSet SchemaSet { @@ -737,29 +713,11 @@ namespace System.Xml.Serialization return; } - internal static XmlSchema XsdSchema - { - get - { - if (s_xsd == null) - { - s_xsd = CreateFakeXsdSchema(XmlSchema.Namespace, "schema"); - } - return s_xsd; - } - } + internal static XmlSchema XsdSchema => + s_xsd ??= CreateFakeXsdSchema(XmlSchema.Namespace, "schema"); - internal static XmlSchema XmlSchema - { - get - { - if (s_xml == null) - { - s_xml = XmlSchema.Read(new StringReader(xmlSchema), null)!; - } - return s_xml; - } - } + internal static XmlSchema XmlSchema => + s_xml ??= XmlSchema.Read(new StringReader(xmlSchema), null)!; private static XmlSchema CreateFakeXsdSchema(string ns, string name) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs index eeab379..82b930a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs @@ -827,15 +827,12 @@ namespace System.Xml.Serialization protected bool GetNullAttr() { - string? isNull = _r.GetAttribute(_nilID, _instanceNsID); - if (isNull == null) - isNull = _r.GetAttribute(_nullID, _instanceNsID); - if (isNull == null) - { - isNull = _r.GetAttribute(_nullID, _instanceNs2000ID); - if (isNull == null) - isNull = _r.GetAttribute(_nullID, _instanceNs1999ID); - } + string? isNull = + _r.GetAttribute(_nilID, _instanceNsID) ?? + _r.GetAttribute(_nullID, _instanceNsID) ?? + _r.GetAttribute(_nullID, _instanceNs2000ID) ?? + _r.GetAttribute(_nullID, _instanceNs1999ID); + if (isNull == null || !XmlConvert.ToBoolean(isNull)) return false; return true; } @@ -1446,14 +1443,13 @@ namespace System.Xml.Serialization { if (id == null) { - if (_targetsWithoutIds == null) - _targetsWithoutIds = new ArrayList(); + _targetsWithoutIds ??= new ArrayList(); if (o != null) _targetsWithoutIds.Add(o); } else { - if (_targets == null) _targets = new Hashtable(); + _targets ??= new Hashtable(); if (!_targets.Contains(id)) _targets.Add(id, o); } @@ -1461,13 +1457,13 @@ namespace System.Xml.Serialization protected void AddFixup(Fixup? fixup) { - if (_fixups == null) _fixups = new ArrayList(); + _fixups ??= new ArrayList(); _fixups.Add(fixup); } protected void AddFixup(CollectionFixup? fixup) { - if (_collectionFixups == null) _collectionFixups = new ArrayList(); + _collectionFixups ??= new ArrayList(); _collectionFixups.Add(fixup); } @@ -1485,7 +1481,7 @@ namespace System.Xml.Serialization protected void Referenced(object? o) { if (o == null) return; - if (_referencedTargets == null) _referencedTargets = new Hashtable(); + _referencedTargets ??= new Hashtable(); _referencedTargets[o] = o; } @@ -2040,17 +2036,7 @@ namespace System.Xml.Serialization private int _nextCreateMethodNumber; private int _nextIdNumber; - internal Hashtable Enums - { - get - { - if (_enums == null) - { - _enums = new Hashtable(); - } - return _enums; - } - } + internal Hashtable Enums => _enums ??= new Hashtable(); private sealed class CreateCollectionInfo { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs index 181daac..a11fd84 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs @@ -24,17 +24,7 @@ namespace System.Xml.Serialization private Dictionary? _enums; private int _nextIdNumber; - internal Dictionary Enums - { - get - { - if (_enums == null) - { - _enums = new Dictionary(); - } - return _enums; - } - } + internal Dictionary Enums => _enums ??= new Dictionary(); private sealed class Member { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs index 00b1d1f..31f7d73 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs @@ -1355,7 +1355,7 @@ namespace System.Xml.Serialization [RequiresUnreferencedCode("calls WriteArray")] private void WriteReferencedElement(string? name, string? ns, object o, Type? ambientType) { - if (name == null) name = string.Empty; + name ??= string.Empty; Type t = o.GetType(); if (t.IsArray || typeof(IEnumerable).IsAssignableFrom(t)) { @@ -3645,9 +3645,13 @@ namespace System.Xml.Serialization { anyCount++; if (element.Name != null && element.Name.Length > 0) + { namedAnys.Add(element); - else if (unnamedAny == null) - unnamedAny = element; + } + else + { + unnamedAny ??= element; + } } else if (choice != null) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs index df96500..1ff8e3a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs @@ -1612,9 +1612,13 @@ namespace System.Xml.Serialization { anyCount++; if (element.Name != null && element.Name.Length > 0) + { namedAnys.Add(element); - else if (unnamedAny == null) - unnamedAny = element; + } + else + { + unnamedAny ??= element; + } } else if (choice != null) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs index dc04841..6331b41 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs @@ -149,10 +149,7 @@ namespace System.Xml.Serialization XmlSerializerNamespaces nss = new XmlSerializerNamespaces(); nss.AddInternal("xsi", XmlSchema.InstanceNamespace); nss.AddInternal("xsd", XmlSchema.Namespace); - if (s_defaultNamespaces == null) - { - s_defaultNamespaces = nss; - } + s_defaultNamespaces ??= nss; } return s_defaultNamespaces; } @@ -260,10 +257,8 @@ namespace System.Xml.Serialization s_cache.Add(defaultNamespace, type, _tempAssembly); } } - if (_mapping == null) - { - _mapping = XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace); - } + + _mapping ??= XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace); } [RequiresUnreferencedCode(TrimSerializationWarning)] diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerNamespaces.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerNamespaces.cs index c514bd7..79bc2c67 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerNamespaces.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerNamespaces.cs @@ -100,15 +100,7 @@ namespace System.Xml.Serialization internal Dictionary.ValueCollection Namespaces => NamespacesInternal.Values; - private Dictionary NamespacesInternal - { - get - { - if (_namespaces == null) - _namespaces = new Dictionary(); - return _namespaces; - } - } + private Dictionary NamespacesInternal => _namespaces ??= new Dictionary(); internal ArrayList? NamespaceList { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/CompiledXPathExpr.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/CompiledXPathExpr.cs index 59de59e..77693c6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/CompiledXPathExpr.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/CompiledXPathExpr.cs @@ -96,10 +96,7 @@ namespace MS.Internal.Xml.XPath XsltContext? xsltContext = nsResolver as XsltContext; if (xsltContext == null) { - if (nsResolver == null) - { - nsResolver = new XmlNamespaceManager(new NameTable()); - } + nsResolver ??= new XmlNamespaceManager(new NameTable()); xsltContext = new UndefinedXsltContext(nsResolver); } _query.SetXsltContext(xsltContext); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/FollSiblingQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/FollSiblingQuery.cs index e66266c..4f847ab 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/FollSiblingQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/FollSiblingQuery.cs @@ -68,10 +68,7 @@ namespace MS.Internal.Xml.XPath { if (currentNode == null) { - if (_nextInput == null) - { - _nextInput = FetchInput(); // This can happen at the beginning and at the end - } + _nextInput ??= FetchInput(); // This can happen at the beginning and at the end if (_elementStk.Count == 0) { if (_nextInput == null) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/QueryBuilder.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/QueryBuilder.cs index e9de690..a38aad8 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/QueryBuilder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/QueryBuilder.cs @@ -269,10 +269,7 @@ namespace MS.Internal.Xml.XPath { qyInput = ((DocumentOrderQuery)qyInput).input; } - if (_firstInput == null) - { - _firstInput = qyInput as BaseAxisQuery; - } + _firstInput ??= qyInput as BaseAxisQuery; bool merge = (qyInput.Properties & QueryProps.Merge) != 0; bool reverse = (qyInput.Properties & QueryProps.Reverse) != 0; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathDocument.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathDocument.cs index 62458a0..b32e858 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathDocument.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathDocument.cs @@ -380,8 +380,7 @@ namespace System.Xml.XPath { Debug.Assert(pageElem[idxElem].NodeType == XPathNodeType.Element && pageNmsp[idxNmsp].NodeType == XPathNodeType.Namespace); - if (_mapNmsp == null) - _mapNmsp = new Dictionary(); + _mapNmsp ??= new Dictionary(); _mapNmsp.Add(new XPathNodeRef(pageElem, idxElem), new XPathNodeRef(pageNmsp, idxNmsp)); } @@ -413,8 +412,7 @@ namespace System.Xml.XPath /// internal void AddIdElement(string id, XPathNode[] pageElem, int idxElem) { - if (_idValueMap == null) - _idValueMap = new Dictionary(); + _idValueMap ??= new Dictionary(); if (!_idValueMap.ContainsKey(id)) _idValueMap.Add(id, new XPathNodeRef(pageElem, idxElem)); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathException.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathException.cs index c22ec80..bca6862 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathException.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathException.cs @@ -104,14 +104,14 @@ namespace System.Xml.XPath try { string message = args == null ? res : string.Format(res, args); - if (message == null) - message = $"UNKNOWN({res})"; - return message; - } - catch (MissingManifestResourceException) - { - return $"UNKNOWN({res})"; + if (message != null) + { + return message; + } } + catch (MissingManifestResourceException) { } + + return $"UNKNOWN({res})"; } public override string Message diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigator.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigator.cs index 861960a..8e995b3 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigator.cs @@ -78,11 +78,7 @@ namespace System.Xml.XPath { if (schemaInfo.Validity == XmlSchemaValidity.Valid) { - schemaType = schemaInfo.MemberType; - if (schemaType == null) - { - schemaType = schemaInfo.SchemaType; - } + schemaType = schemaInfo.MemberType ?? schemaInfo.SchemaType; if (schemaType != null) { datatype = schemaType.Datatype; @@ -136,10 +132,7 @@ namespace System.Xml.XPath } } } - if (value == null) - { - value = XmlUntypedConverter.Untyped.ToString(typedValue, this); - } + value ??= XmlUntypedConverter.Untyped.ToString(typedValue, this); SetValue(value); } @@ -154,11 +147,7 @@ namespace System.Xml.XPath { if (schemaInfo.Validity == XmlSchemaValidity.Valid) { - schemaType = schemaInfo.MemberType; - if (schemaType == null) - { - schemaType = schemaInfo.SchemaType; - } + schemaType = schemaInfo.MemberType ?? schemaInfo.SchemaType; if (schemaType != null) { datatype = schemaType.Datatype; @@ -196,11 +185,7 @@ namespace System.Xml.XPath { if (schemaInfo.Validity == XmlSchemaValidity.Valid) { - schemaType = schemaInfo.MemberType; - if (schemaType == null) - { - schemaType = schemaInfo.SchemaType; - } + schemaType = schemaInfo.MemberType ?? schemaInfo.SchemaType; if (schemaType != null) { return schemaType.ValueConverter.ToBoolean(Value); @@ -234,11 +219,7 @@ namespace System.Xml.XPath { if (schemaInfo.Validity == XmlSchemaValidity.Valid) { - schemaType = schemaInfo.MemberType; - if (schemaType == null) - { - schemaType = schemaInfo.SchemaType; - } + schemaType = schemaInfo.MemberType ?? schemaInfo.SchemaType; if (schemaType != null) { return schemaType.ValueConverter.ToDateTime(Value); @@ -272,11 +253,7 @@ namespace System.Xml.XPath { if (schemaInfo.Validity == XmlSchemaValidity.Valid) { - schemaType = schemaInfo.MemberType; - if (schemaType == null) - { - schemaType = schemaInfo.SchemaType; - } + schemaType = schemaInfo.MemberType ?? schemaInfo.SchemaType; if (schemaType != null) { return schemaType.ValueConverter.ToDouble(Value); @@ -310,11 +287,7 @@ namespace System.Xml.XPath { if (schemaInfo.Validity == XmlSchemaValidity.Valid) { - schemaType = schemaInfo.MemberType; - if (schemaType == null) - { - schemaType = schemaInfo.SchemaType; - } + schemaType = schemaInfo.MemberType ?? schemaInfo.SchemaType; if (schemaType != null) { return schemaType.ValueConverter.ToInt32(Value); @@ -348,11 +321,7 @@ namespace System.Xml.XPath { if (schemaInfo.Validity == XmlSchemaValidity.Valid) { - schemaType = schemaInfo.MemberType; - if (schemaType == null) - { - schemaType = schemaInfo.SchemaType; - } + schemaType = schemaInfo.MemberType ?? schemaInfo.SchemaType; if (schemaType != null) { return schemaType.ValueConverter.ToInt64(Value); @@ -388,11 +357,7 @@ namespace System.Xml.XPath { if (schemaInfo.Validity == XmlSchemaValidity.Valid) { - schemaType = schemaInfo.MemberType; - if (schemaType == null) - { - schemaType = schemaInfo.SchemaType; - } + schemaType = schemaInfo.MemberType ?? schemaInfo.SchemaType; if (schemaType != null) { return schemaType.ValueConverter.ChangeType(Value, returnType, nsResolver); @@ -1223,10 +1188,7 @@ namespace System.Xml.XPath Query query = Query.Clone(cexpr.QueryTree); query.Reset(); - if (context == null) - { - context = new XPathSingletonIterator(this.Clone(), /*moved:*/true); - } + context ??= new XPathSingletonIterator(this.Clone(), moved: true); object result = query.Evaluate(context); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigatorReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigatorReader.cs index 03c1a02..3f07b88 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigatorReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigatorReader.cs @@ -1148,15 +1148,7 @@ namespace System.Xml.XPath { } - public static XmlEmptyNavigator Singleton - { - get - { - if (XmlEmptyNavigator.s_singleton == null) - XmlEmptyNavigator.s_singleton = new XmlEmptyNavigator(); - return XmlEmptyNavigator.s_singleton; - } - } + public static XmlEmptyNavigator Singleton => XmlEmptyNavigator.s_singleton ??= new XmlEmptyNavigator(); //----------------------------------------------- // XmlReader diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlComplianceUtil.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlComplianceUtil.cs index 569faff..7af21f8e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlComplianceUtil.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlComplianceUtil.cs @@ -59,10 +59,7 @@ namespace System.Xml } if (j > i + 1 || value[i] != 0x20) { - if (norValue == null) - { - norValue = new StringBuilder(len); - } + norValue ??= new StringBuilder(len); norValue.Append(value, startPos, i - startPos); norValue.Append((char)0x20); startPos = j; @@ -118,10 +115,7 @@ namespace System.Xml continue; } - if (norValue == null) - { - norValue = new StringBuilder(len); - } + norValue ??= new StringBuilder(len); if (startPos < i) { norValue.Append(value, startPos, i - startPos); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs index 4f5b3fb..e24e909 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs @@ -236,10 +236,7 @@ namespace System.Xml (!local && !XmlCharType.IsNameCharXml4e(name[position])) || (matchPos == position)) { - if (bufBld == null) - { - bufBld = new StringBuilder(length + 20); - } + bufBld ??= new StringBuilder(length + 20); if (matchPos == position) if (en!.MoveNext()) { @@ -1513,10 +1510,7 @@ namespace System.Xml char ch = value[i]; if ((int)ch < 0x20 || ch == '"') { - if (sb == null) - { - sb = new StringBuilder(value.Length + 4); - } + sb ??= new StringBuilder(value.Length + 4); if (i - start > 0) { sb.Append(value, start, i - start); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/GenerateHelper.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/GenerateHelper.cs index ced264a..d510249 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/GenerateHelper.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/GenerateHelper.cs @@ -605,8 +605,7 @@ namespace System.Xml.Xsl.IlGen public void CallSyncToNavigator() { // Get helper method from module - if (_methSyncToNav == null) - _methSyncToNav = _module.FindMethod("SyncToNavigator"); + _methSyncToNav ??= _module.FindMethod("SyncToNavigator"); Call(_methSyncToNav!); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/StaticDataManager.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/StaticDataManager.cs index 9b0d7cb..255a6e5 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/StaticDataManager.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/StaticDataManager.cs @@ -75,8 +75,7 @@ namespace System.Xml.Xsl.IlGen /// public int DeclareName(string name) { - if (_uniqueNames == null) - _uniqueNames = new UniqueList(); + _uniqueNames ??= new UniqueList(); return _uniqueNames.Add(name); } @@ -95,8 +94,7 @@ namespace System.Xml.Xsl.IlGen /// public int DeclareNameFilter(string locName, string nsUri) { - if (_uniqueFilters == null) - _uniqueFilters = new UniqueList(); + _uniqueFilters ??= new UniqueList(); return _uniqueFilters.Add(new Int32Pair(DeclareName(locName), DeclareName(nsUri))); } @@ -131,8 +129,7 @@ namespace System.Xml.Xsl.IlGen } // Add mappings to list and return index - if (_prefixMappingsList == null) - _prefixMappingsList = new List(); + _prefixMappingsList ??= new List(); _prefixMappingsList.Add(prefixMappings); return _prefixMappingsList.Count - 1; @@ -153,8 +150,7 @@ namespace System.Xml.Xsl.IlGen { int idx; - if (_globalNames == null) - _globalNames = new List(); + _globalNames ??= new List(); idx = _globalNames.Count; _globalNames.Add(name); @@ -175,8 +171,7 @@ namespace System.Xml.Xsl.IlGen /// public int DeclareEarlyBound(string namespaceUri, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type ebType) { - if (_earlyInfo == null) - _earlyInfo = new UniqueList(); + _earlyInfo ??= new UniqueList(); return _earlyInfo.Add(new EarlyBoundInfo(namespaceUri, ebType)); } @@ -184,16 +179,7 @@ namespace System.Xml.Xsl.IlGen /// /// Return an array of all early bound information that is used by the query (null if none is used). /// - public EarlyBoundInfo[]? EarlyBound - { - get - { - if (_earlyInfo != null) - return _earlyInfo.ToArray(); - - return null; - } - } + public EarlyBoundInfo[]? EarlyBound => _earlyInfo?.ToArray(); /// /// Add "type" to the list of unique types that are used by this query. Return the index of @@ -201,8 +187,7 @@ namespace System.Xml.Xsl.IlGen /// public int DeclareXmlType(XmlQueryType type) { - if (_uniqueXmlTypes == null) - _uniqueXmlTypes = new UniqueList(); + _uniqueXmlTypes ??= new UniqueList(); XmlQueryTypeFactory.CheckSerializability(type); return _uniqueXmlTypes.Add(type); @@ -222,8 +207,7 @@ namespace System.Xml.Xsl.IlGen /// public int DeclareCollation(string collation) { - if (_uniqueCollations == null) - _uniqueCollations = new UniqueList(); + _uniqueCollations ??= new UniqueList(); return _uniqueCollations.Add(XmlCollation.Create(collation)); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILConstructAnalyzer.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILConstructAnalyzer.cs index 2ca446e..65d93ea 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILConstructAnalyzer.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILConstructAnalyzer.cs @@ -359,16 +359,7 @@ namespace System.Xml.Xsl.IlGen /// This annotation is only applicable to Function nodes. It contains a list of XmlILConstructInfo annotations /// for all QilInvoke nodes which call the annotated function. /// - public ArrayList CallersInfo - { - get - { - if (_callersInfo == null) - _callersInfo = new ArrayList(); - - return _callersInfo; - } - } + public ArrayList CallersInfo => _callersInfo ??= new ArrayList(); /// /// Return name of this annotation. diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILOptimizerVisitor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILOptimizerVisitor.cs index 0c7db85..fc1e40a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILOptimizerVisitor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILOptimizerVisitor.cs @@ -123,10 +123,7 @@ namespace System.Xml.Xsl.IlGen /// protected override QilNode VisitReference(QilNode oldNode) { - QilNode? newNode = _subs.FindReplacement(oldNode); - - if (newNode == null) - newNode = oldNode; + QilNode? newNode = _subs.FindReplacement(oldNode) ?? oldNode; // Fold reference to constant value // This is done here because "p" currently cannot match references diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilCloneVisitor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilCloneVisitor.cs index 1029354..bce34b4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilCloneVisitor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilCloneVisitor.cs @@ -65,8 +65,7 @@ namespace System.Xml.Xsl.Qil newNode = FindClonedReference(oldNode); } - if (newNode == null) - newNode = oldNode.ShallowClone(_fac); + newNode ??= oldNode.ShallowClone(_fac); return base.Visit(newNode); } @@ -88,8 +87,7 @@ namespace System.Xml.Xsl.Qil parent[i] = VisitReference(child); // If no substutition found, then use original child - if (parent[i] == null) - parent[i] = child; + parent[i] ??= child; } else { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilXmlWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilXmlWriter.cs index 7946d52..83f5876 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilXmlWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilXmlWriter.cs @@ -183,9 +183,7 @@ namespace System.Xml.Xsl.Qil protected override QilNode VisitReference(QilNode node) { QilReference reference = (QilReference)node; - string name = _ngen.NameOf(node); - if (name == null) - name = "OUT-OF-SCOPE REFERENCE"; + string name = _ngen.NameOf(node) ?? "OUT-OF-SCOPE REFERENCE"; this.writer.WriteStartElement("RefTo"); this.writer.WriteAttributeString("id", name); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/DocumentOrderComparer.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/DocumentOrderComparer.cs index 4641526..f9d6dee 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/DocumentOrderComparer.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/DocumentOrderComparer.cs @@ -36,8 +36,7 @@ namespace System.Xml.Xsl.Runtime } // Use this.roots to impose stable ordering - if (_roots == null) - _roots = new List(); + _roots ??= new List(); Debug.Assert(GetDocumentIndex(navThis) != GetDocumentIndex(navThat)); return GetDocumentIndex(navThis) < GetDocumentIndex(navThat) ? -1 : 1; @@ -55,8 +54,7 @@ namespace System.Xml.Xsl.Runtime XPathNavigator navRoot; // Use this.roots to impose stable ordering - if (_roots == null) - _roots = new List(); + _roots ??= new List(); // Position navigator to root navRoot = nav.Clone(); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/WhitespaceRuleReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/WhitespaceRuleReader.cs index 2ad5fea..496eeb8 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/WhitespaceRuleReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/WhitespaceRuleReader.cs @@ -128,10 +128,9 @@ namespace System.Xml.Xsl.Runtime if (_shouldStrip) { // Save whitespace until it can be determined whether it will be stripped - if (ws == null) - ws = base.Value; - else - ws = string.Concat(ws, base.Value); + ws = ws == null ? + base.Value : + string.Concat(ws, base.Value); // Read next event continue; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlExtensionFunction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlExtensionFunction.cs index c932dca..56c26ba 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlExtensionFunction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlExtensionFunction.cs @@ -36,8 +36,7 @@ namespace System.Xml.Xsl.Runtime { XmlExtensionFunction func; - if (_funcCached == null) - _funcCached = new XmlExtensionFunction(); + _funcCached ??= new XmlExtensionFunction(); // If the extension function already exists in the table, then binding has already been performed _funcCached.Init(name, namespaceUri, numArgs, objectType, flags); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryContext.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryContext.cs index 1f0519f..7821643 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryContext.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryContext.cs @@ -267,8 +267,7 @@ namespace System.Xml.Xsl.Runtime throw new XslTransformException(SR.XmlIl_UnknownExtObj, namespaceUri); // Bind to a method on the instance object - if (_extFuncsLate == null) - _extFuncsLate = new XmlExtensionFunctionTable(); + _extFuncsLate ??= new XmlExtensionFunctionTable(); // Bind to the instance, looking for a matching method (throws if no matching method) XmlExtensionFunction extFunc = _extFuncsLate.Bind(name, namespaceUri, args.Length, instance.GetType(), XmlQueryRuntime.LateBoundFlags); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryOutput.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryOutput.cs index cd34007..fdb8db8 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryOutput.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryOutput.cs @@ -173,8 +173,7 @@ namespace System.Xml.Xsl.Runtime WriteNamespaceDeclarationUnchecked(prefix, ns); // Cache attributes in order to detect duplicates - if (_attrCache == null) - _attrCache = new XmlAttributeCache(); + _attrCache ??= new XmlAttributeCache(); _attrCache.Init(Writer); Writer = _attrCache; @@ -1400,8 +1399,7 @@ namespace System.Xml.Xsl.Runtime string genPrefix; Debug.Assert(prefix != null && ns != null && ns.Length != 0); - if (_conflictPrefixes == null) - _conflictPrefixes = new Dictionary(16); + _conflictPrefixes ??= new Dictionary(16); if (_nsmgr == null) { @@ -1542,8 +1540,7 @@ namespace System.Xml.Xsl.Runtime private void PushElementNames(string prefix, string localName, string ns) { // Push the name parts onto a stack - if (_stkNames == null) - _stkNames = new Stack(15); + _stkNames ??= new Stack(15); _stkNames.Push(prefix); _stkNames.Push(localName); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryRuntime.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryRuntime.cs index 45746ac..064e333 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryRuntime.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryRuntime.cs @@ -239,18 +239,7 @@ namespace System.Xml.Xsl.Runtime /// /// Return the object that manages the state needed to implement various Xslt functions. /// - public XsltLibrary XsltFunctions - { - get - { - if (_xsltLib == null) - { - _xsltLib = new XsltLibrary(this); - } - - return _xsltLib; - } - } + public XsltLibrary XsltFunctions => _xsltLib ??= new XsltLibrary(this); /// /// Get the early-bound extension object identified by "index". If it does not yet exist, create an instance using the diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlSortKeyAccumulator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlSortKeyAccumulator.cs index 29fc8c7..180f4f6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlSortKeyAccumulator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlSortKeyAccumulator.cs @@ -29,8 +29,7 @@ namespace System.Xml.Xsl.Runtime /// public void Create() { - if (_keys == null) - _keys = new XmlSortKey[DefaultSortKeyCount]; + _keys ??= new XmlSortKey[DefaultSortKeyCount]; _pos = 0; _keys[0] = null; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltFunctions.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltFunctions.cs index 038e99f..2a6a8ce 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltFunctions.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltFunctions.cs @@ -120,15 +120,16 @@ namespace System.Xml.Xsl.Runtime { // Space was previous character or this is a non-space character if (sb == null) + { sb = new StringBuilder(value.Length); + } else + { sb.Append(' '); + } // Copy non-space characters into string builder - if (idxSpace == idx) - sb.Append(value, idxStart, idx - idxStart - 1); - else - sb.Append(value, idxStart, idx - idxStart); + sb.Append(value, idxStart, idxSpace == idx ? idx - idxStart - 1 : idx - idxStart); idxStart = idx + 1; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltLibrary.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltLibrary.cs index d834225..df96ed6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltLibrary.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltLibrary.cs @@ -163,10 +163,7 @@ namespace System.Xml.Xsl.Runtime public int RegisterDecimalFormat(XmlQualifiedName name, string infinitySymbol, string nanSymbol, string characters) { - if (_decimalFormats == null) - { - _decimalFormats = new Dictionary(); - } + _decimalFormats ??= new Dictionary(); _decimalFormats.Add(name, CreateDecimalFormat(infinitySymbol, nanSymbol, characters)); return 0; // have to return something } @@ -189,10 +186,7 @@ namespace System.Xml.Xsl.Runtime public double RegisterDecimalFormatter(string formatPicture, string infinitySymbol, string nanSymbol, string characters) { - if (_decimalFormatters == null) - { - _decimalFormatters = new List(); - } + _decimalFormatters ??= new List(); _decimalFormatters.Add(new DecimalFormatter(formatPicture, CreateDecimalFormat(infinitySymbol, nanSymbol, characters))); return _decimalFormatters.Count - 1; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlILCommand.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlILCommand.cs index 0ee028b..53ffbdd 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlILCommand.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlILCommand.cs @@ -83,8 +83,7 @@ namespace System.Xml.Xsl Debug.Assert(results != null); // Ensure that dataSources is always non-null - if (dataSources == null) - dataSources = XmlNullResolver.Singleton; + dataSources ??= XmlNullResolver.Singleton; _delExec(new XmlQueryRuntime(_staticData, defaultDocument, dataSources, argumentList, results)); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilGenerator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilGenerator.cs index 2b17f4a..043f0f7 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilGenerator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilGenerator.cs @@ -2424,10 +2424,7 @@ namespace System.Xml.Xsl.Xslt XPathScanner scanner; QilNode result; - if (_keyMatchBuilder == null) - { - _keyMatchBuilder = new KeyMatchBuilder((IXPathEnvironment)this); - } + _keyMatchBuilder ??= new KeyMatchBuilder((IXPathEnvironment)this); SetEnvironmentFlags(/*allowVariables:*/false, /*allowCurrent:*/false, /*allowKey:*/false); if (pttrn == null) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilGeneratorEnv.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilGeneratorEnv.cs index b611469..818364a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilGeneratorEnv.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilGeneratorEnv.cs @@ -425,10 +425,7 @@ namespace System.Xml.Xsl.Xslt } else { - if (_generalKey == null) - { - _generalKey = CreateGeneralKeyFunction(); - } + _generalKey ??= CreateGeneralKeyFunction(); QilIterator i = _f.Let(name); QilNode resolvedName = ResolveQNameDynamic(/*ignoreDefaultNs:*/true, i); result = _f.Invoke(_generalKey, _f.ActualParameterList(i, resolvedName, key, env.GetCurrent()!)); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilStrConcatenator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilStrConcatenator.cs index 96010a3..0bcb516 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilStrConcatenator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilStrConcatenator.cs @@ -33,10 +33,7 @@ namespace System.Xml.Xsl.Xslt private void FlushBuilder() { - if (_concat == null) - { - _concat = _f.BaseFactory.Sequence(); - } + _concat ??= _f.BaseFactory.Sequence(); if (_builder.Length != 0) { _concat.Add(_f.String(_builder.ToString())); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XslAst.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XslAst.cs index 224c77d..7009a42 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XslAst.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XslAst.cs @@ -117,10 +117,7 @@ namespace System.Xml.Xsl.Xslt public void AddContent(XslNode node) { Debug.Assert(node != null); - if (_content == null) - { - _content = new List(); - } + _content ??= new List(); _content.Add(node); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XsltLoader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XsltLoader.cs index b003680..1032449 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XsltLoader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XsltLoader.cs @@ -1295,10 +1295,7 @@ namespace System.Xml.Xsl.Xslt } } - if (scriptNs == null) - { - scriptNs = _compiler.CreatePhantomNamespace(); - } + scriptNs ??= _compiler.CreatePhantomNamespace(); ParseStringAttribute(1, "language"); if (!_compiler.Settings.EnableScript) @@ -1550,11 +1547,7 @@ namespace System.Xml.Xsl.Xslt { ContextInfo ctxInfo = _input.GetAttributes(_applyTemplatesAttributes); - string? select = ParseStringAttribute(0, "select"); - if (select == null) - { - select = "node()"; - } + string select = ParseStringAttribute(0, "select") ?? "node()"; QilName mode = ParseModeAttribute(1); List content = LoadWithParams(InstructionFlags.AllowSort); @@ -1818,10 +1811,7 @@ namespace System.Xml.Xsl.Xslt string? groupingSize = ParseStringAttribute(10, "grouping-size"); // Default values for xsl:number : level="single" format="1" - if (format == null) - { - format = "1"; - } + format ??= "1"; CheckNoContent(); return SetInfo( @@ -2187,10 +2177,7 @@ namespace System.Xml.Xsl.Xslt string select = ParseStringAttribute(0, "select"); string regex = ParseStringAttribute(1, "regex" ); - string flags = ParseStringAttribute(2, "flags" ); - if (flags == null) { - flags = ""; - } + string flags = ParseStringAttribute(2, "flags" ) ?? ""; ReportNYI("xsl:analyze-string"); @@ -2412,9 +2399,7 @@ namespace System.Xml.Xsl.Xslt if (format != null) ReportNYI("xsl:result-document/@format"); - if (href == null) { - href = string.Empty; - } + href ??= string.Empty; // attHref is a BaseUri of new output tree. It should be resolved relative to "base output URI" @@ -2847,11 +2832,7 @@ namespace System.Xml.Xsl.Xslt } else { - namespaceName = _input.LookupXmlNamespace(prefix); - if (namespaceName == null) - { - namespaceName = _compiler.CreatePhantomNamespace(); - } + namespaceName = _input.LookupXmlNamespace(prefix) ?? _compiler.CreatePhantomNamespace(); } int index = ( (localName == null ? 1 : 0) + @@ -3071,10 +3052,7 @@ namespace System.Xml.Xsl.Xslt // NOTE: XmlNodeType.SignificantWhitespace is not allowed here if (_input.NodeType != XmlNodeType.Whitespace) { - if (result == null) - { - result = _input.BuildNameLineInfo(); - } + result ??= _input.BuildNameLineInfo(); _input.SkipNode(); } } while (_input.MoveToNextSibling()); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ActionFrame.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ActionFrame.cs index 739fb2a..3a9d084 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ActionFrame.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ActionFrame.cs @@ -109,27 +109,19 @@ namespace System.Xml.Xsl.XsltOld internal void SetParameter(XmlQualifiedName name, object value) { - if (_withParams == null) - { - _withParams = new Hashtable(); - } + _withParams ??= new Hashtable(); Debug.Assert(!_withParams.Contains(name), "We should check duplicate params at compile time"); _withParams[name] = value; } internal void ResetParams() { - if (_withParams != null) - _withParams.Clear(); + _withParams?.Clear(); } internal object? GetParameter(XmlQualifiedName name) { - if (_withParams != null) - { - return _withParams[name]; - } - return null; + return _withParams?[name]; } internal void InitNodeSet(XPathNodeIterator nodeSet) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Compiler.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Compiler.cs index b6ea0dd..fd6e21a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Compiler.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Compiler.cs @@ -372,10 +372,7 @@ namespace System.Xml.Xsl.XsltOld internal void AddNamespaceAlias(string StylesheetURI, NamespaceInfo AliasInfo) { - if (_globalNamespaceAliasTable == null) - { - _globalNamespaceAliasTable = new Hashtable(); - } + _globalNamespaceAliasTable ??= new Hashtable(); NamespaceInfo? duplicate = _globalNamespaceAliasTable[StylesheetURI] as NamespaceInfo; if (duplicate == null || AliasInfo.stylesheetId <= duplicate.stylesheetId) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ContainerAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ContainerAction.cs index 14c86ee..9c31386 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ContainerAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ContainerAction.cs @@ -435,10 +435,7 @@ namespace System.Xml.Xsl.XsltOld input.ToParent(); } info.NegativeInfinitySymbol = string.Concat(info.NegativeSign, info.PositiveInfinitySymbol); - if (Name == null) - { - Name = new XmlQualifiedName(); - } + Name ??= new XmlQualifiedName(); compiler.AddDecimalFormat(Name, format); CheckEmpty(compiler); } @@ -860,10 +857,7 @@ namespace System.Xml.Xsl.XsltOld internal void AddAction(Action? action) { - if (this.containedActions == null) - { - this.containedActions = new ArrayList(); - } + this.containedActions ??= new ArrayList(); this.containedActions.Add(action); lastCopyCodeAction = null; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ForEachAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ForEachAction.cs index de35b02..c9ae1d0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ForEachAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ForEachAction.cs @@ -111,10 +111,7 @@ namespace System.Xml.Xsl.XsltOld if (Ref.Equal(input.NamespaceURI, input.Atoms.UriXsl) && Ref.Equal(input.LocalName, input.Atoms.Sort)) { - if (_sortContainer == null) - { - _sortContainer = new ContainerAction(); - } + _sortContainer ??= new ContainerAction(); _sortContainer.AddAction(compiler.CreateSortAction()); continue; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/InputScope.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/InputScope.cs index 93e73c0..607bde8 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/InputScope.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/InputScope.cs @@ -59,10 +59,7 @@ namespace System.Xml.Xsl.XsltOld internal void InsertExtensionNamespace(string nspace) { - if (_extensionNamespaces == null) - { - _extensionNamespaces = new Hashtable(); - } + _extensionNamespaces ??= new Hashtable(); _extensionNamespaces[nspace] = null; } @@ -77,10 +74,7 @@ namespace System.Xml.Xsl.XsltOld internal void InsertExcludedNamespace(string nspace) { - if (_excludedNamespaces == null) - { - _excludedNamespaces = new Hashtable(); - } + _excludedNamespaces ??= new Hashtable(); _excludedNamespaces[nspace] = null; } @@ -97,10 +91,7 @@ namespace System.Xml.Xsl.XsltOld { Debug.Assert(variable != null); - if (_variables == null) - { - _variables = new Hashtable(); - } + _variables ??= new Hashtable(); _variables[variable.Name!] = variable; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Processor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Processor.cs index 6813edc..b467573 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Processor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Processor.cs @@ -303,17 +303,7 @@ namespace System.Xml.Xsl.XsltOld } #pragma warning restore CA1822 - internal ArrayList NumberList - { - get - { - if (_numberList == null) - { - _numberList = new ArrayList(); - } - return _numberList; - } - } + internal ArrayList NumberList => _numberList ??= new ArrayList(); internal IXsltDebugger? Debugger { @@ -559,40 +549,21 @@ namespace System.Xml.Xsl.XsltOld return expr; } - private XsltCompileContext GetValueOfContext() - { - if (_valueOfContext == null) - { - _valueOfContext = new XsltCompileContext(); - } - return _valueOfContext; - } + private XsltCompileContext GetValueOfContext() => + _valueOfContext ??= new XsltCompileContext(); [Conditional("DEBUG")] private void RecycleValueOfContext() { - if (_valueOfContext != null) - { - _valueOfContext.Recycle(); - } + _valueOfContext?.Recycle(); } - private XsltCompileContext GetMatchesContext() - { - if (_matchesContext == null) - { - _matchesContext = new XsltCompileContext(); - } - return _matchesContext; - } + private XsltCompileContext GetMatchesContext() => _matchesContext ??= new XsltCompileContext(); [Conditional("DEBUG")] private void RecycleMatchesContext() { - if (_matchesContext != null) - { - _matchesContext.Recycle(); - } + _matchesContext?.Recycle(); } internal string? ValueOf(ActionFrame context, int key) @@ -691,9 +662,7 @@ namespace System.Xml.Xsl.XsltOld string? value = null; if (objValue != null) value = XmlConvert.ToXPathString(objValue); - if (value == null) - value = string.Empty; - return value; + return value ?? string.Empty; } internal bool EvaluateBoolean(ActionFrame context, int key) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ReaderOutput.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ReaderOutput.cs index dd263bf..b4e4b19 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ReaderOutput.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ReaderOutput.cs @@ -420,10 +420,7 @@ namespace System.Xml.Xsl.XsltOld } else { - if (sb == null) - { - sb = new StringBuilder(result); - } + sb ??= new StringBuilder(result); sb.Append(this.Value); } if (!Read()) @@ -628,14 +625,8 @@ namespace System.Xml.Xsl.XsltOld private bool FindAttribute(string? localName, string? namespaceURI, out int attrIndex) { - if (namespaceURI == null) - { - namespaceURI = string.Empty; - } - if (localName == null) - { - localName = string.Empty; - } + namespaceURI ??= string.Empty; + localName ??= string.Empty; for (int index = 0; index < _attributeCount; index++) { @@ -655,10 +646,7 @@ namespace System.Xml.Xsl.XsltOld private bool FindAttribute(string? name, out int attrIndex) { - if (name == null) - { - name = string.Empty; - } + name ??= string.Empty; for (int index = 0; index < _attributeCount; index++) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/RecordBuilder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/RecordBuilder.cs index 0a1f386..9031e06 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/RecordBuilder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/RecordBuilder.cs @@ -627,9 +627,13 @@ namespace System.Xml.Xsl.XsltOld if (minus) { if (newComment == null) + { newComment = new StringBuilder(comment, begin, index, 2 * comment.Length); + } else + { newComment.Append(comment, begin, index - begin); + } newComment.Append(s_SpaceMinus); begin = index + 1; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/RootAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/RootAction.cs index cb5ffc7..845fafa 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/RootAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/RootAction.cs @@ -35,10 +35,7 @@ namespace System.Xml.Xsl.XsltOld public void AddKey(XPathNavigator root, Hashtable table) { - if (_keyNodes == null) - { - _keyNodes = new ArrayList(); - } + _keyNodes ??= new ArrayList(); _keyNodes.Add(new DocumentKeyList(root, table)); } @@ -88,17 +85,7 @@ namespace System.Xml.Xsl.XsltOld private List? _keyList; private XsltOutput? _output; - internal XsltOutput Output - { - get - { - if (_output == null) - { - _output = new XsltOutput(); - } - return _output; - } - } + internal XsltOutput Output => _output ??= new XsltOutput(); /* * Compile @@ -110,10 +97,7 @@ namespace System.Xml.Xsl.XsltOld internal void InsertKey(XmlQualifiedName name, int MatchKey, int UseKey) { - if (_keyList == null) - { - _keyList = new List(); - } + _keyList ??= new List(); _keyList.Add(new Key(name, MatchKey, UseKey)); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/SequentialOutput.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/SequentialOutput.cs index 27eac7e..2cabf79 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/SequentialOutput.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/SequentialOutput.cs @@ -390,10 +390,7 @@ namespace System.Xml.Xsl.XsltOld private void CacheRecord(RecordBuilder record) { - if (_outputCache == null) - { - _outputCache = new ArrayList(); - } + _outputCache ??= new ArrayList(); _outputCache.Add(record.MainNode.Clone()); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Stylesheet.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Stylesheet.cs index 4c06483..907bfbe 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Stylesheet.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Stylesheet.cs @@ -148,11 +148,7 @@ namespace System.Xml.Xsl.XsltOld internal void AddAttributeSet(AttributeSetAction attributeSet) { Debug.Assert(attributeSet.Name != null); - if (_attributeSetTable == null) - { - _attributeSetTable = new Hashtable(); - } - Debug.Assert(_attributeSetTable != null); + _attributeSetTable ??= new Hashtable(); if (_attributeSetTable.ContainsKey(attributeSet.Name) == false) { @@ -190,16 +186,8 @@ namespace System.Xml.Xsl.XsltOld if (template.MatchKey != Compiler.InvalidQueryKey) { - if (_modeManagers == null) - { - _modeManagers = new Hashtable(); - } - Debug.Assert(_modeManagers != null); - - if (mode == null) - { - mode = XmlQualifiedName.Empty; - } + _modeManagers ??= new Hashtable(); + mode ??= XmlQualifiedName.Empty; TemplateManager? manager = (TemplateManager?)_modeManagers[mode]; @@ -314,12 +302,7 @@ namespace System.Xml.Xsl.XsltOld // If unsuccessful, search in imported documents from backwards // - if (action == null) - { - action = FindTemplateImports(processor, navigator, mode); - } - - return action; + return action ?? FindTemplateImports(processor, navigator, mode); } internal TemplateAction? FindTemplateImports(Processor processor, XPathNavigator navigator, XmlQualifiedName mode) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TemplateLookupAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TemplateLookupAction.cs index fed4d7a..2308a68 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TemplateLookupAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TemplateLookupAction.cs @@ -41,10 +41,7 @@ namespace System.Xml.Xsl.XsltOld } // Built-int template rules - if (action == null) - { - action = BuiltInTemplate(frame.Node!); - } + action ??= BuiltInTemplate(frame.Node!); // Jump if (action != null) @@ -126,10 +123,7 @@ namespace System.Xml.Xsl.XsltOld } // Built-int template rules - if (action == null) - { - action = BuiltInTemplate(frame.Node!); - } + action ??= BuiltInTemplate(frame.Node!); // Jump if (action != null) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TemplateManager.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TemplateManager.cs index 609d790..bab1745 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TemplateManager.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TemplateManager.cs @@ -62,10 +62,7 @@ namespace System.Xml.Xsl.XsltOld _mode.Equals(template.Mode) ); - if (this.templates == null) - { - this.templates = new ArrayList(); - } + this.templates ??= new ArrayList(); this.templates.Add(template); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/XsltOutput.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/XsltOutput.cs index 6c68964..fb9c7fb 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/XsltOutput.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/XsltOutput.cs @@ -199,10 +199,7 @@ namespace System.Xml.Xsl.XsltOld { string[] qnames = XmlConvert.SplitString(value); - if (_cdataElements == null) - { - _cdataElements = new Hashtable(qnames.Length); - } + _cdataElements ??= new Hashtable(qnames.Length); for (int i = 0; i < qnames.Length; i++) { diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/CustomType.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/CustomType.cs index 5a048fc..543e113 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/CustomType.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/CustomType.cs @@ -134,8 +134,7 @@ namespace System.Reflection.Context.Custom if (matchingProperties.Count == 0) return null; - if (binder == null) - binder = Type.DefaultBinder; + binder ??= Type.DefaultBinder; return binder.SelectProperty(bindingAttr, matchingProperties.ToArray(), returnType, types, modifiers); } @@ -276,24 +275,12 @@ namespace System.Reflection.Context.Custom { Debug.Assert(getPropertySetter && types != null && types.Length == 1); - if (binder == null) - binder = Type.DefaultBinder; + binder ??= Type.DefaultBinder; return (MethodInfo?)binder.SelectMethod(bindingAttr, matchingMethods.ToArray(), types, modifiers); } } - private IEnumerable NewProperties - { - get - { - if (_newProperties == null) - { - _newProperties = ReflectionContext.GetNewPropertiesForType(this); - } - - return _newProperties; - } - } + private IEnumerable NewProperties => _newProperties ??= ReflectionContext.GetNewPropertiesForType(this); } } diff --git a/src/libraries/System.Reflection.DispatchProxy/src/System/Reflection/DispatchProxyGenerator.cs b/src/libraries/System.Reflection.DispatchProxy/src/System/Reflection/DispatchProxyGenerator.cs index 832312a..c779ad0 100644 --- a/src/libraries/System.Reflection.DispatchProxy/src/System/Reflection/DispatchProxyGenerator.cs +++ b/src/libraries/System.Reflection.DispatchProxy/src/System/Reflection/DispatchProxyGenerator.cs @@ -134,18 +134,8 @@ namespace System.Reflection // Gets or creates the ConstructorInfo for the IgnoresAccessChecksAttribute. // This attribute is both defined and referenced in the dynamic assembly to // allow access to internal types in other assemblies. - internal ConstructorInfo IgnoresAccessChecksAttributeConstructor - { - get - { - if (_ignoresAccessChecksToAttributeConstructor == null) - { - _ignoresAccessChecksToAttributeConstructor = IgnoreAccessChecksToAttributeBuilder.AddToModule(_mb); - } - - return _ignoresAccessChecksToAttributeConstructor; - } - } + internal ConstructorInfo IgnoresAccessChecksAttributeConstructor => + _ignoresAccessChecksToAttributeConstructor ??= IgnoreAccessChecksToAttributeBuilder.AddToModule(_mb); public GeneratedTypeInfo GetProxyType( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type baseType, diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/ControlFlowBuilder.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/ControlFlowBuilder.cs index 037ddf6..95b2e13 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/ControlFlowBuilder.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/ControlFlowBuilder.cs @@ -215,10 +215,7 @@ namespace System.Reflection.Metadata.Ecma335 ValidateLabel(handlerStart, nameof(handlerStart)); ValidateLabel(handlerEnd, nameof(handlerEnd)); - if (_lazyExceptionHandlers == null) - { - _lazyExceptionHandlers = ImmutableArray.CreateBuilder(); - } + _lazyExceptionHandlers ??= ImmutableArray.CreateBuilder(); _lazyExceptionHandlers.Add(new ExceptionHandlerInfo(kind, tryStart, tryEnd, handlerStart, handlerEnd, filterStart, catchType)); } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/NamespaceCache.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/NamespaceCache.cs index 30f2027..bf66a5a 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/NamespaceCache.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/NamespaceCache.cs @@ -178,10 +178,7 @@ namespace System.Reflection.Metadata.Ecma335 Debug.Assert(data.Namespaces!.Count == 0); data.MergeInto(existingRecord); - if (remaps == null) - { - remaps = new List>(); - } + remaps ??= new List>(); remaps.Add(new KeyValuePair(group.Key, existingRecord)); } else diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.cs index 7c9f080..89a221b 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.cs @@ -85,10 +85,7 @@ namespace System.Reflection.Metadata Throw.ArgumentNull(nameof(metadata)); } - if (utf8Decoder == null) - { - utf8Decoder = MetadataStringDecoder.DefaultUTF8; - } + utf8Decoder ??= MetadataStringDecoder.DefaultUTF8; if (!(utf8Decoder.Encoding is UTF8Encoding)) { diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/EventDefinition.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/EventDefinition.cs index 5cacd03..0f6dc1e 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/EventDefinition.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/EventDefinition.cs @@ -84,8 +84,7 @@ namespace System.Reflection.Metadata break; case MethodSemanticsAttributes.Other: - if (other == null) - other = ImmutableArray.CreateBuilder(); + other ??= ImmutableArray.CreateBuilder(); other.Add(_reader.MethodSemanticsTable.GetMethod(rowId)); break; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/PropertyDefinition.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/PropertyDefinition.cs index c527ef4..00b28b1 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/PropertyDefinition.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/PropertyDefinition.cs @@ -91,8 +91,7 @@ namespace System.Reflection.Metadata break; case MethodSemanticsAttributes.Other: - if (other == null) - other = ImmutableArray.CreateBuilder(); + other ??= ImmutableArray.CreateBuilder(); other.Add(_reader.MethodSemanticsTable.GetMethod(rowId)); break; diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/Runtime/BindingFlagSupport/PropertyPolicies.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/Runtime/BindingFlagSupport/PropertyPolicies.cs index 98808e1..73e8dcb 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/Runtime/BindingFlagSupport/PropertyPolicies.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/Runtime/BindingFlagSupport/PropertyPolicies.cs @@ -81,15 +81,7 @@ namespace System.Reflection.Runtime.BindingFlagSupport return false; } - private static MethodInfo? GetAccessorMethod(PropertyInfo property) - { - MethodInfo? accessor = property.GetMethod; - if (accessor == null) - { - accessor = property.SetMethod; - } - - return accessor; - } + private static MethodInfo? GetAccessorMethod(PropertyInfo property) => + property.GetMethod ?? property.SetMethod; } } diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Assemblies/RoAssembly.GetForwardedTypes.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Assemblies/RoAssembly.GetForwardedTypes.cs index daebb5e..6a951b7 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Assemblies/RoAssembly.GetForwardedTypes.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Assemblies/RoAssembly.GetForwardedTypes.cs @@ -44,10 +44,7 @@ namespace System.Reflection.TypeLoading } else { - if (exceptions == null) - { - exceptions = new List(); - } + exceptions ??= new List(); exceptions.Add(exception!); } } 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 7817703..5b8b52a 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 @@ -278,8 +278,7 @@ namespace System.Reflection.TypeLoading Func typeResolver = delegate (Assembly? assembly, string fullName, bool ignoreCase2) { - if (assembly == null) - assembly = defaultAssembly; + assembly ??= defaultAssembly; Debug.Assert(assembly is RoAssembly); RoAssembly roAssembly = (RoAssembly)assembly; diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/MethodBase/Ecma/EcmaMethodDecoder.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/MethodBase/Ecma/EcmaMethodDecoder.cs index 23341e6..288d658 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/MethodBase/Ecma/EcmaMethodDecoder.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/MethodBase/Ecma/EcmaMethodDecoder.cs @@ -86,8 +86,7 @@ namespace System.Reflection.TypeLoading.Ecma for (int position = -1; position < numParameters; position++) { Type parameterType = position == -1 ? sig.ReturnType : sig.ParameterTypes[position]; - if (methodSig[position] == null) - methodSig[position] = new RoThinMethodParameter(roMethodBase, position, parameterType); + methodSig[position] ??= new RoThinMethodParameter(roMethodBase, position, parameterType); } return methodSig; 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 1615da1..8644574 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 @@ -38,8 +38,7 @@ namespace System.Reflection.TypeLoading if ((bindingAttr & BindingFlags.ExactBinding) != 0) return System.DefaultBinder.ExactBinding(candidates.ToArray(), types, modifiers) as ConstructorInfo; - if (binder == null) - binder = Loader.GetDefaultBinder(); + binder ??= Loader.GetDefaultBinder(); return binder.SelectMethod(bindingAttr, candidates.ToArray(), types, modifiers) as ConstructorInfo; } @@ -96,8 +95,7 @@ namespace System.Reflection.TypeLoading if (types.Length == 0 && candidates.Count == 1) return candidates[0]; - if (binder == null) - binder = Loader.GetDefaultBinder(); + binder ??= Loader.GetDefaultBinder(); return binder.SelectMethod(bindingAttr, candidates.ToArray(), types, modifiers) as MethodInfo; } } @@ -157,8 +155,7 @@ namespace System.Reflection.TypeLoading if ((bindingAttr & BindingFlags.ExactBinding) != 0) return System.DefaultBinder.ExactPropertyBinding(candidates.ToArray(), returnType, types, modifiers); - if (binder == null) - binder = Loader.GetDefaultBinder(); + binder ??= Loader.GetDefaultBinder(); return binder.SelectProperty(bindingAttr, candidates.ToArray(), returnType, types, modifiers); } diff --git a/src/libraries/System.Resources.Extensions/src/System/Resources/Extensions/DeserializingResourceReader.cs b/src/libraries/System.Resources.Extensions/src/System/Resources/Extensions/DeserializingResourceReader.cs index 49cadc1..716001e 100644 --- a/src/libraries/System.Resources.Extensions/src/System/Resources/Extensions/DeserializingResourceReader.cs +++ b/src/libraries/System.Resources.Extensions/src/System/Resources/Extensions/DeserializingResourceReader.cs @@ -37,13 +37,10 @@ namespace System.Resources.Extensions #pragma warning disable SYSLIB0011 private object ReadBinaryFormattedObject() { - if (_formatter == null) + _formatter ??= new BinaryFormatter() { - _formatter = new BinaryFormatter() - { - Binder = new UndoTruncatedTypeNameSerializationBinder() - }; - } + Binder = new UndoTruncatedTypeNameSerializationBinder() + }; return _formatter.Deserialize(_store.BaseStream); } diff --git a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheItemPolicy.cs b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheItemPolicy.cs index fdd3d52..79e06d1 100644 --- a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheItemPolicy.cs +++ b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheItemPolicy.cs @@ -21,17 +21,7 @@ namespace System.Runtime.Caching set { _absExpiry = value; } } - public Collection ChangeMonitors - { - get - { - if (_changeMonitors == null) - { - _changeMonitors = new Collection(); - } - return _changeMonitors; - } - } + public Collection ChangeMonitors => _changeMonitors ??= new Collection(); public CacheItemPriority Priority { 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 6241c44..c135219 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 @@ -293,10 +293,7 @@ namespace System.Runtime.Caching { lock (s_initLock) { - if (s_defaultCache == null) - { - s_defaultCache = new MemoryCache(); - } + s_defaultCache ??= new MemoryCache(); } } return s_defaultCache; @@ -792,10 +789,7 @@ namespace System.Runtime.Caching // Ensure the sentinel depends on its updatable entry string[] cacheKeys = { key }; ChangeMonitor expensiveObjectDep = CreateCacheEntryChangeMonitor(cacheKeys); - if (changeMonitors == null) - { - changeMonitors = new Collection(); - } + changeMonitors ??= new Collection(); changeMonitors.Add(expensiveObjectDep); // Insert sentinel entry for the updatable cache entry @@ -889,10 +883,7 @@ namespace System.Runtime.Caching object value = GetInternal(key, null); if (value != null) { - if (values == null) - { - values = new Dictionary(); - } + values ??= new Dictionary(); values[key] = value; } } 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 c84a72f..dcf2a6d 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 @@ -164,18 +164,10 @@ namespace System.Runtime.Caching { return; } - if (_fields == null) - { - _fields = new SeldomUsedFields(); - } - if (_fields._cache == null) - { - _fields._cache = cache; - } - if (_fields._dependents == null) - { - _fields._dependents = new Dictionary(); - } + + _fields ??= new SeldomUsedFields(); + _fields._cache ??= cache; + _fields._dependents ??= new Dictionary(); _fields._dependents[dependent] = dependent; } } @@ -219,10 +211,7 @@ namespace System.Runtime.Caching { lock (this) { - if (_fields == null) - { - _fields = new SeldomUsedFields(); - } + _fields ??= new SeldomUsedFields(); _fields._updateSentinel = Tuple.Create(sentinelStore, sentinelEntry); } } diff --git a/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Analyzers/AddDisableRuntimeMarshallingAttributeFixer.cs b/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Analyzers/AddDisableRuntimeMarshallingAttributeFixer.cs index 2d224e9..c7ede67 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Analyzers/AddDisableRuntimeMarshallingAttributeFixer.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Analyzers/AddDisableRuntimeMarshallingAttributeFixer.cs @@ -53,12 +53,9 @@ namespace Microsoft.Interop.Analyzers private static async Task AddDisableRuntimeMarshallingAttributeApplicationToProject(Project project, CancellationToken cancellationToken) { - Document? assemblyInfo = project.Documents.FirstOrDefault(IsPropertiesAssemblyInfo); - - if (assemblyInfo is null) - { - assemblyInfo = project.AddDocument(AssemblyInfoFileName, "", folders: new[] { PropertiesFolderName }); - } + Document? assemblyInfo = + project.Documents.FirstOrDefault(IsPropertiesAssemblyInfo) ?? + project.AddDocument(AssemblyInfoFileName, "", folders: new[] { PropertiesFolderName }); DocumentEditor editor = await DocumentEditor.CreateAsync(assemblyInfo, cancellationToken).ConfigureAwait(false); diff --git a/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/LibraryImportGenerator.cs b/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/LibraryImportGenerator.cs index b52328e..2cee662 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/LibraryImportGenerator.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/LibraryImportGenerator.cs @@ -270,12 +270,9 @@ namespace Microsoft.Interop var generatorDiagnostics = new GeneratorDiagnostics(); // Process the LibraryImport attribute - LibraryImportData? libraryImportData = ProcessLibraryImportAttribute(generatedDllImportAttr!); - - if (libraryImportData is null) - { - libraryImportData = new LibraryImportData("INVALID_CSHARP_SYNTAX"); - } + LibraryImportData libraryImportData = + ProcessLibraryImportAttribute(generatedDllImportAttr!) ?? + new LibraryImportData("INVALID_CSHARP_SYNTAX"); if (libraryImportData.IsUserDefined.HasFlag(InteropAttributeMember.StringMarshalling)) { diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/ManualTypeMarshallingHelper.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/ManualTypeMarshallingHelper.cs index 214e7fe..ca64749 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/ManualTypeMarshallingHelper.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/ManualTypeMarshallingHelper.cs @@ -62,17 +62,17 @@ namespace Microsoft.Interop return false; var namedArguments = attr.NamedArguments.ToImmutableDictionary(); - CustomTypeMarshallerData? inMarshaller = GetNamedArgumentAsMarshallerData(namedArguments, MarshallersProperties.InMarshaller, MarshallingDirection.ManagedToUnmanaged, managedTypeOnAttr, compilation); - if (inMarshaller is null) - inMarshaller = GetMarshallerDataForType(entryPointType, MarshallingDirection.ManagedToUnmanaged, managedTypeOnAttr, compilation); + CustomTypeMarshallerData? inMarshaller = + GetNamedArgumentAsMarshallerData(namedArguments, MarshallersProperties.InMarshaller, MarshallingDirection.ManagedToUnmanaged, managedTypeOnAttr, compilation) ?? + GetMarshallerDataForType(entryPointType, MarshallingDirection.ManagedToUnmanaged, managedTypeOnAttr, compilation); - CustomTypeMarshallerData? refMarshaller = GetNamedArgumentAsMarshallerData(namedArguments, MarshallersProperties.RefMarshaller, MarshallingDirection.Bidirectional, managedTypeOnAttr, compilation); - if (refMarshaller is null) - refMarshaller = GetMarshallerDataForType(entryPointType, MarshallingDirection.Bidirectional, managedTypeOnAttr, compilation); + CustomTypeMarshallerData? refMarshaller = + GetNamedArgumentAsMarshallerData(namedArguments, MarshallersProperties.RefMarshaller, MarshallingDirection.Bidirectional, managedTypeOnAttr, compilation) ?? + GetMarshallerDataForType(entryPointType, MarshallingDirection.Bidirectional, managedTypeOnAttr, compilation); - CustomTypeMarshallerData? outMarshaller = GetNamedArgumentAsMarshallerData(namedArguments, MarshallersProperties.OutMarshaller, MarshallingDirection.UnmanagedToManaged, managedTypeOnAttr, compilation); - if (outMarshaller is null) - outMarshaller = GetMarshallerDataForType(entryPointType, MarshallingDirection.UnmanagedToManaged, managedTypeOnAttr, compilation); + CustomTypeMarshallerData? outMarshaller = + GetNamedArgumentAsMarshallerData(namedArguments, MarshallersProperties.OutMarshaller, MarshallingDirection.UnmanagedToManaged, managedTypeOnAttr, compilation) ?? + GetMarshallerDataForType(entryPointType, MarshallingDirection.UnmanagedToManaged, managedTypeOnAttr, compilation); if (inMarshaller is null && refMarshaller is null && outMarshaller is null) return false; diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/SerializationEventsCache.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/SerializationEventsCache.cs index a11b6f6..27b8a9a 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/SerializationEventsCache.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/SerializationEventsCache.cs @@ -42,7 +42,7 @@ namespace System.Runtime.Serialization // For each method find if attribute is present, the return type is void and the method is not virtual if (m.IsDefined(attribute, false)) { - if (mi == null) mi = new List(); + mi ??= new List(); mi.Add(m); } } diff --git a/src/libraries/System.Security.Claims/src/System/Security/Claims/Claim.cs b/src/libraries/System.Security.Claims/src/System/Security/Claims/Claim.cs index e192e601..6158716 100644 --- a/src/libraries/System.Security.Claims/src/System/Security/Claims/Claim.cs +++ b/src/libraries/System.Security.Claims/src/System/Security/Claims/Claim.cs @@ -341,17 +341,7 @@ namespace System.Security.Claims /// /// Gets the collection of Properties associated with the . /// - public IDictionary Properties - { - get - { - if (_properties == null) - { - _properties = new Dictionary(); - } - return _properties; - } - } + public IDictionary Properties => _properties ??= new Dictionary(); /// /// Gets the subject of the . diff --git a/src/libraries/System.Security.Claims/src/System/Security/Claims/ClaimsIdentity.cs b/src/libraries/System.Security.Claims/src/System/Security/Claims/ClaimsIdentity.cs index a0f3e6b..282c8fe 100644 --- a/src/libraries/System.Security.Claims/src/System/Security/Claims/ClaimsIdentity.cs +++ b/src/libraries/System.Security.Claims/src/System/Security/Claims/ClaimsIdentity.cs @@ -343,17 +343,7 @@ namespace System.Security.Claims /// Allow the association of claims with this instance of . /// The claims will not be serialized or added in Clone(). They will be included in searches, finds and returned from the call to . /// - internal List> ExternalClaims - { - get - { - if (_externalClaims == null) - { - _externalClaims = new List>(); - } - return _externalClaims; - } - } + internal List> ExternalClaims => _externalClaims ??= new List>(); /// /// Gets or sets the label for this diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12Builder.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12Builder.cs index 008cebd..a7cba21 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12Builder.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12Builder.cs @@ -57,10 +57,7 @@ namespace System.Security.Cryptography.Pkcs byte[] encrypted = safeContents.Encrypt(ReadOnlySpan.Empty, passwordBytes, pbeParameters); - if (_contents == null) - { - _contents = new List(); - } + _contents ??= new List(); _contents.Add( new ContentInfoAsn @@ -110,10 +107,7 @@ namespace System.Security.Cryptography.Pkcs byte[] encrypted = safeContents.Encrypt(password, ReadOnlySpan.Empty, pbeParameters); - if (_contents == null) - { - _contents = new List(); - } + _contents ??= new List(); _contents.Add( new ContentInfoAsn @@ -133,10 +127,7 @@ namespace System.Security.Cryptography.Pkcs if (IsSealed) throw new InvalidOperationException(SR.Cryptography_Pkcs12_PfxIsSealed); - if (_contents == null) - { - _contents = new List(); - } + _contents ??= new List(); _contents.Add(safeContents.EncodeToContentInfo()); } diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12CertBag.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12CertBag.cs index e0a2108..0c7eb16 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12CertBag.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12CertBag.cs @@ -62,10 +62,7 @@ namespace System.Security.Cryptography.Pkcs public Oid GetCertificateType() { - if (_certTypeOid == null) - { - _certTypeOid = new Oid(_decoded.CertId); - } + _certTypeOid ??= new Oid(_decoded.CertId); return _certTypeOid.CopyOid(); } diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SafeBag.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SafeBag.cs index e2dcd03..e9edb96 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SafeBag.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SafeBag.cs @@ -21,10 +21,7 @@ namespace System.Security.Cryptography.Pkcs { get { - if (_attributes == null) - { - _attributes = new CryptographicAttributeObjectCollection(); - } + _attributes ??= new CryptographicAttributeObjectCollection(); return _attributes; } @@ -56,10 +53,7 @@ namespace System.Security.Cryptography.Pkcs public Oid GetBagId() { - if (_bagOid == null) - { - _bagOid = new Oid(_bagIdValue); - } + _bagOid ??= new Oid(_bagIdValue); return _bagOid.CopyOid(); } diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SafeContents.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SafeContents.cs index e2f7666..bcf62d5 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SafeContents.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SafeContents.cs @@ -65,10 +65,7 @@ namespace System.Security.Cryptography.Pkcs if (IsReadOnly) throw new InvalidOperationException(SR.Cryptography_Pkcs12_SafeContentsIsReadOnly); - if (_bags == null) - { - _bags = new List(); - } + _bags ??= new List(); _bags.Add(safeBag); } @@ -360,10 +357,7 @@ namespace System.Security.Cryptography.Pkcs { } - if (bag == null) - { - bag = new Pkcs12SafeBag.UnknownBag(serializedBags[i].BagId, bagValue); - } + bag ??= new Pkcs12SafeBag.UnknownBag(serializedBags[i].BagId, bagValue); bag.Attributes = SignerInfo.MakeAttributeCollection(serializedBags[i].BagAttributes); bags.Add(bag); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SecretBag.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SecretBag.cs index 7709f27..c214def 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SecretBag.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SecretBag.cs @@ -36,10 +36,7 @@ namespace System.Security.Cryptography.Pkcs public Oid GetSecretType() { - if (_secretTypeOid == null) - { - _secretTypeOid = new Oid(_decoded.SecretTypeId); - } + _secretTypeOid ??= new Oid(_decoded.SecretTypeId); return _secretTypeOid.CopyOid(); } 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 a677fcd..2ee1049 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 @@ -58,48 +58,18 @@ namespace System.Security.Cryptography.Pkcs _document = ownerDocument; } - public CryptographicAttributeObjectCollection SignedAttributes - { - get - { - if (_parsedSignedAttrs == null) - { - _parsedSignedAttrs = MakeAttributeCollection(_signedAttributes); - } - - return _parsedSignedAttrs; - } - } - - public CryptographicAttributeObjectCollection UnsignedAttributes - { - get - { - if (_parsedUnsignedAttrs == null) - { - _parsedUnsignedAttrs = MakeAttributeCollection(_unsignedAttributes); - } + public CryptographicAttributeObjectCollection SignedAttributes => + _parsedSignedAttrs ??= MakeAttributeCollection(_signedAttributes); - return _parsedUnsignedAttrs; - } - } + public CryptographicAttributeObjectCollection UnsignedAttributes => + _parsedUnsignedAttrs ??= MakeAttributeCollection(_unsignedAttributes); internal ReadOnlyMemory GetSignatureMemory() => _signature; public byte[] GetSignature() => _signature.ToArray(); - public X509Certificate2? Certificate - { - get - { - if (_signerCertificate == null) - { - _signerCertificate = FindSignerCertificate(); - } - - return _signerCertificate; - } - } + public X509Certificate2? Certificate => + _signerCertificate ??= FindSignerCertificate(); public SignerInfoCollection CounterSignerInfos { 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 4d8d96a..47f374e 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 @@ -15,13 +15,7 @@ namespace System.Security.Cryptography.Xml public string Recipient { - get - { - // an unspecified value for an XmlAttribute is string.Empty - if (_recipient == null) - _recipient = string.Empty; - return _recipient; - } + get => _recipient ??= string.Empty; // an unspecified value for an XmlAttribute is string.Empty set { _recipient = value; @@ -39,15 +33,7 @@ namespace System.Security.Cryptography.Xml } } - public ReferenceList ReferenceList - { - get - { - if (_referenceList == null) - _referenceList = new ReferenceList(); - return _referenceList; - } - } + public ReferenceList ReferenceList => _referenceList ??= new ReferenceList(); public void AddReference(DataReference dataReference) { 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 e8e282f..315e5ea 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 @@ -41,12 +41,7 @@ namespace System.Security.Cryptography.Xml public TransformChain TransformChain { - get - { - if (_transformChain == null) - _transformChain = new TransformChain(); - return _transformChain; - } + get => _transformChain ??= new TransformChain(); set { _transformChain = value; diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedType.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedType.cs index 2e5680f..61c5339 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedType.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedType.cs @@ -67,13 +67,8 @@ namespace System.Security.Cryptography.Xml public KeyInfo KeyInfo { - get - { - if (_keyInfo == null) - _keyInfo = new KeyInfo(); - return _keyInfo; - } - set { _keyInfo = value; } + get => _keyInfo ??= new KeyInfo(); + set => _keyInfo = value; } public virtual EncryptionMethod EncryptionMethod @@ -86,15 +81,7 @@ namespace System.Security.Cryptography.Xml } } - public virtual EncryptionPropertyCollection EncryptionProperties - { - get - { - if (_props == null) - _props = new EncryptionPropertyCollection(); - return _props; - } - } + public virtual EncryptionPropertyCollection EncryptionProperties => _props ??= new EncryptionPropertyCollection(); public void AddProperty(EncryptionProperty ep) { @@ -103,13 +90,7 @@ namespace System.Security.Cryptography.Xml public virtual CipherData CipherData { - get - { - if (_cipherData == null) - _cipherData = new CipherData(); - - return _cipherData; - } + get => _cipherData ??= new CipherData(); set { if (value == null) 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 4be3199..537d1a5 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 @@ -164,14 +164,8 @@ namespace System.Security.Cryptography.Xml // when an EncyptedData references an EncryptedKey using a CarriedKeyName and Recipient public string Recipient { - get - { - // an unspecified value for an XmlAttribute is string.Empty - if (_recipient == null) - _recipient = string.Empty; - return _recipient; - } - set { _recipient = value; } + get => _recipient ??= string.Empty; // an unspecified value for an XmlAttribute is string.Empty + set => _recipient = value; } // 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 d56ce81..81bad80 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 @@ -99,8 +99,7 @@ namespace System.Security.Cryptography.Xml KeyInfoClause keyInfoClause = CryptoHelpers.CreateFromName(kicString); // if we don't know what kind of KeyInfoClause we're looking at, use a generic KeyInfoNode: - if (keyInfoClause == null) - keyInfoClause = new KeyInfoNode(); + keyInfoClause ??= new KeyInfoNode(); // Ask the create clause to fill itself with the corresponding XML keyInfoClause.LoadXml(elem); 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 53104e7..f92b4db 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 @@ -109,8 +109,7 @@ namespace System.Security.Cryptography.Xml throw new ArgumentNullException(nameof(certificate)); } - if (_certificates == null) - _certificates = new ArrayList(); + _certificates ??= new ArrayList(); X509Certificate2 x509 = new X509Certificate2(certificate); _certificates.Add(x509); @@ -123,15 +122,13 @@ namespace System.Security.Cryptography.Xml public void AddSubjectKeyId(byte[] subjectKeyId) { - if (_subjectKeyIds == null) - _subjectKeyIds = new ArrayList(); + _subjectKeyIds ??= new ArrayList(); _subjectKeyIds.Add(subjectKeyId); } public void AddSubjectKeyId(string subjectKeyId) { - if (_subjectKeyIds == null) - _subjectKeyIds = new ArrayList(); + _subjectKeyIds ??= new ArrayList(); _subjectKeyIds.Add(Utils.DecodeHexString(subjectKeyId)); } @@ -142,8 +139,7 @@ namespace System.Security.Cryptography.Xml public void AddSubjectName(string subjectName) { - if (_subjectNames == null) - _subjectNames = new ArrayList(); + _subjectNames ??= new ArrayList(); _subjectNames.Add(subjectName); } @@ -164,16 +160,14 @@ namespace System.Security.Cryptography.Xml if (!BigInteger.TryParse(serialNumber, NumberStyles.AllowHexSpecifier, NumberFormatInfo.CurrentInfo, out h)) throw new ArgumentException(SR.Cryptography_Xml_InvalidX509IssuerSerialNumber, nameof(serialNumber)); - if (_issuerSerials == null) - _issuerSerials = new ArrayList(); + _issuerSerials ??= new ArrayList(); _issuerSerials.Add(Utils.CreateX509IssuerSerial(issuerName, h.ToString())); } // When we load an X509Data from Xml, we know the serial number is in decimal representation. internal void InternalAddIssuerSerial(string issuerName, string serialNumber) { - if (_issuerSerials == null) - _issuerSerials = new ArrayList(); + _issuerSerials ??= new ArrayList(); _issuerSerials.Add(Utils.CreateX509IssuerSerial(issuerName, serialNumber)); } 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 6cad039..32a7cc4 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 @@ -117,12 +117,7 @@ namespace System.Security.Cryptography.Xml public TransformChain TransformChain { - get - { - if (_transformChain == null) - _transformChain = new TransformChain(); - return _transformChain; - } + get => _transformChain ??= new TransformChain(); set { _transformChain = 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 ac61737..e88334f 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 @@ -62,13 +62,8 @@ namespace System.Security.Cryptography.Xml public KeyInfo KeyInfo { - get - { - if (_keyInfo == null) - _keyInfo = new KeyInfo(); - return _keyInfo; - } - set { _keyInfo = value; } + get => _keyInfo ??= new KeyInfo(); + set => _keyInfo = value; } public IList ObjectList 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 c2d6881..a717789 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 @@ -168,13 +168,8 @@ namespace System.Security.Cryptography.Xml public EncryptedXml EncryptedXml { - get - { - if (_exml == null) - _exml = new EncryptedXml(_containingDocument); // default processing rules - return _exml; - } - set { _exml = value; } + get => _exml ??= new EncryptedXml(_containingDocument); // default processing rules + set => _exml = value; } public Signature Signature @@ -226,10 +221,7 @@ namespace System.Security.Cryptography.Xml m_signature.LoadXml(value); - if (_context == null) - { - _context = value; - } + _context ??= value; _bCacheValid = false; } @@ -399,8 +391,7 @@ namespace System.Security.Cryptography.Xml else if (key is RSA) { // Default to RSA-SHA256 - if (SignedInfo.SignatureMethod == null) - SignedInfo.SignatureMethod = XmlDsigRSASHA256Url; + SignedInfo.SignatureMethod ??= XmlDsigRSASHA256Url; } else { @@ -482,31 +473,29 @@ namespace System.Security.Cryptography.Xml return key; } - if (_keyInfoEnum == null) - _keyInfoEnum = KeyInfo.GetEnumerator(); + _keyInfoEnum ??= KeyInfo.GetEnumerator(); // In our implementation, we move to the next KeyInfo clause which is an RSAKeyValue, DSAKeyValue or KeyInfoX509Data while (_keyInfoEnum.MoveNext()) { - RSAKeyValue rsaKeyValue = _keyInfoEnum.Current as RSAKeyValue; - if (rsaKeyValue != null) - return rsaKeyValue.Key; + switch (_keyInfoEnum.Current) + { + case RSAKeyValue rsaKeyValue: + return rsaKeyValue.Key; - DSAKeyValue dsaKeyValue = _keyInfoEnum.Current as DSAKeyValue; - if (dsaKeyValue != null) - return dsaKeyValue.Key; + case DSAKeyValue dsaKeyValue: + return dsaKeyValue.Key; - KeyInfoX509Data x509Data = _keyInfoEnum.Current as KeyInfoX509Data; - if (x509Data != null) - { - _x509Collection = Utils.BuildBagOfCerts(x509Data, CertUsageType.Verification); - if (_x509Collection.Count > 0) - { - _x509Enum = _x509Collection.GetEnumerator(); - AsymmetricAlgorithm key = GetNextCertificatePublicKey(); - if (key != null) - return key; - } + case KeyInfoX509Data x509Data: + _x509Collection = Utils.BuildBagOfCerts(x509Data, CertUsageType.Verification); + if (_x509Collection.Count > 0) + { + _x509Enum = _x509Collection.GetEnumerator(); + AsymmetricAlgorithm key = GetNextCertificatePublicKey(); + if (key != null) + return key; + } + break; } } @@ -520,9 +509,10 @@ namespace System.Security.Cryptography.Xml { foreach (KeyInfoClause clause in KeyInfo) { - KeyInfoX509Data x509Data = clause as KeyInfoX509Data; - if (x509Data != null) + if (clause is KeyInfoX509Data x509Data) + { collection.AddRange(Utils.BuildBagOfCerts(x509Data, CertUsageType.Verification)); + } } } @@ -901,8 +891,7 @@ namespace System.Security.Cryptography.Xml foreach (Reference reference in sortedReferences) { // If no DigestMethod has yet been set, default it to sha1 - if (reference.DigestMethod == null) - reference.DigestMethod = Reference.DefaultDigestMethod; + reference.DigestMethod ??= Reference.DefaultDigestMethod; SignedXmlDebugLog.LogSigningReference(this, reference); 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 513b1a8..6920c73 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 @@ -26,15 +26,7 @@ namespace System.Security.Cryptography.Xml Algorithm = SignedXml.XmlDecryptionTransformUrl; } - private ArrayList ExceptUris - { - get - { - if (_arrayListUri == null) - _arrayListUri = new ArrayList(); - return _arrayListUri; - } - } + private ArrayList ExceptUris => _arrayListUri ??= new ArrayList(); protected virtual bool IsTargetElement(XmlElement inputElement, string idValue) { 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 429f925..996a9fb 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 @@ -179,10 +179,7 @@ namespace System.Security.Cryptography.Xml { if (type == typeof(XmlNodeList) || type.IsSubclassOf(typeof(XmlNodeList))) { - if (_inputNodeList == null) - { - _inputNodeList = Utils.AllDescendantNodes(_containingDocument, true); - } + _inputNodeList ??= Utils.AllDescendantNodes(_containingDocument, true); return (XmlNodeList)GetOutput(); } else if (type == typeof(XmlDocument) || type.IsSubclassOf(typeof(XmlDocument))) diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CapiHelper.Windows.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CapiHelper.Windows.cs index 9357680..53ad764 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CapiHelper.Windows.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CapiHelper.Windows.cs @@ -1032,9 +1032,7 @@ namespace System.Security.Cryptography if (nameOrOid == null) return CapiHelper.CALG_SHA1; - string? oidValue = CryptoConfig.MapNameToOID(nameOrOid); - if (oidValue == null) - oidValue = nameOrOid; // we were probably passed an OID value directly + string oidValue = CryptoConfig.MapNameToOID(nameOrOid) ?? nameOrOid; // we were probably passed an OID value directly int algId = GetAlgIdFromOid(oidValue, oidGroup); if (algId == 0 || algId == -1) diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.Create.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.Create.cs index 550b4ce..e184e13 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.Create.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.Create.cs @@ -36,8 +36,7 @@ namespace System.Security.Cryptography { ArgumentNullException.ThrowIfNull(algorithm); - if (creationParameters == null) - creationParameters = new CngKeyCreationParameters(); + creationParameters ??= new CngKeyCreationParameters(); SafeNCryptProviderHandle providerHandle = creationParameters.Provider!.OpenStorageProvider(); SafeNCryptKeyHandle keyHandle; diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/Oid.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/Oid.cs index e53b628..68b0889 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/Oid.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/Oid.cs @@ -15,12 +15,7 @@ namespace System.Security.Cryptography public Oid(string oid) { // If we were passed the friendly name, retrieve the value String. - string? oidValue = OidLookup.ToOid(oid, OidGroup.All, fallBackToAllGroups: false); - if (oidValue == null) - { - oidValue = oid; - } - this.Value = oidValue; + this.Value = OidLookup.ToOid(oid, OidGroup.All, fallBackToAllGroups: false) ?? oid; _group = OidGroup.All; } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/OidCollection.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/OidCollection.cs index 25ced97..945918a 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/OidCollection.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/OidCollection.cs @@ -45,11 +45,7 @@ namespace System.Security.Cryptography get { // If we were passed the friendly name, retrieve the value String. - string? oidValue = OidLookup.ToOid(oid, OidGroup.All, fallBackToAllGroups: false); - if (oidValue == null) - { - oidValue = oid; - } + string? oidValue = OidLookup.ToOid(oid, OidGroup.All, fallBackToAllGroups: false) ?? oid; for (int i = 0; i < _count; i++) { Oid entry = _oids[i]; diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/PasswordDeriveBytes.Windows.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/PasswordDeriveBytes.Windows.cs index 51b244f..f5ee38e 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/PasswordDeriveBytes.Windows.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/PasswordDeriveBytes.Windows.cs @@ -55,10 +55,7 @@ namespace System.Security.Cryptography private static SafeProvHandle AcquireSafeProviderHandle(CspParameters? cspParams) { - if (cspParams == null) - { - cspParams = new CspParameters(CapiHelper.DefaultRsaProviderType); - } + cspParams ??= new CspParameters(CapiHelper.DefaultRsaProviderType); CapiHelper.AcquireCsp(cspParams, out SafeProvHandle safeProvHandle); return safeProvHandle; diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SHAHashProvider.Browser.Managed.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SHAHashProvider.Browser.Managed.cs index 574cdf8..cfa39e5 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SHAHashProvider.Browser.Managed.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SHAHashProvider.Browser.Managed.cs @@ -42,10 +42,7 @@ namespace System.Security.Cryptography public override void AppendHashData(ReadOnlySpan data) { - if (buffer == null) - { - buffer = new MemoryStream(1000); - } + buffer ??= new MemoryStream(1000); buffer.Write(data); } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/CertificateData.ManagedDecode.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/CertificateData.ManagedDecode.cs index c62dc60..c35b33b 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/CertificateData.ManagedDecode.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/CertificateData.ManagedDecode.cs @@ -243,11 +243,7 @@ namespace System.Security.Cryptography.X509Certificates e = value; break; default: - if (firstRdn == null) - { - firstRdn = value; - } - + firstRdn ??= value; break; } } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/ChainPal.Android.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/ChainPal.Android.cs index 3096f31..ba5e813 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/ChainPal.Android.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/ChainPal.Android.cs @@ -317,10 +317,7 @@ namespace System.Security.Cryptography.X509Certificates AddUniqueStatus(overallStatus, ref statusToSet); for (int i = index; i >= 0; i--) { - if (statuses[i] == null) - { - statuses[i] = new List(); - } + statuses[i] ??= new List(); AddUniqueStatus(statuses[i], ref statusToSet); } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/OpenSslX509ChainProcessor.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/OpenSslX509ChainProcessor.cs index 0b1d6dd..780262e 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/OpenSslX509ChainProcessor.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/OpenSslX509ChainProcessor.cs @@ -262,10 +262,7 @@ namespace System.Security.Cryptography.X509Certificates break; } - if (downloadedCerts == null) - { - downloadedCerts = new List(); - } + downloadedCerts ??= new List(); AddToStackAndUpRef(downloaded.Handle, _untrustedLookup); downloadedCerts.Add(downloaded); @@ -917,10 +914,7 @@ namespace System.Security.Cryptography.X509Certificates if (failsPolicyChecks) { - if (overallStatus == null) - { - overallStatus = new List(); - } + overallStatus ??= new List(); X509ChainStatus chainStatus = new X509ChainStatus { diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/UnixPkcs12Reader.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/UnixPkcs12Reader.cs index f7454d5..a9a89f6 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/UnixPkcs12Reader.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/UnixPkcs12Reader.cs @@ -275,10 +275,7 @@ namespace System.Security.Cryptography.X509Certificates private void Decrypt(ReadOnlySpan password, ReadOnlyMemory authSafeContents) { - if (_safeContentsValues == null) - { - _safeContentsValues = DecodeSafeContents(authSafeContents); - } + _safeContentsValues ??= DecodeSafeContents(authSafeContents); // The average PFX contains one cert, and one key. // The next most common PFX contains 3 certs, and one key. diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X500DistinguishedName.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X500DistinguishedName.cs index 1da4b68..90c4aee 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X500DistinguishedName.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X500DistinguishedName.cs @@ -45,18 +45,7 @@ namespace System.Security.Cryptography.X509Certificates _lazyDistinguishedName = distinguishedName; } - public string Name - { - get - { - string? name = _lazyDistinguishedName; - if (name == null) - { - name = _lazyDistinguishedName = Decode(X500DistinguishedNameFlags.Reversed); - } - return name; - } - } + public string Name => _lazyDistinguishedName ??= Decode(X500DistinguishedNameFlags.Reversed); public string Decode(X500DistinguishedNameFlags flag) { diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Certificate2.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Certificate2.cs index 4cfddb4..072923e 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Certificate2.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Certificate2.cs @@ -260,19 +260,16 @@ namespace System.Security.Cryptography.X509Certificates if (!HasPrivateKey) return null; - if (_lazyPrivateKey == null) + _lazyPrivateKey ??= GetKeyAlgorithm() switch { - _lazyPrivateKey = GetKeyAlgorithm() switch - { - Oids.Rsa => Pal.GetRSAPrivateKey(), - Oids.Dsa => Pal.GetDSAPrivateKey(), - - // This includes ECDSA, because an Oids.EcPublicKey key can be - // many different algorithm kinds, not necessarily with mutual exclusion. - // Plus, .NET Framework only supports RSA and DSA in this property. - _ => throw new NotSupportedException(SR.NotSupported_KeyAlgorithm), - }; - } + Oids.Rsa => Pal.GetRSAPrivateKey(), + Oids.Dsa => Pal.GetDSAPrivateKey(), + + // This includes ECDSA, because an Oids.EcPublicKey key can be + // many different algorithm kinds, not necessarily with mutual exclusion. + // Plus, .NET Framework only supports RSA and DSA in this property. + _ => throw new NotSupportedException(SR.NotSupported_KeyAlgorithm), + }; return _lazyPrivateKey; } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Chain.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Chain.cs index 7a9286a..e7b5cb1 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Chain.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Chain.cs @@ -37,24 +37,11 @@ namespace System.Security.Cryptography.X509Certificates return new X509Chain(); } - public X509ChainElementCollection ChainElements - { - get - { - if (_chainElements == null) - _chainElements = new X509ChainElementCollection(); - return _chainElements; - } - } + public X509ChainElementCollection ChainElements => _chainElements ??= new X509ChainElementCollection(); public X509ChainPolicy ChainPolicy { - get - { - if (_chainPolicy == null) - _chainPolicy = new X509ChainPolicy(); - return _chainPolicy; - } + get => _chainPolicy ??= new X509ChainPolicy(); set { ArgumentNullException.ThrowIfNull(value); @@ -67,10 +54,7 @@ namespace System.Security.Cryptography.X509Certificates get { // We give the user a reference to the array since we'll never access it. - X509ChainStatus[]? chainStatus = _lazyChainStatus; - if (chainStatus == null) - chainStatus = _lazyChainStatus = (_pal == null ? Array.Empty() : _pal.ChainStatus!); - return chainStatus; + return _lazyChainStatus ??= (_pal == null ? Array.Empty() : _pal.ChainStatus!); } } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509SignatureGenerator.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509SignatureGenerator.cs index 0ba24b4..e493ab5 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509SignatureGenerator.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509SignatureGenerator.cs @@ -7,18 +7,7 @@ namespace System.Security.Cryptography.X509Certificates { private PublicKey? _publicKey; - public PublicKey PublicKey - { - get - { - if (_publicKey == null) - { - _publicKey = BuildPublicKey(); - } - - return _publicKey; - } - } + public PublicKey PublicKey => _publicKey ??= BuildPublicKey(); public abstract byte[] GetSignatureAlgorithmIdentifier(HashAlgorithmName hashAlgorithm); public abstract byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/XmlKeyHelper.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/XmlKeyHelper.cs index 4121e19..d8e3947 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/XmlKeyHelper.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/XmlKeyHelper.cs @@ -202,10 +202,7 @@ namespace System.Security.Cryptography return null; } - if (_enumerator == null) - { - _enumerator = _enumerable.GetEnumerator(); - } + _enumerator ??= _enumerable.GetEnumerator(); int origIdx = _index; int idx = origIdx; 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 848efb5..060fd7b 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 @@ -161,8 +161,7 @@ namespace System.Security.Permissions } if (addToNewIDRoles) { - if (idroles == null) - idroles = new List(); + idroles ??= new List(); idroles.Add(new IDRole(newAuthenticated, newID, newRole)); } } diff --git a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/IdentityNotMappedException.cs b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/IdentityNotMappedException.cs index 5cfa788..b9f353f 100644 --- a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/IdentityNotMappedException.cs +++ b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/IdentityNotMappedException.cs @@ -41,16 +41,6 @@ namespace System.Security.Principal base.GetObjectData(serializationInfo, streamingContext); } - public IdentityReferenceCollection UnmappedIdentities - { - get - { - if (_unmappedIdentities == null) - { - _unmappedIdentities = new IdentityReferenceCollection(); - } - return _unmappedIdentities; - } - } + public IdentityReferenceCollection UnmappedIdentities => _unmappedIdentities ??= new IdentityReferenceCollection(); } } diff --git a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/WindowsIdentity.cs b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/WindowsIdentity.cs index 1a21a72..3eca69a 100644 --- a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/WindowsIdentity.cs +++ b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/WindowsIdentity.cs @@ -429,13 +429,11 @@ namespace System.Security.Principal { if (_isAuthenticated == -1) { - if (s_authenticatedUserRid is null) - { - s_authenticatedUserRid = new SecurityIdentifier( - IdentifierAuthority.NTAuthority, - new int[] { Interop.SecurityIdentifier.SECURITY_AUTHENTICATED_USER_RID } - ); - } + s_authenticatedUserRid ??= new SecurityIdentifier( + IdentifierAuthority.NTAuthority, + new int[] { Interop.SecurityIdentifier.SECURITY_AUTHENTICATED_USER_RID } + ); + // This approach will not work correctly for domain guests (will return false // instead of true). This is a corner-case that is not very interesting. _isAuthenticated = CheckNtTokenForSid(s_authenticatedUserRid) ? 1 : 0; @@ -502,13 +500,10 @@ namespace System.Security.Principal if (_safeTokenHandle.IsInvalid) return false; - if (s_domainRid is null) - { - s_domainRid = new SecurityIdentifier( - IdentifierAuthority.NTAuthority, - new int[] { Interop.SecurityIdentifier.SECURITY_BUILTIN_DOMAIN_RID, (int)WindowsBuiltInRole.Guest } - ); - } + s_domainRid ??= new SecurityIdentifier( + IdentifierAuthority.NTAuthority, + new int[] { Interop.SecurityIdentifier.SECURITY_BUILTIN_DOMAIN_RID, (int)WindowsBuiltInRole.Guest } + ); return CheckNtTokenForSid(s_domainRid); } @@ -522,13 +517,10 @@ namespace System.Security.Principal if (_safeTokenHandle.IsInvalid) return false; - if (s_localSystemRid is null) - { - s_localSystemRid = new SecurityIdentifier( - IdentifierAuthority.NTAuthority, - new int[] { Interop.SecurityIdentifier.SECURITY_LOCAL_SYSTEM_RID } - ); - } + s_localSystemRid ??= new SecurityIdentifier( + IdentifierAuthority.NTAuthority, + new int[] { Interop.SecurityIdentifier.SECURITY_LOCAL_SYSTEM_RID } + ); return User == s_localSystemRid; } @@ -542,13 +534,10 @@ namespace System.Security.Principal if (_safeTokenHandle.IsInvalid) return true; - if (s_anonymousRid is null) - { - s_anonymousRid = new SecurityIdentifier( - IdentifierAuthority.NTAuthority, - new int[] { Interop.SecurityIdentifier.SECURITY_ANONYMOUS_LOGON_RID } - ); - } + s_anonymousRid ??= new SecurityIdentifier( + IdentifierAuthority.NTAuthority, + new int[] { Interop.SecurityIdentifier.SECURITY_ANONYMOUS_LOGON_RID } + ); return User == s_anonymousRid; } 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 2050b17..ec4388d 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 @@ -582,10 +582,7 @@ namespace System.ServiceModel.Syndication if (preserveAttributeExtensions) { string value = reader.Value; - if (attrs == null) - { - attrs = new Dictionary(); - } + attrs ??= new Dictionary(); attrs.Add(new XmlQualifiedName(name, ns), value); } } 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 b37e04b..a679681 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 @@ -221,10 +221,7 @@ namespace System.ServiceModel.Syndication { SyndicationCategory category = CreateCategory(inlineCategories); Atom10FeedFormatter.ReadCategory(reader, category, version, preserveAttributeExtensions: true, preserveElementExtensions: true, maxExtensionSize); - if (category.Scheme == null) - { - category.Scheme = inlineCategories.Scheme; - } + category.Scheme ??= inlineCategories.Scheme; inlineCategories.Categories.Add(category); } else if (!TryParseElement(reader, inlineCategories, version)) 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 c645a58..31e669a 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 @@ -124,14 +124,7 @@ namespace System.ServiceModel.Syndication _extensions.LoadElementExtensions(buffer); } - private static IEnumerable CreateSingleEmptyAccept() - { - if (s_singleEmptyAccept == null) - { - s_singleEmptyAccept = new List(1) { string.Empty }.AsReadOnly(); - } - - return s_singleEmptyAccept; - } + private static IEnumerable CreateSingleEmptyAccept() => + s_singleEmptyAccept ??= new List(1) { string.Empty }.AsReadOnly(); } } 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 980318e..8baf3c9 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 @@ -1004,10 +1004,7 @@ namespace System.ServiceModel.Syndication { if (item.Links[i].RelationshipType == Atom10Constants.AlternateTag) { - if (firstAlternateLink == null) - { - firstAlternateLink = item.Links[i]; - } + firstAlternateLink ??= item.Links[i]; if (guid == FeedUtils.GetUriString(item.Links[i].Uri)) { isPermalink = true; 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 df531ef..5829235 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 @@ -67,10 +67,7 @@ namespace System.ServiceModel.Syndication throw new ArgumentException(SR.OuterNameOfElementExtensionEmpty, nameof(outerName)); } - if (dataContractSerializer == null) - { - dataContractSerializer = new DataContractSerializer(dataContractExtension.GetType()); - } + dataContractSerializer ??= new DataContractSerializer(dataContractExtension.GetType()); _outerName = outerName; _outerNamespace = outerNamespace; _extensionData = dataContractExtension; @@ -84,10 +81,7 @@ namespace System.ServiceModel.Syndication throw new ArgumentNullException(nameof(xmlSerializerExtension)); } - if (serializer == null) - { - serializer = new XmlSerializer(xmlSerializerExtension.GetType()); - } + serializer ??= new XmlSerializer(xmlSerializerExtension.GetType()); _extensionData = xmlSerializerExtension; _extensionDataWriter = new ExtensionDataWriter(_extensionData, serializer); } 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 3188e57..f3a4d74 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 @@ -68,10 +68,7 @@ namespace System.ServiceModel.Syndication throw new ArgumentNullException(nameof(dataContractExtension)); } - if (dataContractSerializer == null) - { - dataContractSerializer = new DataContractSerializer(dataContractExtension.GetType()); - } + dataContractSerializer ??= new DataContractSerializer(dataContractExtension.GetType()); base.Add(new SyndicationElementExtension(outerName, outerNamespace, dataContractExtension, dataContractSerializer)); } @@ -82,10 +79,7 @@ namespace System.ServiceModel.Syndication throw new ArgumentNullException(nameof(xmlSerializerExtension)); } - if (serializer == null) - { - serializer = new XmlSerializer(xmlSerializerExtension.GetType()); - } + serializer ??= new XmlSerializer(xmlSerializerExtension.GetType()); base.Add(new SyndicationElementExtension(xmlSerializerExtension, serializer)); } @@ -250,10 +244,7 @@ namespace System.ServiceModel.Syndication Debug.Assert((dcSerializer == null) != (xmlSerializer == null), "exactly one serializer should be supplied"); // normalize the null and empty namespace - if (extensionNamespace == null) - { - extensionNamespace = string.Empty; - } + extensionNamespace ??= string.Empty; Collection results = new Collection(); for (int i = 0; i < Count; ++i) { 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 e7ba697..c9b5d43 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 @@ -100,10 +100,7 @@ namespace System.ServiceModel.Syndication public TContent ReadContent(XmlObjectSerializer dataContractSerializer) { - if (dataContractSerializer == null) - { - dataContractSerializer = new DataContractSerializer(typeof(TContent)); - } + dataContractSerializer ??= new DataContractSerializer(typeof(TContent)); if (Extension != null) { return Extension.GetObject(dataContractSerializer); @@ -122,10 +119,7 @@ namespace System.ServiceModel.Syndication public TContent ReadContent(XmlSerializer serializer) { - if (serializer == null) - { - serializer = new XmlSerializer(typeof(TContent)); - } + serializer ??= new XmlSerializer(typeof(TContent)); if (Extension != null) { return Extension.GetObject(serializer); diff --git a/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceBase.cs b/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceBase.cs index 09df969..ddc3e2e 100644 --- a/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceBase.cs +++ b/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceBase.cs @@ -249,21 +249,11 @@ namespace System.ServiceProcess /// can be used to write notification of service command calls, such as Start and Stop, to the Application event log. This property is read-only. /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public virtual EventLog EventLog - { - get + public virtual EventLog EventLog => + _eventLog ??= new EventLog("Application") { - if (_eventLog == null) - { - _eventLog = new EventLog("Application") - { - Source = ServiceName - }; - } - - return _eventLog; - } - } + Source = ServiceName + }; [EditorBrowsable(EditorBrowsableState.Advanced)] protected IntPtr ServiceHandle 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 088c41c..017c75c 100644 --- a/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceController.cs +++ b/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceController.cs @@ -652,10 +652,7 @@ namespace System.ServiceProcess } // get a handle to SCM with connect access and store it in serviceManagerHandle field. - if (_serviceManagerHandle == null) - { - _serviceManagerHandle = GetDataBaseHandleWithAccess(_machineName, Interop.Advapi32.ServiceControllerOptions.SC_MANAGER_CONNECT); - } + _serviceManagerHandle ??= GetDataBaseHandleWithAccess(_machineName, Interop.Advapi32.ServiceControllerOptions.SC_MANAGER_CONNECT); } /// diff --git a/src/libraries/System.Speech/src/Recognition/Grammar.cs b/src/libraries/System.Speech/src/Recognition/Grammar.cs index 0f57d4c..7a3135d 100644 --- a/src/libraries/System.Speech/src/Recognition/Grammar.cs +++ b/src/libraries/System.Speech/src/Recognition/Grammar.cs @@ -257,15 +257,7 @@ namespace System.Speech.Recognition public string Name { get { return _grammarName; } - set - { -#pragma warning disable 6507 -#pragma warning disable 6526 - if (value == null) { value = string.Empty; } - _grammarName = value; -#pragma warning restore 6507 -#pragma warning restore 6526 - } + set { _grammarName = value ?? string.Empty; } } public string RuleName { diff --git a/src/libraries/System.Speech/src/Recognition/RecognizerBase.cs b/src/libraries/System.Speech/src/Recognition/RecognizerBase.cs index 7754e73..c91a07e 100644 --- a/src/libraries/System.Speech/src/Recognition/RecognizerBase.cs +++ b/src/libraries/System.Speech/src/Recognition/RecognizerBase.cs @@ -296,8 +296,8 @@ ISpGrammarResourceLoader void IRecognizerInternal.SetDictationContext(Grammar grammar, string precedingText, string subsequentText) { - if (precedingText == null) { precedingText = string.Empty; } - if (subsequentText == null) { subsequentText = string.Empty; } + precedingText ??= string.Empty; + subsequentText ??= string.Empty; SPTEXTSELECTIONINFO selectionInfo = new(0, 0, (uint)precedingText.Length, 0); string textString = precedingText + subsequentText + "\0\0"; diff --git a/src/libraries/System.Speech/src/Synthesis/VoiceInfo.cs b/src/libraries/System.Speech/src/Synthesis/VoiceInfo.cs index d68ccd6..10f432b 100644 --- a/src/libraries/System.Speech/src/Synthesis/VoiceInfo.cs +++ b/src/libraries/System.Speech/src/Synthesis/VoiceInfo.cs @@ -201,16 +201,7 @@ namespace System.Speech.Synthesis } } [EditorBrowsable(EditorBrowsableState.Advanced)] - public IDictionary AdditionalInfo - { - get - { - if (_attributes == null) - _attributes = new ReadOnlyDictionary(new Dictionary(0)); - return _attributes; - } - } - + public IDictionary AdditionalInfo => _attributes ??= new ReadOnlyDictionary(new Dictionary(0)); #endregion #region Internal Methods diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DecoderBestFitFallback.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DecoderBestFitFallback.cs index 846da4c..571aa1f 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DecoderBestFitFallback.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DecoderBestFitFallback.cs @@ -72,8 +72,7 @@ namespace System.Text lock (InternalSyncObject) { // Double check before we do it again. - if (_oFallback.arrayBestFit == null) - _oFallback.arrayBestFit = fallback.encoding.GetBestFitBytesToUnicodeData(); + _oFallback.arrayBestFit ??= fallback.encoding.GetBestFitBytesToUnicodeData(); } } } diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncoderBestFitFallback.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncoderBestFitFallback.cs index e232be8..95a038e 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncoderBestFitFallback.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncoderBestFitFallback.cs @@ -72,8 +72,7 @@ namespace System.Text lock (InternalSyncObject) { // Double check before we do it again. - if (_oFallback.arrayBestFit == null) - _oFallback.arrayBestFit = fallback.encoding.GetBestFitUnicodeToBytesData(); + _oFallback.arrayBestFit ??= fallback.encoding.GetBestFitUnicodeToBytesData(); } } } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/BitStack.cs b/src/libraries/System.Text.Json/src/System/Text/Json/BitStack.cs index 12255d9..40d70a5 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/BitStack.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/BitStack.cs @@ -60,10 +60,7 @@ namespace System.Text.Json [MethodImpl(MethodImplOptions.NoInlining)] private void PushToArray(bool value) { - if (_array == null) - { - _array = new int[DefaultInitialArraySize]; - } + _array ??= new int[DefaultInitialArraySize]; int index = _currentDepth - AllocationFreeMaxDepth; 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 decf879..fef9b48 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 @@ -108,11 +108,7 @@ namespace System.Text.Json.Nodes } else { - JsonNode? jNode = value as JsonNode; - if (jNode == null) - { - jNode = new JsonValueNotTrimmable(value); - } + JsonNode jNode = value as JsonNode ?? new JsonValueNotTrimmable(value); // Call the IList.Add() implementation. Add(jNode); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/IgnoreReferenceResolver.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/IgnoreReferenceResolver.cs index 53a13a2..c9a66ed 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/IgnoreReferenceResolver.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/IgnoreReferenceResolver.cs @@ -24,10 +24,7 @@ namespace System.Text.Json.Serialization { var wrappedValue = new ReferenceEqualsWrapper(value); - if (_stackForCycleDetection is null) - { - _stackForCycleDetection = new Stack(); - } + _stackForCycleDetection ??= new Stack(); Debug.Assert(!_stackForCycleDetection.Contains(wrappedValue)); _stackForCycleDetection.Push(wrappedValue); 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 ff47237..2dd8adf 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 @@ -190,10 +190,7 @@ namespace System.Text.Json } // Priority 3: Attempt to get built-in converter. - if (converter == null) - { - converter = DefaultJsonTypeInfoResolver.GetDefaultConverter(typeToConvert); - } + converter ??= DefaultJsonTypeInfoResolver.GetDefaultConverter(typeToConvert); // Allow redirection for generic types or the enum converter. if (converter is JsonConverterFactory factory) diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfo.Cache.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfo.Cache.cs index 7b1202a..3d99324 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfo.Cache.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfo.Cache.cs @@ -251,10 +251,7 @@ namespace System.Text.Json.Serialization.Metadata // Check again to append the cache up to the threshold. if (cacheCount < PropertyNameCountCacheThreshold) { - if (frame.PropertyRefCache == null) - { - frame.PropertyRefCache = new List(); - } + frame.PropertyRefCache ??= new List(); Debug.Assert(info != null); @@ -390,10 +387,7 @@ namespace System.Text.Json.Serialization.Metadata // Check again to append the cache up to the threshold. if (cacheCount < ParameterNameCountCacheThreshold) { - if (frame.CtorArgumentState.ParameterRefCache == null) - { - frame.CtorArgumentState.ParameterRefCache = new List(); - } + frame.CtorArgumentState.ParameterRefCache ??= new List(); parameterRef = new ParameterRef(key, info!, utf8PropertyName); frame.CtorArgumentState.ParameterRefCache.Add(parameterRef); 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 fc86396..439de06 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Base/DataflowBlock.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Base/DataflowBlock.cs @@ -1341,10 +1341,10 @@ namespace System.Threading.Tasks.Dataflow // Task final state: Faulted case ReceiveCoreByLinkingCleanupReason.SourceCompletion: - if (_receivedException == null) _receivedException = CreateExceptionForSourceCompletion(); + _receivedException ??= CreateExceptionForSourceCompletion(); goto case ReceiveCoreByLinkingCleanupReason.SourceProtocolError; case ReceiveCoreByLinkingCleanupReason.Timer: - if (_receivedException == null) _receivedException = CreateExceptionForTimeout(); + _receivedException ??= CreateExceptionForTimeout(); goto case ReceiveCoreByLinkingCleanupReason.SourceProtocolError; case ReceiveCoreByLinkingCleanupReason.SourceProtocolError: case ReceiveCoreByLinkingCleanupReason.ErrorDuringCleanup: @@ -2574,7 +2574,7 @@ namespace System.Threading.Tasks.Dataflow if (sendAsyncTask.Status != TaskStatus.RanToCompletion) { // Ensure the SendAsyncTaskList is instantiated - if (_tempSendAsyncTaskList == null) _tempSendAsyncTaskList = new List>(); + _tempSendAsyncTaskList ??= new List>(); // Add the task to the list _tempSendAsyncTaskList.Add(sendAsyncTask); 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 56ee24c..05ca506 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BatchBlock.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BatchBlock.cs @@ -1101,7 +1101,7 @@ namespace System.Threading.Tasks.Dataflow catch (Exception e) { if (throwOnFirstException) throw; - if (exceptions == null) exceptions = new List(1); + exceptions ??= new List(1); exceptions.Add(e); } } 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 85a980d..927e971 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/TransformManyBlock.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/TransformManyBlock.cs @@ -366,8 +366,7 @@ namespace System.Threading.Tasks.Dataflow // This avoids the cost of updating it once per output item (since each update requires synchronization). // Even if we're not bounding, we still want to determine whether the item is trusted so that we // can immediately dump it out once we take the lock if we're the next item. - IList? itemAsTrustedList = item as TOutput[]; - if (itemAsTrustedList == null) itemAsTrustedList = item as List; + IList? itemAsTrustedList = (IList?)(item as TOutput[]) ?? item as List; if (itemAsTrustedList != null && isBounded) { UpdateBoundingCountWithOutputCount(count: itemAsTrustedList.Count); diff --git a/src/libraries/System.Threading.Tasks.Parallel/src/System/Threading/Tasks/Parallel.cs b/src/libraries/System.Threading.Tasks.Parallel/src/System/Threading/Tasks/Parallel.cs index 9fd0653..e222fa3 100644 --- a/src/libraries/System.Threading.Tasks.Parallel/src/System/Threading/Tasks/Parallel.cs +++ b/src/libraries/System.Threading.Tasks.Parallel/src/System/Threading/Tasks/Parallel.cs @@ -3098,8 +3098,7 @@ namespace System.Threading.Tasks Debug.Assert(exObj is Exception); Exception ex = (Exception)exObj; - if (first == null) - first = ex; + first ??= ex; // If mismatch found, fail-fast: OperationCanceledException? ocEx = ex as OperationCanceledException; diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/DurableEnlistmentState.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/DurableEnlistmentState.cs index b9e08e7..a7b9aa1 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/DurableEnlistmentState.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/DurableEnlistmentState.cs @@ -117,10 +117,7 @@ namespace System.Transactions internal override void Aborted(InternalEnlistment enlistment, Exception? e) { - if (enlistment.Transaction._innerException == null) - { - enlistment.Transaction._innerException = e; - } + enlistment.Transaction._innerException ??= e; // Transition to the ended state DurableEnlistmentEnded.EnterState(enlistment); @@ -212,10 +209,7 @@ namespace System.Transactions // Transition to the ended state DurableEnlistmentEnded.EnterState(enlistment); - if (enlistment.Transaction._innerException == null) - { - enlistment.Transaction._innerException = e; - } + enlistment.Transaction._innerException ??= e; Debug.Assert(enlistment.Transaction.State != null); // Make the transaction in dobut @@ -252,10 +246,7 @@ namespace System.Transactions // Transition to the ended state DurableEnlistmentEnded.EnterState(enlistment); - if (enlistment.Transaction._innerException == null) - { - enlistment.Transaction._innerException = e; - } + enlistment.Transaction._innerException ??= e; Debug.Assert(enlistment.Transaction.State != null); // Start the transaction aborting @@ -267,10 +258,7 @@ namespace System.Transactions // Transition to the ended state DurableEnlistmentEnded.EnterState(enlistment); - if (enlistment.Transaction._innerException == null) - { - enlistment.Transaction._innerException = e; - } + enlistment.Transaction._innerException ??= e; Debug.Assert(enlistment.Transaction.State != null); // Tell the transaction that the enlistment is InDoubt. Note that diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/Transaction.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/Transaction.cs index 7b16ffc..4126a75 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/Transaction.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/Transaction.cs @@ -1217,17 +1217,7 @@ namespace System.Transactions [AllowNull] internal static ContextData TLSCurrentData { - get - { - ContextData? data = t_staticData; - if (data == null) - { - data = new ContextData(false); - t_staticData = data; - } - - return data; - } + get => t_staticData ??= new ContextData(false); set { if (value == null && t_staticData != null) diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionManager.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionManager.cs index c27adcf..c4d3c4a 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionManager.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionManager.cs @@ -272,33 +272,11 @@ namespace System.Transactions private static DefaultSettingsSection? s_defaultSettings; - private static DefaultSettingsSection DefaultSettings - { - get - { - if (s_defaultSettings == null) - { - s_defaultSettings = DefaultSettingsSection.GetSection(); - } - - return s_defaultSettings; - } - } + private static DefaultSettingsSection DefaultSettings => s_defaultSettings ??= DefaultSettingsSection.GetSection(); private static MachineSettingsSection? s_machineSettings; - private static MachineSettingsSection MachineSettings - { - get - { - if (s_machineSettings == null) - { - s_machineSettings = MachineSettingsSection.GetSection(); - } - - return s_machineSettings; - } - } + private static MachineSettingsSection MachineSettings => s_machineSettings ??= MachineSettingsSection.GetSection(); private static bool s_defaultTimeoutValidated; private static TimeSpan s_defaultTimeout; diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionScope.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionScope.cs index 34bc3b8..1329ab1 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionScope.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionScope.cs @@ -555,11 +555,7 @@ namespace System.Transactions // Something must have gone wrong trying to clean up a bad scope // stack previously. // Make a best effort to abort the active transaction. - Transaction? rollbackTransaction = _committableTransaction; - if (rollbackTransaction == null) - { - rollbackTransaction = _dependentTransaction; - } + Transaction? rollbackTransaction = (Transaction?)_committableTransaction ?? _dependentTransaction; Debug.Assert(rollbackTransaction != null); rollbackTransaction.Rollback(); @@ -792,11 +788,7 @@ namespace System.Transactions // Note: Rollback is not called on expected current because someone could conceiveably // dispose expectedCurrent out from under the transaction scope. // - Transaction? rollbackTransaction = _committableTransaction; - if (rollbackTransaction == null) - { - rollbackTransaction = _dependentTransaction; - } + Transaction? rollbackTransaction = (Transaction?)_committableTransaction ?? _dependentTransaction; Debug.Assert(rollbackTransaction != null); rollbackTransaction.Rollback(); } @@ -1088,10 +1080,7 @@ namespace System.Transactions private void SaveTLSContextData() { - if (_savedTLSContextData == null) - { - _savedTLSContextData = new ContextData(false); - } + _savedTLSContextData ??= new ContextData(false); _savedTLSContextData.CurrentScope = ContextData.TLSCurrentData.CurrentScope; _savedTLSContextData.CurrentTransaction = ContextData.TLSCurrentData.CurrentTransaction; diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionState.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionState.cs index ee42f6d..995ea8c 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionState.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionState.cs @@ -697,10 +697,7 @@ namespace System.Transactions // Start the process for abort. From the active state we can transition directly // to the aborted state. - if (tx._innerException == null) - { - tx._innerException = e; - } + tx._innerException ??= e; TransactionStateAborted.EnterState(tx); } @@ -843,10 +840,7 @@ namespace System.Transactions // Start the process for abort. From the active state we can transition directly // to the aborted state. - if (tx._innerException == null) - { - tx._innerException = e; - } + tx._innerException ??= e; Debug.Assert(tx._promoter != null); ((ISimpleTransactionSuperior)tx._promoter).Rollback(); @@ -1155,10 +1149,7 @@ namespace System.Transactions internal override void ChangeStateTransactionAborted(InternalTransaction tx, Exception? e) { - if (tx._innerException == null) - { - tx._innerException = e; - } + tx._innerException ??= e; TransactionStateAborted.EnterState(tx); } @@ -1232,10 +1223,7 @@ namespace System.Transactions internal override void ChangeStateTransactionAborted(InternalTransaction tx, Exception? e) { - if (tx._innerException == null) - { - tx._innerException = e; - } + tx._innerException ??= e; TransactionStateAborted.EnterState(tx); } @@ -1296,10 +1284,7 @@ namespace System.Transactions internal override void ChangeStateTransactionAborted(InternalTransaction tx, Exception? e) { - if (tx._innerException == null) - { - tx._innerException = e; - } + tx._innerException ??= e; // The durable enlistment must have aborted. Go to the aborted state. TransactionStateAborted.EnterState(tx); @@ -1343,10 +1328,7 @@ namespace System.Transactions internal override void ChangeStateTransactionAborted(InternalTransaction tx, Exception? e) { - if (tx._innerException == null) - { - tx._innerException = e; - } + tx._innerException ??= e; // The durable enlistment must have aborted. Go to the aborted state. TransactionStateAborted.EnterState(tx); @@ -1824,10 +1806,7 @@ namespace System.Transactions Debug.Assert(tx.PromotedTransaction != null, "Promoted state not valid for transaction."); // Forward this on to the promoted transaction. - if (tx._innerException == null) - { - tx._innerException = e; - } + tx._innerException ??= e; // Don't hold locks while calling into the promoted tx Monitor.Exit(tx); @@ -2072,10 +2051,7 @@ namespace System.Transactions // LTM gives up the ability to control Tx timeout when it promotes. try { - if (tx._innerException == null) - { - tx._innerException = new TimeoutException(SR.TraceTransactionTimeout); - } + tx._innerException ??= new TimeoutException(SR.TraceTransactionTimeout); Debug.Assert(tx.PromotedTransaction != null); DistributedTransaction.Rollback(); @@ -2440,10 +2416,7 @@ namespace System.Transactions // In this state we don't want a transaction exception from BeginCommit to randomly // bubble up to the application or go unhandled. So catch the exception and if the // inner exception for the transaction has not already been set then set it. - if (tx._innerException == null) - { - tx._innerException = e; - } + tx._innerException ??= e; TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { @@ -2461,10 +2434,7 @@ namespace System.Transactions internal override void ChangeStateTransactionAborted(InternalTransaction tx, Exception? e) { - if (tx._innerException == null) - { - tx._innerException = e; - } + tx._innerException ??= e; // This change state event at this point would be caused by one of the enlistments // aborting. Really change to P0Aborting @@ -2576,10 +2546,7 @@ namespace System.Transactions internal override void ChangeStateTransactionAborted(InternalTransaction tx, Exception? e) { - if (tx._innerException == null) - { - tx._innerException = e; - } + tx._innerException ??= e; // This change state event at this point would be caused by one of the enlistments // aborting. Really change to P0Aborting @@ -2653,10 +2620,7 @@ namespace System.Transactions internal override void ChangeStateTransactionAborted(InternalTransaction tx, Exception? e) { - if (tx._innerException == null) - { - tx._innerException = e; - } + tx._innerException ??= e; // This change state event at this point would be caused by one of the enlistments // aborting. Really change to P1Aborting @@ -3406,10 +3370,7 @@ namespace System.Transactions // Pass the Rollback through the promotable single phase enlistment to be // certain it is notified. - if (tx._innerException == null) - { - tx._innerException = e; - } + tx._innerException ??= e; TransactionStateDelegatedAborting.EnterState(tx); } @@ -3521,10 +3482,7 @@ namespace System.Transactions // transaction promoter will get notified of the abort. Debug.Assert(tx._durableEnlistment != null, "PromotedNonMSDTC state is not valid for transaction"); - if (tx._innerException == null) - { - tx._innerException = e; - } + tx._innerException ??= e; TransactionStateAborted.EnterState(tx); } @@ -3613,10 +3571,7 @@ namespace System.Transactions // Just transition to Aborted. The PSPE will be told to rollback thru the durableEnlistment. // This is also overridden in TransactionStatePromotedNonMSDTCSinglePhaseCommit // that does something slightly differently. - if (tx._innerException == null) - { - tx._innerException = e; - } + tx._innerException ??= e; TransactionStateAborted.EnterState(tx); } @@ -3917,10 +3872,7 @@ namespace System.Transactions internal override void ChangeStateTransactionAborted(InternalTransaction tx, Exception? e) { - if (tx._innerException == null) - { - tx._innerException = e; - } + tx._innerException ??= e; // The durable enlistment must have aborted. Go to the aborted state. TransactionStatePromotedNonMSDTCAborted.EnterState(tx); @@ -4342,10 +4294,7 @@ namespace System.Transactions // Pass the Rollback through the promotable single phase enlistment to be // certain it is notified. - if (tx._innerException == null) - { - tx._innerException = e; - } + tx._innerException ??= e; Debug.Assert(tx.PromotedTransaction != null); DistributedTransaction.Rollback(); diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/VolatileEnlistmentState.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/VolatileEnlistmentState.cs index 7873186..360dc3e 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/VolatileEnlistmentState.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/VolatileEnlistmentState.cs @@ -261,10 +261,7 @@ namespace System.Transactions { VolatileEnlistmentEnded.EnterState(enlistment); - if (enlistment.Transaction._innerException == null) - { - enlistment.Transaction._innerException = e; - } + enlistment.Transaction._innerException ??= e; Debug.Assert(enlistment.Transaction.State != null); enlistment.Transaction.State.InDoubtFromEnlistment(enlistment.Transaction); diff --git a/src/libraries/System.Web.HttpUtility/src/System/Web/Util/HttpEncoder.cs b/src/libraries/System.Web.HttpUtility/src/System/Web/Util/HttpEncoder.cs index e6e90c7..9971f14 100644 --- a/src/libraries/System.Web.HttpUtility/src/System/Web/Util/HttpEncoder.cs +++ b/src/libraries/System.Web.HttpUtility/src/System/Web/Util/HttpEncoder.cs @@ -169,10 +169,7 @@ namespace System.Web.Util // to the string builder when special characters are detected. if (CharRequiresJavaScriptEncoding(c)) { - if (b == null) - { - b = new StringBuilder(value.Length + 5); - } + b ??= new StringBuilder(value.Length + 5); if (count > 0) { @@ -708,10 +705,7 @@ namespace System.Web.Util else */ { - if (_byteBuffer == null) - { - _byteBuffer = new byte[_bufferSize]; - } + _byteBuffer ??= new byte[_bufferSize]; _byteBuffer[_numBytes++] = b; } diff --git a/src/libraries/System.Windows.Extensions/src/System/Media/SoundPlayer.cs b/src/libraries/System.Windows.Extensions/src/System/Media/SoundPlayer.cs index c970d47..b1ce057 100644 --- a/src/libraries/System.Windows.Extensions/src/System/Media/SoundPlayer.cs +++ b/src/libraries/System.Windows.Extensions/src/System/Media/SoundPlayer.cs @@ -85,10 +85,7 @@ namespace System.Media get => _soundLocation; set { - if (value == null) - { - value = string.Empty; - } + value ??= string.Empty; if (_soundLocation.Equals(value)) { diff --git a/src/mono/System.Private.CoreLib/src/System/Delegate.Mono.cs b/src/mono/System.Private.CoreLib/src/System/Delegate.Mono.cs index c0c16a9..54cc282 100644 --- a/src/mono/System.Private.CoreLib/src/System/Delegate.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/Delegate.Mono.cs @@ -430,8 +430,7 @@ namespace System object? target = _target; - if (data is null) - data = CreateDelegateData(); + data ??= CreateDelegateData(); // replace all Type.Missing with default values defined on parameters of the delegate if any MethodInfo? invoke = GetType().GetMethod("Invoke"); diff --git a/src/mono/System.Private.CoreLib/src/System/Reflection/CustomAttribute.cs b/src/mono/System.Private.CoreLib/src/System/Reflection/CustomAttribute.cs index 55d3aa8..9ae8182 100644 --- a/src/mono/System.Private.CoreLib/src/System/Reflection/CustomAttribute.cs +++ b/src/mono/System.Private.CoreLib/src/System/Reflection/CustomAttribute.cs @@ -48,8 +48,8 @@ namespace System.Reflection return false; if ((obj is Type)) return true; - if (corlib == null) - corlib = typeof(int).Assembly; + + corlib ??= typeof(int).Assembly; return obj.GetType().Assembly != corlib; } @@ -733,8 +733,7 @@ namespace System.Reflection { AttributeUsageAttribute? usageAttribute; /* Usage a thread-local cache to speed this up, since it is called a lot from GetCustomAttributes () */ - if (usage_cache == null) - usage_cache = new Dictionary(); + usage_cache ??= new Dictionary(); if (usage_cache.TryGetValue(attributeType, out usageAttribute)) return usageAttribute; usageAttribute = RetrieveAttributeUsageNoCache(attributeType); diff --git a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/DynamicMethod.cs b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/DynamicMethod.cs index ea546a5..eeb3a37 100644 --- a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/DynamicMethod.cs +++ b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/DynamicMethod.cs @@ -119,8 +119,7 @@ namespace System.Reflection.Emit private DynamicMethod(string name, MethodAttributes attributes, CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes, Type? owner, Module? m, bool skipVisibility, bool anonHosted, bool typeOwner) { ArgumentNullException.ThrowIfNull(name); - if (returnType == null) - returnType = typeof(void); + returnType ??= typeof(void); if (typeOwner) ArgumentNullException.ThrowIfNull(owner); if (!anonHosted) @@ -136,8 +135,7 @@ namespace System.Reflection.Emit throw new ArgumentException("Owner can't be an array or an interface."); } - if (m == null) - m = AnonHostModuleHolder.AnonHostModule; + m ??= AnonHostModuleHolder.AnonHostModule; this.name = name; this.attributes = attributes | MethodAttributes.Static; @@ -255,12 +253,7 @@ namespace System.Reflection.Emit return (object[])Array.CreateInstance(attributeType.IsValueType || attributeType.ContainsGenericParameters ? typeof(object) : attributeType, 0); } - public DynamicILInfo GetDynamicILInfo() - { - if (il_info == null) - il_info = new DynamicILInfo(this); - return il_info; - } + public DynamicILInfo GetDynamicILInfo() => il_info ??= new DynamicILInfo(this); public ILGenerator GetILGenerator() { @@ -316,8 +309,7 @@ namespace System.Reflection.Emit /* public override object Invoke (object obj, object[] parameters) { CreateDynMethod (); - if (method == null) - method = new RuntimeMethodInfo (mhandle); + method ??= new RuntimeMethodInfo (mhandle); return method.Invoke (obj, parameters); } */ diff --git a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/ILGenerator.Mono.cs b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/ILGenerator.Mono.cs index c1f4df1..3f7f25a 100644 --- a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/ILGenerator.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/ILGenerator.Mono.cs @@ -469,7 +469,9 @@ namespace System.Reflection.Emit public virtual Label DefineLabel() { if (labels == null) + { labels = new LabelData[defaultLabelsSize]; + } else if (num_labels >= labels.Length) { LabelData[] t = new LabelData[labels.Length * 2]; @@ -554,7 +556,9 @@ namespace System.Reflection.Emit labels[label.m_label].maxStack = cur_stack; if (fixups == null) + { fixups = new LabelFixup[defaultFixupSize]; + } else if (num_fixups >= fixups.Length) { LabelFixup[] newf = new LabelFixup[fixups.Length * 2]; @@ -584,7 +588,9 @@ namespace System.Reflection.Emit emit_int(count); if (fixups == null) + { fixups = new LabelFixup[defaultFixupSize + count]; + } else if (num_fixups + count >= fixups.Length) { LabelFixup[] newf = new LabelFixup[count + fixups.Length * 2]; diff --git a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/MethodBuilder.Mono.cs b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/MethodBuilder.Mono.cs index bc40ef5..478e66c 100644 --- a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/MethodBuilder.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/MethodBuilder.Mono.cs @@ -334,8 +334,7 @@ namespace System.Reflection.Emit throw new ArgumentOutOfRangeException(nameof(position)); ParameterBuilder pb = new ParameterBuilder(this, position, attributes, strParamName); - if (pinfo == null) - pinfo = new ParameterBuilder[parameters.Length + 1]; + pinfo ??= new ParameterBuilder[parameters.Length + 1]; pinfo[position] = pb; return pb; } diff --git a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.Mono.cs b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.Mono.cs index 5dbafb8..8ccdd30 100644 --- a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.Mono.cs @@ -697,12 +697,7 @@ namespace System.Reflection.Emit [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern object GetRegisteredToken(int token); - internal ITokenGenerator GetTokenGenerator() - { - if (token_gen == null) - token_gen = new ModuleBuilderTokenGenerator(this); - return token_gen; - } + internal ITokenGenerator GetTokenGenerator() => token_gen ??= new ModuleBuilderTokenGenerator(this); // Called from the runtime to return the corresponding finished reflection object internal static object RuntimeResolve(object obj) @@ -744,8 +739,7 @@ namespace System.Reflection.Emit internal void CreateGlobalType() { - if (global_type == null) - global_type = new TypeBuilder(this, 0, 1); + global_type ??= new TypeBuilder(this, 0, 1); } public override Assembly Assembly diff --git a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/SignatureHelper.cs b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/SignatureHelper.cs index 84a0090..45c734e 100644 --- a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/SignatureHelper.cs +++ b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/SignatureHelper.cs @@ -391,8 +391,7 @@ namespace System.Reflection.Emit if (mod != null && !(mod is ModuleBuilder)) throw new ArgumentException("ModuleBuilder is expected"); - if (returnType == null) - returnType = typeof(void); + returnType ??= typeof(void); if (returnType.IsUserType) throw new NotSupportedException("User defined subclasses of System.Type are not yet supported."); diff --git a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.Mono.cs b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.Mono.cs index b2ee5ca..4178b25 100644 --- a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.Mono.cs @@ -518,8 +518,7 @@ namespace System.Reflection.Emit !(((attributes & MethodAttributes.Static) != 0))) throw new ArgumentException("Interface method must be abstract and virtual."); - if (returnType == null) - returnType = typeof(void); + returnType ??= typeof(void); MethodBuilder res = new MethodBuilder(this, name, attributes, callingConvention, returnType, returnTypeRequiredCustomModifiers, diff --git a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs index 88a493f..48bed67 100644 --- a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs +++ b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs @@ -177,29 +177,32 @@ namespace System.Reflection.Emit internal override MethodInfo GetMethod(MethodInfo fromNoninstanciated) { - if (methods == null) - methods = new Dictionary(); - if (!methods.ContainsKey(fromNoninstanciated)) - methods[fromNoninstanciated] = new MethodOnTypeBuilderInst(this, fromNoninstanciated); - return methods[fromNoninstanciated]!; + methods ??= new Dictionary(); + if (!methods.TryGetValue(fromNoninstanciated, out MethodInfo? mi)) + { + methods[fromNoninstanciated] = mi = new MethodOnTypeBuilderInst(this, fromNoninstanciated); + } + return mi; } internal override ConstructorInfo GetConstructor(ConstructorInfo fromNoninstanciated) { - if (ctors == null) - ctors = new Dictionary(); - if (!ctors.ContainsKey(fromNoninstanciated)) - ctors[fromNoninstanciated] = new ConstructorOnTypeBuilderInst(this, fromNoninstanciated); - return ctors[fromNoninstanciated]!; + ctors ??= new Dictionary(); + if (!ctors.TryGetValue(fromNoninstanciated, out ConstructorInfo? ci)) + { + ctors[fromNoninstanciated] = ci = new ConstructorOnTypeBuilderInst(this, fromNoninstanciated); + } + return ci; } internal override FieldInfo GetField(FieldInfo fromNoninstanciated) { - if (fields == null) - fields = new Dictionary(); - if (!fields.ContainsKey(fromNoninstanciated)) - fields[fromNoninstanciated] = new FieldOnTypeBuilderInst(this, fromNoninstanciated); - return fields[fromNoninstanciated]!; + fields ??= new Dictionary(); + if (!fields.TryGetValue(fromNoninstanciated, out FieldInfo? fi)) + { + fields[fromNoninstanciated] = fi = new FieldOnTypeBuilderInst(this, fromNoninstanciated); + } + return fi; } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] diff --git a/src/mono/System.Private.CoreLib/src/System/Reflection/RuntimeEventInfo.cs b/src/mono/System.Private.CoreLib/src/System/Reflection/RuntimeEventInfo.cs index a9844f7..f59e3e2 100644 --- a/src/mono/System.Private.CoreLib/src/System/Reflection/RuntimeEventInfo.cs +++ b/src/mono/System.Private.CoreLib/src/System/Reflection/RuntimeEventInfo.cs @@ -91,11 +91,7 @@ namespace System.Reflection { MonoEventInfo info = GetEventInfo(this); - MethodInfo method = info.add_method; - if (method == null) - method = info.remove_method; - if (method == null) - method = info.raise_method; + MethodInfo method = info.add_method ?? info.remove_method ?? info.raise_method; return RuntimeType.FilterPreCalculate(method != null && method.IsPublic, GetDeclaringTypeInternal() != ReflectedType, method != null && method.IsStatic); } diff --git a/src/mono/System.Private.CoreLib/src/System/Reflection/RuntimeFieldInfo.cs b/src/mono/System.Private.CoreLib/src/System/Reflection/RuntimeFieldInfo.cs index 73aa474..1fcb299 100644 --- a/src/mono/System.Private.CoreLib/src/System/Reflection/RuntimeFieldInfo.cs +++ b/src/mono/System.Private.CoreLib/src/System/Reflection/RuntimeFieldInfo.cs @@ -174,15 +174,7 @@ namespace System.Reflection [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern Type ResolveType(); - public override Type FieldType - { - get - { - if (type == null) - type = ResolveType(); - return type; - } - } + public override Type FieldType => type ??= ResolveType(); [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern Type GetParentType(bool declaring); @@ -272,8 +264,8 @@ namespace System.Reflection } if (IsLiteral) throw new FieldAccessException("Cannot set a constant field"); - if (binder == null) - binder = Type.DefaultBinder; + + binder ??= Type.DefaultBinder; CheckGeneric(); if (val != null) { diff --git a/src/mono/System.Private.CoreLib/src/System/RuntimeType.Mono.cs b/src/mono/System.Private.CoreLib/src/System/RuntimeType.Mono.cs index 32c447f..d44dbff 100644 --- a/src/mono/System.Private.CoreLib/src/System/RuntimeType.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/RuntimeType.Mono.cs @@ -802,8 +802,7 @@ namespace System } } - if (binder == null) - binder = DefaultBinder; + binder ??= DefaultBinder; return binder.SelectMethod(bindingAttr, candidates.ToArray(), types, modifiers) as MethodInfo; } @@ -832,8 +831,7 @@ namespace System if ((bindingAttr & BindingFlags.ExactBinding) != 0) return System.DefaultBinder.ExactBinding(candidates.ToArray(), types) as ConstructorInfo; - if (binder == null) - binder = DefaultBinder; + binder ??= DefaultBinder; return binder.SelectMethod(bindingAttr, candidates.ToArray(), types, modifiers) as ConstructorInfo; } @@ -872,8 +870,7 @@ namespace System if ((bindingAttr & BindingFlags.ExactBinding) != 0) return System.DefaultBinder.ExactPropertyBinding(candidates.ToArray(), returnType, types); - if (binder == null) - binder = DefaultBinder; + binder ??= DefaultBinder; return binder.SelectProperty(bindingAttr, candidates.ToArray(), returnType, types, modifiers); } @@ -968,14 +965,12 @@ namespace System StringComparison nameComparison = ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; foreach (RuntimeType t in GetInterfaces()) { - if (!string.Equals(t.Name, name, nameComparison)) { continue; } - if (list == null) - list = new List(2); + list ??= new List(2); list.Add(t); } @@ -1297,9 +1292,7 @@ namespace System Type[]? types = null; var this_type = this; GetGenericArgumentsInternal(new QCallTypeHandle(ref this_type), ObjectHandleOnStack.Create(ref types), false); - if (types == null) - types = Type.EmptyTypes; - return types; + return types ?? Type.EmptyTypes; } [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.")] @@ -1409,8 +1402,7 @@ namespace System int argCnt = args.Length; // Without a binder we need to do use the default binder... - if (binder == null) - binder = DefaultBinder; + binder ??= DefaultBinder; // deal with the __COMObject case first. It is very special because from a reflection point of view it has no ctors // so a call to GetMemberCons would fail diff --git a/src/mono/System.Private.CoreLib/src/System/TypeNameParser.cs b/src/mono/System.Private.CoreLib/src/System/TypeNameParser.cs index 6d966fb..db6db62 100644 --- a/src/mono/System.Private.CoreLib/src/System/TypeNameParser.cs +++ b/src/mono/System.Private.CoreLib/src/System/TypeNameParser.cs @@ -307,16 +307,14 @@ namespace System pos++; isbyref = true; isptr = false; - if (res.Modifiers == null) - res.Modifiers = new List(); + res.Modifiers ??= new List(); res.Modifiers.Add(0); break; case '*': if (isbyref) return null; pos++; - if (res.Modifiers == null) - res.Modifiers = new List(); + res.Modifiers ??= new List(); res.Modifiers.Add(-1); isptr = true; break; @@ -355,8 +353,7 @@ namespace System if (bounded && rank > 1) return null; /* n.b. bounded needs both modifiers: -2 == bounded, 1 == rank 1 array */ - if (res.Modifiers == null) - res.Modifiers = new List(); + res.Modifiers ??= new List(); if (bounded) res.Modifiers.Add(-2); res.Modifiers.Add(rank); diff --git a/src/mono/System.Private.CoreLib/src/System/TypeSpec.cs b/src/mono/System.Private.CoreLib/src/System/TypeSpec.cs index 23749b5..516975f 100644 --- a/src/mono/System.Private.CoreLib/src/System/TypeSpec.cs +++ b/src/mono/System.Private.CoreLib/src/System/TypeSpec.cs @@ -243,15 +243,7 @@ namespace System return sb; } - internal string DisplayFullName - { - get - { - if (display_fullname == null) - display_fullname = GetDisplayFullName(DisplayNameFormat.Default); - return display_fullname; - } - } + internal string DisplayFullName => display_fullname ??= GetDisplayFullName(DisplayNameFormat.Default); internal static TypeSpec Parse(string typeName) { @@ -312,18 +304,12 @@ namespace System } else { - if (nested == null) - nested = new List(); + nested ??= new List(); nested.Add(ParsedTypeIdentifier(type_name)); } } - private void AddModifier(IModifierSpec md) - { - if (modifier_spec == null) - modifier_spec = new List(); - modifier_spec.Add(md); - } + private void AddModifier(IModifierSpec md) => modifier_spec ??= new List(); private static void SkipSpace(string name, ref int pos) { -- 2.7.4