Use null coalescing in many more places (#71361)
authorStephen Toub <stoub@microsoft.com>
Tue, 28 Jun 2022 18:47:36 +0000 (14:47 -0400)
committerGitHub <noreply@github.com>
Tue, 28 Jun 2022 18:47:36 +0000 (14:47 -0400)
641 files changed:
src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/ILGenerator.cs
src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/SignatureHelper.cs
src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.cs
src/libraries/Common/src/System/CodeDom/CodeTypeReference.cs
src/libraries/Common/src/System/Net/ContextAwareResult.cs
src/libraries/Common/src/System/Net/CookieParser.cs
src/libraries/Common/src/System/Net/Logging/NetEventSource.Common.cs
src/libraries/Common/src/System/Net/NTAuthentication.Common.cs
src/libraries/Common/src/System/Net/Security/NegotiateStreamPal.Unix.cs
src/libraries/Common/src/System/Resources/ResourceWriter.cs
src/libraries/Common/src/System/Runtime/InteropServices/ComEventsMethod.cs
src/libraries/Common/src/System/Text/OSEncoding.Windows.cs
src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComEventsSink.Extended.cs
src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComInvokeBinder.cs
src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComTypeClassDesc.cs
src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/IDispatchComObject.cs
src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/SplatCallSite.cs
src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/TypeUtils.cs
src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Errors/UserStringBuilder.cs
src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/GroupToArgsBinder.cs
src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/MemberLookup.cs
src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Operators.cs
src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/PredefinedMembers.cs
src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/PredefinedTypes.cs
src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/TypeManager.cs
src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteValidator.cs
src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ILEmit/ILEmitResolverBuilder.cs
src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextJsonReader.cs
src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextLoader.cs
src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/Patterns/PatternBuilder.cs
src/libraries/Microsoft.Extensions.Http/src/DefaultHttpClientFactory.cs
src/libraries/Microsoft.Extensions.Logging/src/Logger.cs
src/libraries/Microsoft.Extensions.Logging/src/LoggerFactory.cs
src/libraries/System.CodeDom/src/System/CodeDom/CodeMemberMethod.cs
src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerInfo.cs
src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/BlockingCollection.cs
src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/PartitionerStatic.cs
src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/AllocFreeConcurrentStack.cs
src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray_1.cs
src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary_2.Builder.cs
src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary_2.cs
src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableExtensions.cs
src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableHashSet_1.Builder.cs
src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableHashSet_1.cs
src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Builder.cs
src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Node.cs
src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableQueue_1.cs
src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary_2.Builder.cs
src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary_2.cs
src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.Builder.cs
src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.cs
src/libraries/System.Collections.Immutable/src/System/Linq/ImmutableArrayExtensions.cs
src/libraries/System.Collections.NonGeneric/src/System/Collections/CaseInsensitiveComparer.cs
src/libraries/System.Collections.NonGeneric/src/System/Collections/DictionaryBase.cs
src/libraries/System.Collections.NonGeneric/src/System/Collections/ReadOnlyCollectionBase.cs
src/libraries/System.Collections.NonGeneric/src/System/Collections/SortedList.cs
src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/HybridDictionary.cs
src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/NameObjectCollectionBase.cs
src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/NameValueCollection.cs
src/libraries/System.Collections/src/System/Collections/Generic/SortedDictionary.cs
src/libraries/System.Collections/src/System/Collections/Generic/SortedList.cs
src/libraries/System.Collections/src/System/Collections/StructuralComparisons.cs
src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CompareAttribute.cs
src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CustomValidationAttribute.cs
src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttributeStore.cs
src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/ExportBuilder.cs
src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/ImportBuilder.cs
src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/PartBuilder.cs
src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/PartBuilderOfT.cs
src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Collections/CollectionServices.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedPartCreationInfo.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AtomicComposition.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.FactoryExport.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartExportProvider.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionServices.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportProvider.GetExportOverrides.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportProvider.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportsChangeEventArgs.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.DependenciesTraversal.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.DependentsTraversal.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.PartManager.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ContractBasedImportDefinition.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ImportDefinition.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/GenericSpecializationPartCreationInfo.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePart.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePartDefinition.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberExportDefinition.cs
src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/AttributeCollection.cs
src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/BaseNumberConverter.cs
src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/BindingList.cs
src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ComponentResourceManager.cs
src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/DateOnlyConverter.cs
src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/DateTimeConverter.cs
src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/DateTimeOffsetConverter.cs
src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerOptionService.cs
src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesigntimeLicenseContext.cs
src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/ContextStack.cs
src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/MemberRelationshipService.cs
src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicFileLicenseProvider.cs
src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicenseManager.LicenseInteropHelper.cs
src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicenseManager.cs
src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MaskedTextProvider.cs
src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/PropertyDescriptor.cs
src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectPropertyDescriptor.cs
src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.ReflectedTypeData.cs
src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.cs
src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TimeOnlyConverter.cs
src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeConverter.cs
src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptor.cs
src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/WeakHashtable.cs
src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/ColorConverter.cs
src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/PointConverter.cs
src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/RectangleConverter.cs
src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/SizeConverter.cs
src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/SizeFConverter.cs
src/libraries/System.Composition.Convention/src/System/Composition/Convention/ExportConventionBuilder.cs
src/libraries/System.Composition.Convention/src/System/Composition/Convention/ImportConventionBuilder.cs
src/libraries/System.Composition.Convention/src/System/Composition/Convention/PartConventionBuilder.cs
src/libraries/System.Composition.Convention/src/System/Composition/Convention/PartConventionBuilderOfT.cs
src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/CompositionOperation.cs
src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Util/SmallSparseInitonlyArray.cs
src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Discovery/DiscoveredPart.cs
src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ApplicationSettingsBase.cs
src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/BaseConfigurationRecord.cs
src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientConfigPaths.cs
src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientSettingsStore.cs
src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElement.cs
src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationManagerInternalFactory.cs
src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/DictionarySectionHandler.cs
src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ErrorsHelper.cs
src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/LocalFileSettingsProvider.cs
src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/MgmtConfigurationRecord.cs
src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProviderSettings.cs
src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingValueElement.cs
src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/TypeUtil.cs
src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/UpdateConfigHost.cs
src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/XmlUtil.cs
src/libraries/System.Console/src/System/IO/StdInReader.cs
src/libraries/System.Console/src/System/TermInfo.cs
src/libraries/System.Data.Common/src/System/Data/Common/DataRecordInternal.cs
src/libraries/System.Data.Common/src/System/Data/Constraint.cs
src/libraries/System.Data.Common/src/System/Data/DataColumn.cs
src/libraries/System.Data.Common/src/System/Data/DataError.cs
src/libraries/System.Data.Common/src/System/Data/DataRelation.cs
src/libraries/System.Data.Common/src/System/Data/DataRow.cs
src/libraries/System.Data.Common/src/System/Data/DataSet.cs
src/libraries/System.Data.Common/src/System/Data/DataTable.cs
src/libraries/System.Data.Common/src/System/Data/DataTableReader.cs
src/libraries/System.Data.Common/src/System/Data/DataView.cs
src/libraries/System.Data.Common/src/System/Data/DataViewSetting.cs
src/libraries/System.Data.Common/src/System/Data/ProviderBase/SchemaMapping.cs
src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBytes.cs
src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLChars.cs
src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLString.cs
src/libraries/System.Data.Common/src/System/Data/SQLTypes/SqlXml.cs
src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs
src/libraries/System.Data.Common/src/System/Data/XmlDataLoader.cs
src/libraries/System.Data.Common/src/System/Data/XmlToDatasetMap.cs
src/libraries/System.Data.Common/src/System/Xml/XmlDataDocument.cs
src/libraries/System.Data.Odbc/src/System/Data/Odbc/DbDataRecord.cs
src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcCommand.cs
src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnection.cs
src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataReader.cs
src/libraries/System.Data.Odbc/tests/OdbcParameterTests.cs
src/libraries/System.Data.OleDb/src/OleDbCommandBuilder.cs
src/libraries/System.Data.OleDb/src/OleDbMetaDataFactory.cs
src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DiagnosticSourceEventSource.cs
src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/MeterListener.cs
src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/RandomNumberGenerator.cs
src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLog.cs
src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogConfiguration.cs
src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogRecord.cs
src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogSession.cs
src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/ProviderMetadata.cs
src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounter.cs
src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterCategory.cs
src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterLib.cs
src/libraries/System.Diagnostics.Process/src/System/Diagnostics/PerformanceCounterLib.cs
src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Win32.cs
src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessWaitState.Unix.cs
src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/DefaultTraceListener.cs
src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/Switch.cs
src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceEventCache.cs
src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceInternal.cs
src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceListener.cs
src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceSource.cs
src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADAMStoreCtx.cs
src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx.cs
src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_Query.cs
src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AuthenticablePrincipal.cs
src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Context.cs
src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx.cs
src/libraries/System.DirectoryServices.AccountManagement/tests/AccountManagementTests.cs
src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.cs
src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchema.cs
src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClass.cs
src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClassCollection.cs
src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaProperty.cs
src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaPropertyCollection.cs
src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ConfigSet.cs
src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryEntryManager.cs
src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServer.cs
src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Domain.cs
src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainController.cs
src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Forest.cs
src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyStringCollection.cs
src/libraries/System.DirectoryServices/src/System/DirectoryServices/Design/DirectoryEntryConverter.cs
src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntries.cs
src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntry.cs
src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectorySearcher.cs
src/libraries/System.DirectoryServices/src/System/DirectoryServices/SearchResultCollection.cs
src/libraries/System.Drawing.Common/src/System/Drawing/ColorConverter.cs
src/libraries/System.Drawing.Common/src/System/Drawing/FontConverter.cs
src/libraries/System.Drawing.Common/src/System/Drawing/Image.cs
src/libraries/System.Drawing.Common/src/System/Drawing/ImageAnimator.cs
src/libraries/System.Drawing.Common/src/System/Drawing/Internal/SystemColorTracker.cs
src/libraries/System.Drawing.Common/src/System/Drawing/PointConverter.cs
src/libraries/System.Drawing.Common/src/System/Drawing/Printing/MarginsConverter.cs
src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PageSettings.cs
src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrintDocument.cs
src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.cs
src/libraries/System.Drawing.Common/src/System/Drawing/Printing/QueryPageSettingsEventArgs.cs
src/libraries/System.Drawing.Common/src/System/Drawing/RectangleConverter.cs
src/libraries/System.Drawing.Common/src/System/Drawing/SizeConverter.cs
src/libraries/System.Drawing.Common/src/System/Drawing/SystemBrushes.cs
src/libraries/System.Drawing.Common/src/System/Drawing/SystemFonts.cs
src/libraries/System.Drawing.Common/src/System/Drawing/SystemPens.cs
src/libraries/System.Drawing.Common/src/System/Drawing/ToolboxBitmapAttribute.cs
src/libraries/System.Drawing.Common/src/misc/GDI/DeviceContext.cs
src/libraries/System.Drawing.Common/src/misc/GDI/DeviceContexts.cs
src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.BitString.cs
src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnDecoder.OctetString.cs
src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.cs
src/libraries/System.IO.Packaging/src/System/IO/Packaging/InternalRelationshipCollection.cs
src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackUriHelper.cs
src/libraries/System.IO.Packaging/src/System/IO/Packaging/Package.cs
src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackagePart.cs
src/libraries/System.IO.Packaging/src/System/IO/Packaging/XmlCompatibilityReader.cs
src/libraries/System.IO.Packaging/src/System/IO/Packaging/ZipPackage.cs
src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeCompletionCallbacks.cs
src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeReader.cs
src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeWriter.cs
src/libraries/System.Linq.Expressions/src/System/Dynamic/DynamicObject.cs
src/libraries/System.Linq.Expressions/src/System/Dynamic/ExpandoClass.cs
src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/DelegateHelpers.Generated.cs
src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LabelInfo.cs
src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.ControlFlow.cs
src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Expressions.cs
src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Statements.cs
src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/StackSpiller.ChildRewriter.cs
src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/StackSpiller.Temps.cs
src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/StackSpiller.cs
src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/VariableBinder.cs
src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/DebugViewWriter.cs
src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ExpressionStringBuilder.cs
src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/BranchLabel.cs
src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/ControlFlowInstructions.cs
src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InstructionList.cs
src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InterpretedFrame.cs
src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LabelInfo.cs
src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightCompiler.cs
src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LocalVariables.cs
src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/LambdaExpression.cs
src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MethodCallExpression.cs
src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/CallSiteBinder.cs
src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Enumerables/RangeEnumerable.cs
src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Enumerables/RepeatEnumerable.cs
src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Partitioning/HashRepartitionEnumerator.cs
src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Partitioning/OrderedHashRepartitionEnumerator.cs
src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Partitioning/PartitionedDataSource.cs
src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Binary/UnionQueryOperator.cs
src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/QueryOperator.cs
src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/QuerySettings.cs
src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Unary/ContainsSearchOperator.cs
src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Unary/DistinctQueryOperator.cs
src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Unary/IndexedWhereQueryOperator.cs
src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Unary/SortQueryOperator.cs
src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Unary/WhereQueryOperator.cs
src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Utils/Sorting.cs
src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Utils/WrapperEqualityComparer.cs
src/libraries/System.Linq.Queryable/src/System/Linq/EnumerableRewriter.cs
src/libraries/System.Management/src/System/Management/ManagementBaseObject.cs
src/libraries/System.Management/src/System/Management/ManagementClass.cs
src/libraries/System.Management/src/System/Management/ManagementObject.cs
src/libraries/System.Management/src/System/Management/ManagementOptions.cs
src/libraries/System.Management/src/System/Management/ManagementPath.cs
src/libraries/System.Management/src/System/Management/ManagementScope.cs
src/libraries/System.Management/src/System/Management/Method.cs
src/libraries/System.Management/src/System/Management/Property.cs
src/libraries/System.Management/src/System/Management/WMIGenerator.cs
src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpHandler.cs
src/libraries/System.Net.Http/src/System/Net/Http/Headers/CacheControlHeaderValue.cs
src/libraries/System.Net.Http/src/System/Net/Http/HttpContent.cs
src/libraries/System.Net.Http/src/System/Net/Http/HttpTelemetry.cs
src/libraries/System.Net.Http/src/System/Net/Http/NetEventSource.Http.cs
src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http3Connection.cs
src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionPool.cs
src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpEnvironmentProxy.Unix.cs
src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpEnvironmentProxy.Windows.cs
src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerContext.cs
src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequest.cs
src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerResponse.cs
src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpConnection.cs
src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerResponse.Managed.cs
src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpStreamAsyncResult.cs
src/libraries/System.Net.HttpListener/src/System/Net/Managed/ListenerAsyncResult.Managed.cs
src/libraries/System.Net.HttpListener/src/System/Net/ServiceNameStore.cs
src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs
src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequest.Windows.cs
src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerResponse.Windows.cs
src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBase.cs
src/libraries/System.Net.Mail/src/System/Net/Mail/MailPriority.cs
src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs
src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpReplyReaderFactory.cs
src/libraries/System.Net.Mail/src/System/Net/Mime/MimeBasePart.cs
src/libraries/System.Net.Mail/src/System/Net/Mime/MimeMultiPart.cs
src/libraries/System.Net.Mail/src/System/Net/Mime/MimePart.cs
src/libraries/System.Net.Mail/src/System/Net/TrackingValidationObjectDictionary.cs
src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/BsdNetworkInterface.cs
src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/UnixIPGlobalProperties.cs
src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.Windows.cs
src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs
src/libraries/System.Net.Primitives/src/System/Net/CredentialCache.cs
src/libraries/System.Net.Primitives/src/System/Net/IPAddress.cs
src/libraries/System.Net.Requests/src/System/Net/FtpControlStream.cs
src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs
src/libraries/System.Net.Requests/src/System/Net/FtpWebResponse.cs
src/libraries/System.Net.Security/src/System/Net/Security/NetEventSource.Security.cs
src/libraries/System.Net.Security/src/System/Net/Security/SslStream.IO.cs
src/libraries/System.Net.Security/src/System/Net/Security/SslStream.Protocol.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Windows.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/TCPClient.cs
src/libraries/System.Net.WebClient/src/System/Net/WebClient.cs
src/libraries/System.Net.WebHeaderCollection/src/System/Net/WebHeaderCollection.cs
src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs
src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/DataCollector.cs
src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TypeAnalysis.cs
src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormatInfo.cs
src/libraries/System.Private.CoreLib/src/System/Globalization/OrdinalCasing.Icu.cs
src/libraries/System.Private.CoreLib/src/System/Globalization/TextInfo.cs
src/libraries/System.Private.CoreLib/src/System/IO/BufferedStream.cs
src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemEnumerator.Unix.cs
src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemEnumerator.Windows.cs
src/libraries/System.Private.CoreLib/src/System/IO/FileSystem.Windows.cs
src/libraries/System.Private.CoreLib/src/System/IO/StreamReader.cs
src/libraries/System.Private.CoreLib/src/System/IO/StreamWriter.cs
src/libraries/System.Private.CoreLib/src/System/IO/StringWriter.cs
src/libraries/System.Private.CoreLib/src/System/IO/TextWriter.cs
src/libraries/System.Private.CoreLib/src/System/Net/WebUtility.cs
src/libraries/System.Private.CoreLib/src/System/Runtime/Versioning/FrameworkName.cs
src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs
src/libraries/System.Private.CoreLib/src/System/Threading/PortableThreadPool.WaitThread.cs
src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskExceptionHolder.cs
src/libraries/System.Private.CoreLib/src/System/Threading/TimerQueue.Portable.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ClassDataContract.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CodeGenerator.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CollectionDataContract.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSerializer.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSet.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataMember.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExportOptions.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExtensionDataReader.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/HybridObjectCache.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/DataContractJsonSerializer.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonDataContract.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonEncodingStreamWrapper.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatGeneratorStatics.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatWriterGenerator.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonReaderDelegator.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ReflectionJsonFormatWriter.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonReader.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonWriter.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlObjectSerializerReadContextComplexJson.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ObjectReferenceStack.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/PrimitiveDataContract.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionReader.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionXmlFormatWriter.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaExporter.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaHelper.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ScopedKnownTypes.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SurrogateDataContract.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatGeneratorStatics.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatWriterGenerator.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializer.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerContext.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContext.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerWriteContext.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/EncodingStreamWrapper.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/UniqueId.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseReader.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseWriter.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReaderSession.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriter.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriterSession.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBufferReader.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlCanonicalWriter.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlConverter.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionary.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryReader.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryString.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryWriter.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlNodeWriter.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlSigningNodeWriter.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextReader.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextWriter.cs
src/libraries/System.Private.Uri/src/System/DomainNameHelper.cs
src/libraries/System.Private.Uri/src/System/UriExt.cs
src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XContainer.cs
src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNode.cs
src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNodeBuilder.cs
src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNodeReader.cs
src/libraries/System.Private.Xml.Linq/src/System/Xml/Schema/XNodeValidator.cs
src/libraries/System.Private.Xml.Linq/src/System/Xml/XPath/XNodeNavigator.cs
src/libraries/System.Private.Xml.Linq/src/System/Xml/XPath/XObjectExtensions.cs
src/libraries/System.Private.Xml/src/System/Xml/Base64Encoder.cs
src/libraries/System.Private.Xml/src/System/Xml/Base64EncoderAsync.cs
src/libraries/System.Private.Xml/src/System/Xml/BinaryXml/XmlBinaryReader.cs
src/libraries/System.Private.Xml/src/System/Xml/BitStack.cs
src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathDocumentBuilder.cs
src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathDocumentNavigator.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/HtmlEncodedRawTextWriter.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/HtmlUtf8RawTextWriter.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriter.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriterAsync.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/XmlRawWriter.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/XmlRawWriterAsync.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/XmlReader.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/XmlReaderAsync.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSubtreeReader.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplAsync.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextWriter.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/XmlValidatingReaderImpl.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriter.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterAsync.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/XsdCachingReader.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReader.cs
src/libraries/System.Private.Xml/src/System/Xml/DiagnosticsSwitches.cs
src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentSchemaValidator.cs
src/libraries/System.Private.Xml/src/System/Xml/Dom/DomNameTable.cs
src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocument.cs
src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocumentType.cs
src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElement.cs
src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElementList.cs
src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlName.cs
src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNode.cs
src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeReader.cs
src/libraries/System.Private.Xml/src/System/Xml/Schema/BaseProcessor.cs
src/libraries/System.Private.Xml/src/System/Xml/Schema/ContentValidator.cs
src/libraries/System.Private.Xml/src/System/Xml/Schema/DataTypeImplementation.cs
src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParser.cs
src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdValidator.cs
src/libraries/System.Private.Xml/src/System/Xml/Schema/FacetChecker.cs
src/libraries/System.Private.Xml/src/System/Xml/Schema/Inference/Infer.cs
src/libraries/System.Private.Xml/src/System/Xml/Schema/Preprocessor.cs
src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionCompiler.cs
src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaDeclBase.cs
src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaElementDecl.cs
src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaInfo.cs
src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaSetCompiler.cs
src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrBuilder.cs
src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrValidator.cs
src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchema.cs
src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAttributeGroup.cs
src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaCollection.cs
src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaComplexType.cs
src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaElement.cs
src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaObject.cs
src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSet.cs
src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidator.cs
src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlValueConverter.cs
src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdBuilder.cs
src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdValidator.cs
src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerator.cs
src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compilation.cs
src/libraries/System.Private.Xml/src/System/Xml/Serialization/ImportContext.cs
src/libraries/System.Private.Xml/src/System/Xml/Serialization/Mappings.cs
src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationReader.cs
src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs
src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaImporter.cs
src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapReflectionImporter.cs
src/libraries/System.Private.Xml/src/System/Xml/Serialization/Types.cs
src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMapping.cs
src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs
src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs
src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs
src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs
src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs
src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs
src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs
src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs
src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs
src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerNamespaces.cs
src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/CompiledXPathExpr.cs
src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/FollSiblingQuery.cs
src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/QueryBuilder.cs
src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathDocument.cs
src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathException.cs
src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigator.cs
src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigatorReader.cs
src/libraries/System.Private.Xml/src/System/Xml/XmlComplianceUtil.cs
src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs
src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/GenerateHelper.cs
src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/StaticDataManager.cs
src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILConstructAnalyzer.cs
src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILOptimizerVisitor.cs
src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilCloneVisitor.cs
src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilXmlWriter.cs
src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/DocumentOrderComparer.cs
src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/WhitespaceRuleReader.cs
src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlExtensionFunction.cs
src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryContext.cs
src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryOutput.cs
src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryRuntime.cs
src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlSortKeyAccumulator.cs
src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltFunctions.cs
src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltLibrary.cs
src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlILCommand.cs
src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilGenerator.cs
src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilGeneratorEnv.cs
src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilStrConcatenator.cs
src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XslAst.cs
src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XsltLoader.cs
src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ActionFrame.cs
src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Compiler.cs
src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ContainerAction.cs
src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ForEachAction.cs
src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/InputScope.cs
src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Processor.cs
src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ReaderOutput.cs
src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/RecordBuilder.cs
src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/RootAction.cs
src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/SequentialOutput.cs
src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Stylesheet.cs
src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TemplateLookupAction.cs
src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TemplateManager.cs
src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/XsltOutput.cs
src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/CustomType.cs
src/libraries/System.Reflection.DispatchProxy/src/System/Reflection/DispatchProxyGenerator.cs
src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/ControlFlowBuilder.cs
src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/NamespaceCache.cs
src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.cs
src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/EventDefinition.cs
src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/PropertyDefinition.cs
src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/Runtime/BindingFlagSupport/PropertyPolicies.cs
src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Assemblies/RoAssembly.GetForwardedTypes.cs
src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/General/Helpers.cs
src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/MethodBase/Ecma/EcmaMethodDecoder.cs
src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/RuntimeTypeInfo.BindingFlags.cs
src/libraries/System.Resources.Extensions/src/System/Resources/Extensions/DeserializingResourceReader.cs
src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheItemPolicy.cs
src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCache.cs
src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCacheEntry.cs
src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Analyzers/AddDisableRuntimeMarshallingAttributeFixer.cs
src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/LibraryImportGenerator.cs
src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/ManualTypeMarshallingHelper.cs
src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/SerializationEventsCache.cs
src/libraries/System.Security.Claims/src/System/Security/Claims/Claim.cs
src/libraries/System.Security.Claims/src/System/Security/Claims/ClaimsIdentity.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12Builder.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12CertBag.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SafeBag.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SafeContents.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SecretBag.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfo.cs
src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedKey.cs
src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedReference.cs
src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedType.cs
src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedXml.cs
src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfo.cs
src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoX509Data.cs
src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Reference.cs
src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Signature.cs
src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXml.cs
src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDecryptionTransform.cs
src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigEnvelopedSignatureTransform.cs
src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CapiHelper.Windows.cs
src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.Create.cs
src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/Oid.cs
src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/OidCollection.cs
src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/PasswordDeriveBytes.Windows.cs
src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SHAHashProvider.Browser.Managed.cs
src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/CertificateData.ManagedDecode.cs
src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/ChainPal.Android.cs
src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/OpenSslX509ChainProcessor.cs
src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/UnixPkcs12Reader.cs
src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X500DistinguishedName.cs
src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Certificate2.cs
src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Chain.cs
src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509SignatureGenerator.cs
src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/XmlKeyHelper.cs
src/libraries/System.Security.Permissions/src/System/Security/Permissions/PrincipalPermission.cs
src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/IdentityNotMappedException.cs
src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/WindowsIdentity.cs
src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10FeedFormatter.cs
src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/AtomPub10ServiceDocumentFormatter.cs
src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ResourceCollectionInfo.cs
src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Rss20FeedFormatter.cs
src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtension.cs
src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtensionCollection.cs
src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/XmlSyndicationContent.cs
src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceBase.cs
src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceController.cs
src/libraries/System.Speech/src/Recognition/Grammar.cs
src/libraries/System.Speech/src/Recognition/RecognizerBase.cs
src/libraries/System.Speech/src/Synthesis/VoiceInfo.cs
src/libraries/System.Text.Encoding.CodePages/src/System/Text/DecoderBestFitFallback.cs
src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncoderBestFitFallback.cs
src/libraries/System.Text.Json/src/System/Text/Json/BitStack.cs
src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonArray.cs
src/libraries/System.Text.Json/src/System/Text/Json/Serialization/IgnoreReferenceResolver.cs
src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Converters.cs
src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfo.Cache.cs
src/libraries/System.Threading.Tasks.Dataflow/src/Base/DataflowBlock.cs
src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BatchBlock.cs
src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/TransformManyBlock.cs
src/libraries/System.Threading.Tasks.Parallel/src/System/Threading/Tasks/Parallel.cs
src/libraries/System.Transactions.Local/src/System/Transactions/DurableEnlistmentState.cs
src/libraries/System.Transactions.Local/src/System/Transactions/Transaction.cs
src/libraries/System.Transactions.Local/src/System/Transactions/TransactionManager.cs
src/libraries/System.Transactions.Local/src/System/Transactions/TransactionScope.cs
src/libraries/System.Transactions.Local/src/System/Transactions/TransactionState.cs
src/libraries/System.Transactions.Local/src/System/Transactions/VolatileEnlistmentState.cs
src/libraries/System.Web.HttpUtility/src/System/Web/Util/HttpEncoder.cs
src/libraries/System.Windows.Extensions/src/System/Media/SoundPlayer.cs
src/mono/System.Private.CoreLib/src/System/Delegate.Mono.cs
src/mono/System.Private.CoreLib/src/System/Reflection/CustomAttribute.cs
src/mono/System.Private.CoreLib/src/System/Reflection/Emit/DynamicMethod.cs
src/mono/System.Private.CoreLib/src/System/Reflection/Emit/ILGenerator.Mono.cs
src/mono/System.Private.CoreLib/src/System/Reflection/Emit/MethodBuilder.Mono.cs
src/mono/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.Mono.cs
src/mono/System.Private.CoreLib/src/System/Reflection/Emit/SignatureHelper.cs
src/mono/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.Mono.cs
src/mono/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs
src/mono/System.Private.CoreLib/src/System/Reflection/RuntimeEventInfo.cs
src/mono/System.Private.CoreLib/src/System/Reflection/RuntimeFieldInfo.cs
src/mono/System.Private.CoreLib/src/System/RuntimeType.Mono.cs
src/mono/System.Private.CoreLib/src/System/TypeNameParser.cs
src/mono/System.Private.CoreLib/src/System/TypeSpec.cs

index f87435f..6498a25 100644 (file)
@@ -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;
         }
index a1f913b..93c80fc 100644 (file)
@@ -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;
 
index cc0c86e..3310d40 100644 (file)
@@ -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);
index 63d6e61..ec93522 100644 (file)
@@ -348,12 +348,7 @@ namespace System.Runtime.Serialization
                     return ArrayElementType.TypeArguments;
                 }
 
-                if (_typeArguments == null)
-                {
-                    _typeArguments = new CodeTypeReferenceCollection();
-                }
-
-                return _typeArguments;
+                return _typeArguments ??= new CodeTypeReferenceCollection();
             }
         }
 
index 87d936a..fdfc440 100644 (file)
@@ -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)
                 {
index 1e0ee27..b87c74d 100644 (file)
@@ -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;
                 }
index ffbbc20..a292310 100644 (file)
@@ -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<byte>();
+                arg1 ??= "";
+                arg2 ??= "";
+                arg3 ??= Array.Empty<byte>();
 
                 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)
index cdb7103..8dae80d 100644 (file)
@@ -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
         {
index 47daaaf..89fb18d 100644 (file)
@@ -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
index 01768ac..c64aff3 100644 (file)
@@ -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<string, PrecannedResource>(FastResourceComparer.Default);
+            _preserializedData ??= new Dictionary<string, PrecannedResource>(FastResourceComparer.Default);
 
             _preserializedData.Add(name, new PrecannedResource(typeName, data));
         }
index 73a12ea..9da0795 100644 (file)
@@ -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();
                     }
index b1ddcdd..4b1c520 100644 (file)
@@ -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
         {
index b68929a..7c000b1 100644 (file)
@@ -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)
             {
index 343684e..9052ad6 100644 (file)
@@ -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;
index 6b71421..3422730 100644 (file)
@@ -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<string>();
-                }
+                _sourceItfs ??= new LinkedList<string>();
                 _sourceItfs.AddLast(itfName);
             }
             else
             {
-                if (_itfs == null)
-                {
-                    _itfs = new LinkedList<string>();
-                }
-
+                _itfs ??= new LinkedList<string>();
                 _itfs.AddLast(itfName);
             }
         }
index 1c0bd12..7776fe9 100644 (file)
@@ -282,10 +282,7 @@ namespace Microsoft.CSharp.RuntimeBinder.ComInterop
         [RequiresUnreferencedCode(Binder.TrimmerWarning)]
         internal override IList<KeyValuePair<string, object>> GetMembers(IEnumerable<string> names)
         {
-            if (names == null)
-            {
-                names = GetMemberNames(true);
-            }
+            names ??= GetMemberNames(true);
 
             Type comType = RuntimeCallableWrapper.GetType();
 
index 2a0c30a..354da7b 100644 (file)
@@ -32,10 +32,7 @@ namespace Microsoft.CSharp.RuntimeBinder.ComInterop
             Debug.Assert(args != null);
 
             // Create a CallSite and invoke it.
-            if (_site == null)
-            {
-                _site = CallSite<Func<CallSite, object, object[], object>>.Create(SplatInvokeBinder.Instance);
-            }
+            _site ??= CallSite<Func<CallSite, object, object[], object>>.Create(SplatInvokeBinder.Instance);
 
             return _site.Target(_site, _callable, args);
         }
index 6bd081d..11c4133 100644 (file)
@@ -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;
index a30b08e..3a0e6ae 100644 (file)
@@ -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()
index 5092e2a..5941f74 100644 (file)
@@ -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;
                     }
                 }
index b27c38f..e060dee 100644 (file)
@@ -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.
index f730892..36a9ff0 100644 (file)
@@ -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);
         }
index a6f8b26..6f6ad50 100644 (file)
@@ -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)]
index 291a1fa..4e8750f 100644 (file)
@@ -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
index 539221a..df3805e 100644 (file)
@@ -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);
index 9e0b4e3..17c5d34 100644 (file)
@@ -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;
         }
index 73a8a86..8067a66 100644 (file)
@@ -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<Func<IServiceProvider, object>>();
-            }
+            argument.Factories ??= new List<Func<IServiceProvider, object>>();
 
             // 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<object?>();
-            }
+            argument.Constants ??= new List<object?>();
 
             // this.Constants[i]
             argument.Generator.Emit(OpCodes.Ldarg_0);
index 4198379..26335fe 100644 (file)
@@ -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;
index 6bcdd35..867fadd 100644 (file)
@@ -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)
                 {
index 1800f36..12601f2 100644 (file)
@@ -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)
index b51f570..7e2967a 100644 (file)
@@ -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);
             }
         }
 
index 8a069df..86524a2 100644 (file)
@@ -47,11 +47,7 @@ namespace Microsoft.Extensions.Logging
                 }
                 catch (Exception ex)
                 {
-                    if (exceptions == null)
-                    {
-                        exceptions = new List<Exception>();
-                    }
-
+                    exceptions ??= new List<Exception>();
                     exceptions.Add(ex);
                 }
             }
@@ -99,11 +95,7 @@ namespace Microsoft.Extensions.Logging
                 }
                 catch (Exception ex)
                 {
-                    if (exceptions == null)
-                    {
-                        exceptions = new List<Exception>();
-                    }
-
+                    exceptions ??= new List<Exception>();
                     exceptions.Add(ex);
                 }
 
@@ -137,11 +129,7 @@ namespace Microsoft.Extensions.Logging
                 }
                 catch (Exception ex)
                 {
-                    if (exceptions == null)
-                    {
-                        exceptions = new List<Exception>();
-                    }
-
+                    exceptions ??= new List<Exception>();
                     exceptions.Add(ex);
                 }
             }
index 4f88f4a..315ea91 100644 (file)
@@ -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);
             }
index ca55c34..e1cd920 100644 (file)
@@ -61,10 +61,7 @@ namespace System.CodeDom
         {
             get
             {
-                if (_implementationTypes == null)
-                {
-                    _implementationTypes = new CodeTypeReferenceCollection();
-                }
+                _implementationTypes ??= new CodeTypeReferenceCollection();
 
                 if ((_populated & ImplTypesCollection) == 0)
                 {
index 0f0edfe..b2a08cf 100644 (file)
@@ -30,10 +30,7 @@ namespace System.CodeDom.Compiler
                 {
                     lock (this)
                     {
-                        if (_type == null)
-                        {
-                            _type = Type.GetType(_codeDomProviderTypeName);
-                        }
+                        _type ??= Type.GetType(_codeDomProviderTypeName);
                     }
                 }
 
index e4ec985..22cbad3 100644 (file)
@@ -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);
                 }
             }
index 22910ff..ac906d6 100644 (file)
@@ -926,10 +926,7 @@ namespace System.Collections.Concurrent
                     }
 
                     // defer allocation to avoid false sharing
-                    if (_localList == null)
-                    {
-                        _localList = new KeyValuePair<long, TSource>[_maxChunkSize];
-                    }
+                    _localList ??= new KeyValuePair<long, TSource>[_maxChunkSize];
 
                     // make the actual call to the enumerable that grabs a chunk
                     return _enumerable.GrabChunk(_localList, requestedChunkSize, ref _currentChunkSize!.Value);
index 503ea37..ad22b0b 100644 (file)
@@ -19,14 +19,11 @@ namespace System.Collections.Immutable
 
         public static void TryAdd(T item)
         {
+            Stack<RefAsValueType<T>> localStack =
 #if NETCOREAPP
-            Stack<RefAsValueType<T>>? localStack = t_stack; // cache in a local to avoid unnecessary TLS hits on repeated accesses
-            if (localStack == null)
-            {
-                t_stack = localStack = new Stack<RefAsValueType<T>>(MaxSize);
-            }
+                t_stack ??= new Stack<RefAsValueType<T>>(MaxSize);
 #else
-            Stack<RefAsValueType<T>> 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<Type, object>? typesToStacks = AllocFreeConcurrentStack.t_stacks;
-                if (typesToStacks == null)
-                {
-                    AllocFreeConcurrentStack.t_stacks = typesToStacks = new Dictionary<Type, object>();
-                }
+                Dictionary<Type, object>? typesToStacks = AllocFreeConcurrentStack.t_stacks ??= new Dictionary<Type, object>();
 
                 // Get the stack that corresponds to the T
                 if (!typesToStacks.TryGetValue(s_typeOfT, out object? stackObj))
index e1d6e00..73a0b69 100644 (file)
@@ -735,10 +735,7 @@ namespace System.Collections.Immutable
             {
                 if (match(self.array[i]))
                 {
-                    if (removeIndices == null)
-                    {
-                        removeIndices = new List<int>();
-                    }
+                    removeIndices ??= new List<int>();
 
                     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<T>.Default;
-                }
+                comparer ??= Comparer<T>.Default;
 
                 // Avoid copying the entire array when the array is already sorted.
                 bool outOfOrder = false;
index 1c89245..2dc5938 100644 (file)
@@ -505,12 +505,7 @@ namespace System.Collections.Immutable
                 // Creating an instance of ImmutableSortedMap<T> 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<TKey, TValue>.Wrap(_root, _comparers, _count);
-                }
-
-                return _immutable;
+                return _immutable ??= ImmutableDictionary<TKey, TValue>.Wrap(_root, _comparers, _count);
             }
 
             #endregion
@@ -744,17 +739,6 @@ namespace System.Collections.Immutable
         /// Gets a simple debugger-viewable collection.
         /// </summary>
         [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
-        public KeyValuePair<TKey, TValue>[] Contents
-        {
-            get
-            {
-                if (_contents == null)
-                {
-                    _contents = _map.ToArray(_map.Count);
-                }
-
-                return _contents;
-            }
-        }
+        public KeyValuePair<TKey, TValue>[] Contents => _contents ??= _map.ToArray(_map.Count);
     }
 }
index 0fb3c5d..40340e6 100644 (file)
@@ -424,15 +424,8 @@ namespace System.Collections.Immutable
         /// </summary>
         public ImmutableDictionary<TKey, TValue> WithComparers(IEqualityComparer<TKey>? keyComparer, IEqualityComparer<TValue>? valueComparer)
         {
-            if (keyComparer == null)
-            {
-                keyComparer = EqualityComparer<TKey>.Default;
-            }
-
-            if (valueComparer == null)
-            {
-                valueComparer = EqualityComparer<TValue>.Default;
-            }
+            keyComparer ??= EqualityComparer<TKey>.Default;
+            valueComparer ??= EqualityComparer<TValue>.Default;
 
             if (this.KeyComparer == keyComparer)
             {
index 006a26a..9c1f19b 100644 (file)
@@ -219,10 +219,7 @@ namespace System.Collections.Immutable
             {
                 get
                 {
-                    if (_collection == null)
-                    {
-                        _collection = _sequence.ToArray();
-                    }
+                    _collection ??= _sequence.ToArray();
 
                     return _collection[index];
                 }
index 2a83032..3faf07a 100644 (file)
@@ -194,12 +194,7 @@ namespace System.Collections.Immutable
                 // Creating an instance of ImmutableSortedMap<T> 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<T>.Wrap(_root, _equalityComparer, _count);
-                }
-
-                return _immutable;
+                return _immutable ??= ImmutableHashSet<T>.Wrap(_root, _equalityComparer, _count);
             }
 
             /// <summary>
index 92077a5..02dc0af 100644 (file)
@@ -418,10 +418,7 @@ namespace System.Collections.Immutable
         /// </summary>
         public ImmutableHashSet<T> WithComparer(IEqualityComparer<T>? equalityComparer)
         {
-            if (equalityComparer == null)
-            {
-                equalityComparer = EqualityComparer<T>.Default;
-            }
+            equalityComparer ??= EqualityComparer<T>.Default;
 
             if (equalityComparer == _equalityComparer)
             {
index c10cfa1..1b4494e 100644 (file)
@@ -1023,12 +1023,7 @@ namespace System.Collections.Immutable
                 // Creating an instance of ImmutableList<T> 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<T>.WrapNode(this.Root);
-                }
-
-                return _immutable;
+                return _immutable ??= ImmutableList<T>.WrapNode(this.Root);
             }
 
             #endregion
@@ -1219,17 +1214,6 @@ namespace System.Collections.Immutable
         /// Gets a simple debugger-viewable list.
         /// </summary>
         [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);
     }
 }
index bc64c46..2a2315f 100644 (file)
@@ -1038,10 +1038,7 @@ namespace System.Collections.Immutable
                 {
                     if (match(item))
                     {
-                        if (list == null)
-                        {
-                            list = new List<T>();
-                        }
+                        list ??= new List<T>();
 
                         list.Add(item);
                     }
index 1f2ae3e..b7ee9d7 100644 (file)
@@ -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;
index 75bb852..dc203b5 100644 (file)
@@ -640,12 +640,7 @@ namespace System.Collections.Immutable
                 // Creating an instance of ImmutableSortedMap<T> 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.
         /// </summary>
         [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
-        public KeyValuePair<TKey, TValue>[] Contents
-        {
-            get
-            {
-                if (_contents == null)
-                {
-                    _contents = _map.ToArray(_map.Count);
-                }
-
-                return _contents;
-            }
-        }
+        public KeyValuePair<TKey, TValue>[] Contents => _contents ??= _map.ToArray(_map.Count);
     }
 }
index 2648014..a997c93 100644 (file)
@@ -328,15 +328,8 @@ namespace System.Collections.Immutable
         /// </summary>
         public ImmutableSortedDictionary<TKey, TValue> WithComparers(IComparer<TKey>? keyComparer, IEqualityComparer<TValue>? valueComparer)
         {
-            if (keyComparer == null)
-            {
-                keyComparer = Comparer<TKey>.Default;
-            }
-
-            if (valueComparer == null)
-            {
-                valueComparer = EqualityComparer<TValue>.Default;
-            }
+            keyComparer ??= Comparer<TKey>.Default;
+            valueComparer ??= EqualityComparer<TValue>.Default;
 
             if (keyComparer == _keyComparer)
             {
index fdb44bd..3771963 100644 (file)
@@ -456,12 +456,7 @@ namespace System.Collections.Immutable
                 // Creating an instance of ImmutableSortedSet<T> 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<T>.Wrap(this.Root, _comparer);
-                }
-
-                return _immutable;
+                return _immutable ??= ImmutableSortedSet<T>.Wrap(this.Root, _comparer);
             }
 
             /// <summary>
index a1871e4..4ee94f6 100644 (file)
@@ -340,10 +340,7 @@ namespace System.Collections.Immutable
         /// </summary>
         public ImmutableSortedSet<T> WithComparer(IComparer<T>? comparer)
         {
-            if (comparer == null)
-            {
-                comparer = Comparer<T>.Default;
-            }
+            comparer ??= Comparer<T>.Default;
 
             if (comparer == _comparer)
             {
index 34f9e3b..5dc4019 100644 (file)
@@ -167,10 +167,7 @@ namespace System.Linq
                 return false;
             }
 
-            if (comparer == null)
-            {
-                comparer = EqualityComparer<TBase>.Default;
-            }
+            comparer ??= EqualityComparer<TBase>.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<TBase>.Default;
-            }
+            comparer ??= EqualityComparer<TBase>.Default;
 
             int i = 0;
             int n = immutableArray.Length;
index c385f1e..0c84d46 100644 (file)
@@ -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.
index 151b361..658b63b 100644 (file)
@@ -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
         {
index 9947faf..3cf850e 100644 (file)
@@ -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
         {
index b1cae78..c047eac 100644 (file)
@@ -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.
index be3f840..86e27dc 100644 (file)
@@ -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();
         }
 
index 9c75a8e..82a136e 100644 (file)
@@ -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
         /// <para>Returns a <see cref='System.Collections.Specialized.NameObjectCollectionBase.KeysCollection'/> instance containing
         ///    all the keys in the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para>
         /// </devdoc>
-        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
index c567ede..5bb2723 100644 (file)
@@ -387,14 +387,6 @@ namespace System.Collections.Specialized
         /// <devdoc>
         /// <para>Gets all the keys in the <see cref='System.Collections.Specialized.NameValueCollection'/>. </para>
         /// </devdoc>
-        public virtual string?[] AllKeys
-        {
-            get
-            {
-                if (_allKeys == null)
-                    _allKeys = BaseGetAllKeys();
-                return _allKeys;
-            }
-        }
+        public virtual string?[] AllKeys => _allKeys ??= BaseGetAllKeys();
     }
 }
index ce5f346..8925d08 100644 (file)
@@ -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<TKey> IDictionary<TKey, TValue>.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<TValue> IDictionary<TKey, TValue>.Values
         {
@@ -899,14 +885,7 @@ namespace System.Collections.Generic
 
             public KeyValuePairComparer(IComparer<TKey>? keyComparer)
             {
-                if (keyComparer == null)
-                {
-                    this.keyComparer = Comparer<TKey>.Default;
-                }
-                else
-                {
-                    this.keyComparer = keyComparer;
-                }
+                this.keyComparer = keyComparer ?? Comparer<TKey>.Default;
             }
 
             public override int Compare(KeyValuePair<TKey, TValue> x, KeyValuePair<TKey, TValue> y)
index da67926..3588586 100644 (file)
@@ -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<KeyValuePair<TKey, TValue>>.IsReadOnly
         {
index 792d495..988cc21 100644 (file)
@@ -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
index 698b95b..a8f1458 100644 (file)
@@ -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 }
index 73684d7..ffe523a 100644 (file)
@@ -105,18 +105,7 @@ namespace System.ComponentModel.DataAnnotations
         /// <summary>
         /// Gets a unique identifier for this attribute.
         /// </summary>
-        public override object TypeId
-        {
-            get
-            {
-                if (_typeId is null)
-                {
-                    _typeId = new Tuple<string, Type>(Method, ValidatorType);
-                }
-
-                return _typeId;
-            }
-        }
+        public override object TypeId => _typeId ??= new Tuple<string, Type>(Method, ValidatorType);
 
         /// <summary>
         ///     Gets the name of the method in <see cref="ValidatorType" /> to invoke to perform validation.
index d122453..93ac5eb 100644 (file)
@@ -201,10 +201,7 @@ namespace System.ComponentModel.DataAnnotations
                 {
                     lock (_syncRoot)
                     {
-                        if (_propertyStoreItems == null)
-                        {
-                            _propertyStoreItems = CreatePropertyStoreItems();
-                        }
+                        _propertyStoreItems ??= CreatePropertyStoreItems();
                     }
                 }
 
index 77b84b7..d12b928 100644 (file)
@@ -40,10 +40,7 @@ namespace System.ComponentModel.Composition.Registration
 
         public ExportBuilder AddMetadata(string name, object value)
         {
-            if (_metadataItems == null)
-            {
-                _metadataItems = new List<Tuple<string, object>>();
-            }
+            _metadataItems ??= new List<Tuple<string, object>>();
             _metadataItems.Add(Tuple.Create(name, value));
 
             return this;
@@ -51,10 +48,7 @@ namespace System.ComponentModel.Composition.Registration
 
         public ExportBuilder AddMetadata(string name, Func<Type, object> itemFunc)
         {
-            if (_metadataItemFuncs == null)
-            {
-                _metadataItemFuncs = new List<Tuple<string, Func<Type, object>>>();
-            }
+            _metadataItemFuncs ??= new List<Tuple<string, Func<Type, object>>>();
             _metadataItemFuncs.Add(Tuple.Create(name, itemFunc));
 
             return this;
@@ -62,10 +56,7 @@ namespace System.ComponentModel.Composition.Registration
 
         internal void BuildAttributes(Type type, ref List<Attribute> attributes)
         {
-            if (attributes == null)
-            {
-                attributes = new List<Attribute>();
-            }
+            attributes ??= new List<Attribute>();
 
             if (_isInherited)
             {
index 1b96998..d9bd476 100644 (file)
@@ -94,10 +94,7 @@ namespace System.ComponentModel.Composition.Registration
                 };
             }
 
-            if (attributes == null)
-            {
-                attributes = new List<Attribute>();
-            }
+            attributes ??= new List<Attribute>();
 
             attributes.Add(importAttribute);
         }
index 8374779..5a07d74 100644 (file)
@@ -212,10 +212,7 @@ namespace System.ComponentModel.Composition.Registration
 
         public PartBuilder AddMetadata(string name, object value)
         {
-            if (_metadataItems == null)
-            {
-                _metadataItems = new List<Tuple<string, object>>();
-            }
+            _metadataItems ??= new List<Tuple<string, object>>();
             _metadataItems.Add(Tuple.Create(name, value));
 
             return this;
@@ -223,10 +220,7 @@ namespace System.ComponentModel.Composition.Registration
 
         public PartBuilder AddMetadata(string name, Func<Type, object> itemFunc)
         {
-            if (_metadataItemFuncs == null)
-            {
-                _metadataItemFuncs = new List<Tuple<string, Func<Type, object>>>();
-            }
+            _metadataItemFuncs ??= new List<Tuple<string, Func<Type, object>>>();
             _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<Tuple<object, List<Attribute>>> configuredMembers, Action<ParameterInfo, ImportBuilder> configureConstuctorImports)
         {
-            if (configuredMembers == null)
-            {
-                configuredMembers = new List<Tuple<object, List<Attribute>>>();
-            }
+            configuredMembers ??= new List<Tuple<object, List<Attribute>>>();
 
             // 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<Tuple<object, List<Attribute>>>();
-                        }
+                        configuredMembers ??= new List<Tuple<object, List<Attribute>>>();
 
                         configuredMembers.Add(Tuple.Create((object)declaredPi, attributes));
                     }
index 375d3fd..ace4c8b 100644 (file)
@@ -126,10 +126,7 @@ namespace System.ComponentModel.Composition.Registration
                                 var lambdaExpression = (LambdaExpression)parameter;
                                 Delegate importDelegate = lambdaExpression.Compile();
 
-                                if (_importBuilders == null)
-                                {
-                                    _importBuilders = new Dictionary<ParameterInfo, Action<ImportBuilder>>();
-                                }
+                                _importBuilders ??= new Dictionary<ParameterInfo, Action<ImportBuilder>>();
 
                                 _importBuilders.Add(parameterInfos[index], (Action<ImportBuilder>)importDelegate);
                                 ++index;
index b3f6096..339c3ae 100644 (file)
@@ -131,10 +131,7 @@ namespace Microsoft.Internal.Collections
 
         private static List<T> FastAppendToListAllowNulls<T>(this List<T>? source, T value)
         {
-            if (source == null)
-            {
-                source = new List<T>();
-            }
+            source ??= new List<T>();
             source.Add(value);
 
             return source;
index 4fe4123..d4de703 100644 (file)
@@ -175,10 +175,7 @@ namespace System.ComponentModel.Composition.AttributedModel
         {
             get
             {
-                if (_partCreationPolicy == null)
-                {
-                    _partCreationPolicy = _type.GetFirstAttribute<PartCreationPolicyAttribute>() ?? PartCreationPolicyAttribute.Default;
-                }
+                _partCreationPolicy ??= _type.GetFirstAttribute<PartCreationPolicyAttribute>() ?? PartCreationPolicyAttribute.Default;
 
                 return _partCreationPolicy.CreationPolicy;
             }
index 2ee4094..b747320 100644 (file)
@@ -93,10 +93,7 @@ namespace System.ComponentModel.Composition.Hosting
 
             Requires.NotNull(completeAction, nameof(completeAction));
 
-            if (_completeActionList == null)
-            {
-                _completeActionList = new List<Action>();
-            }
+            _completeActionList ??= new List<Action>();
             _completeActionList.Add(completeAction);
         }
 
@@ -108,10 +105,7 @@ namespace System.ComponentModel.Composition.Hosting
 
             Requires.NotNull(revertAction, nameof(revertAction));
 
-            if (_revertActionList == null)
-            {
-                _revertActionList = new List<Action>();
-            }
+            _revertActionList ??= new List<Action>();
             _revertActionList.Add(revertAction);
         }
 
index 3b785e6..a2f6cbb 100644 (file)
@@ -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
             {
index 55c7455..5bbf40e 100644 (file)
@@ -625,10 +625,7 @@ namespace System.ComponentModel.Composition.Hosting
                 List<ComposablePart>? partList;
 
                 ConditionalWeakTable<object, List<ComposablePart>>? gcRoots = _gcRoots;
-                if (gcRoots == null)
-                {
-                    gcRoots = new ConditionalWeakTable<object, List<ComposablePart>>();
-                }
+                gcRoots ??= new ConditionalWeakTable<object, List<ComposablePart>>();
 
                 if (!gcRoots.TryGetValue(exportedValue, out partList))
                 {
index de2d80b..d16314d 100644 (file)
@@ -342,10 +342,7 @@ namespace System.ComponentModel.Composition.Hosting
             {
                 if (parts.Remove(part))
                 {
-                    if (partsToRemove == null)
-                    {
-                        partsToRemove = new List<ComposablePart>();
-                    }
+                    partsToRemove ??= new List<ComposablePart>();
                     partsToRemove.Add(part);
                 }
             }
index c5c6b4b..8046b0b 100644 (file)
@@ -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<string, object?>();
-                }
+                metadata ??= new Dictionary<string, object?>();
                 metadata[CompositionConstants.ImportSourceMetadataName] = attributedImport.Source;
             }
 
index d7b452f..f527bef 100644 (file)
@@ -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))
             {
index 28ebe1f..30d0a2f 100644 (file)
@@ -224,10 +224,7 @@ namespace System.ComponentModel.Composition.Hosting
                 exports = null;
             }
 
-            if (exports == null)
-            {
-                exports = Array.Empty<Export>();
-            }
+            exports ??= Array.Empty<Export>();
 
             return checkResult;
         }
index 06ed592..0e0cbed 100644 (file)
@@ -93,21 +93,12 @@ namespace System.ComponentModel.Composition.Hosting
         ///     A <see cref="IEnumerable{T}"/> of strings representing the contract names of
         ///     the exports that have changed in the <see cref="CompositionContainer"/>.
         /// </value>
-        public IEnumerable<string> ChangedContractNames
-        {
-            get
-            {
-                if (_changedContractNames == null)
-                {
-                    _changedContractNames = AddedExports
-                        .Concat(RemovedExports)
-                        .Select(export => export.ContractName)
-                        .Distinct()
-                        .ToArray();
-                }
-                return _changedContractNames;
-            }
-        }
+        public IEnumerable<string> ChangedContractNames =>
+            _changedContractNames ??= AddedExports
+                                      .Concat(RemovedExports)
+                                      .Select(export => export.ContractName)
+                                      .Distinct()
+                                      .ToArray();
 
         /// <summary>
         ///     Gets the atomicComposition, if any, that this change applies to.
index d0f2715..085cc7a 100644 (file)
@@ -75,10 +75,7 @@ namespace System.ComponentModel.Composition.Hosting
                                 {
                                     if (import.IsImportDependentOnPart(candidateReachablePart, export, part.IsGeneric() != candidateReachablePart.IsGeneric()))
                                     {
-                                        if (reachablePartList == null)
-                                        {
-                                            reachablePartList = new List<ComposablePartDefinition>();
-                                        }
+                                        reachablePartList ??= new List<ComposablePartDefinition>();
                                         reachablePartList.Add(candidateReachablePart);
                                     }
                                 }
index f14b829..9c456ec 100644 (file)
@@ -82,10 +82,7 @@ namespace System.ComponentModel.Composition.Hosting
                             {
                                 if (import.IsImportDependentOnPart(part, export, part.IsGeneric() != candidateReachablePart.IsGeneric()))
                                 {
-                                    if (reachablePartList == null)
-                                    {
-                                        reachablePartList = new List<ComposablePartDefinition>();
-                                    }
+                                    reachablePartList ??= new List<ComposablePartDefinition>();
                                     reachablePartList.Add(candidateReachablePart);
                                 }
                             }
index ad16329..64ba13f 100644 (file)
@@ -65,11 +65,7 @@ namespace System.ComponentModel.Composition.Hosting
                     return Enumerable.Empty<string>();
                 }
 
-                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<ImportDefinition, Export[]?>();
-                }
-
+                _importCache ??= new Dictionary<ImportDefinition, Export[]?>();
                 _importCache[import] = exports;
             }
 
@@ -154,10 +146,7 @@ namespace System.ComponentModel.Composition.Hosting
                 {
                     if (export is IDisposable disposableExport)
                     {
-                        if (disposableExports == null)
-                        {
-                            disposableExports = new List<IDisposable>();
-                        }
+                        disposableExports ??= new List<IDisposable>();
                         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<ImportDefinition, List<IDisposable>>();
-                    }
+                    _importedDisposableExports ??= new Dictionary<ImportDefinition, List<IDisposable>>();
                     _importedDisposableExports[import] = disposableExports;
                 }
             }
index e68780f..712f542 100644 (file)
@@ -269,18 +269,8 @@ namespace System.ComponentModel.Composition.Primitives
         ///         properties.
         ///     </para>
         /// </remarks>
-        public override Expression<Func<ExportDefinition, bool>> Constraint
-        {
-            get
-            {
-                if (_constraint == null)
-                {
-                    _constraint = ConstraintServices.CreateConstraint(ContractName, RequiredTypeIdentity, RequiredMetadata, RequiredCreationPolicy);
-                }
-
-                return _constraint;
-            }
-        }
+        public override Expression<Func<ExportDefinition, bool>> Constraint =>
+            _constraint ??= ConstraintServices.CreateConstraint(ContractName, RequiredTypeIdentity, RequiredMetadata, RequiredCreationPolicy);
 
         /// <summary>
         ///     Executes an optimized version of the contraint given by the <see cref="Constraint"/> property
index 7a3be92..4b67121 100644 (file)
@@ -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);
         }
index 42c1e4c..c52e709 100644 (file)
@@ -88,10 +88,7 @@ namespace System.ComponentModel.Composition.ReflectionModel
                 Thread.MemoryBarrier();
                 lock (_lock)
                 {
-                    if (_constructor == null)
-                    {
-                        _constructor = result;
-                    }
+                    _constructor ??= result;
                 }
             }
 
index e42af67..a7f7910 100644 (file)
@@ -566,10 +566,7 @@ namespace System.ComponentModel.Composition.ReflectionModel
             }
 
             int exportIndex = reflectionExport.GetIndex();
-            if (_exportsCache == null)
-            {
-                _exportsCache = new Dictionary<int, ExportingMember>();
-            }
+            _exportsCache ??= new Dictionary<int, ExportingMember>();
             if (!_exportsCache.TryGetValue(exportIndex, out ExportingMember? result))
             {
                 result = GetExportingMember(definition);
index 9ae0913..3fba07e 100644 (file)
@@ -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<string, object?> metadata = _creationInfo.GetMetadata().AsReadOnly();
                     lock (_lock)
                     {
-                        if (_metadata == null)
-                        {
-                            _metadata = metadata;
-                        }
+                        _metadata ??= metadata;
                     }
                 }
                 return _metadata;
index f2b73d7..58adef9 100644 (file)
@@ -33,17 +33,7 @@ namespace System.ComponentModel.Composition.ReflectionModel
             get { return _member; }
         }
 
-        public override IDictionary<string, object?> Metadata
-        {
-            get
-            {
-                if (_metadata == null)
-                {
-                    _metadata = _exportDefinition.Metadata.AsReadOnly();
-                }
-                return _metadata;
-            }
-        }
+        public override IDictionary<string, object?> Metadata => _metadata ??= _exportDefinition.Metadata.AsReadOnly();
 
         string ICompositionElement.DisplayName
         {
index 56e8178..07d7d9e 100644 (file)
@@ -62,10 +62,7 @@ namespace System.ComponentModel
         {
             ArgumentNullException.ThrowIfNull(existing);
 
-            if (newAttributes == null)
-            {
-                newAttributes = Array.Empty<Attribute>();
-            }
+            newAttributes ??= Array.Empty<Attribute>();
 
             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<Type, Attribute?>();
-                }
+                s_defaultAttributes ??= new Dictionary<Type, Attribute?>();
 
                 // If we have already encountered this, use what's in the table.
                 if (s_defaultAttributes.TryGetValue(attributeType, out Attribute? defaultAttribute))
index 3f3fc35..337ebe5 100644 (file)
@@ -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);
index b423375..e9bd9ad 100644 (file)
@@ -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;
             }
         }
index 1a03f04..b35e0a1 100644 (file)
@@ -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
index 1a118c4..8e7835b 100644 (file)
@@ -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));
 
index b5eb861..9eeffb9 100644 (file)
@@ -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));
 
index 2b0b4fc..7ac65b5 100644 (file)
@@ -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));
index 62824c6..3188cf2 100644 (file)
@@ -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);
                 }
             }
 
index e42bf8e..e5e4b48 100644 (file)
@@ -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)
                 {
index 26f2d87..dd62aa6 100644 (file)
@@ -100,10 +100,7 @@ namespace System.ComponentModel.Design.Serialization
         {
             ArgumentNullException.ThrowIfNull(context);
 
-            if (_contextStack == null)
-            {
-                _contextStack = new List<object>();
-            }
+            _contextStack ??= new List<object>();
             _contextStack.Insert(0, context);
         }
 
@@ -132,10 +129,7 @@ namespace System.ComponentModel.Design.Serialization
         {
             ArgumentNullException.ThrowIfNull(context);
 
-            if (_contextStack == null)
-            {
-                _contextStack = new List<object>();
-            }
+            _contextStack ??= new List<object>();
             _contextStack.Add(context);
         }
     }
index 8f1d3ad..65c16f4 100644 (file)
@@ -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));
         }
 
index e5ce14b..573e97e 100644 (file)
@@ -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";
index ddc88ef..31ad7d2 100644 (file)
@@ -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,
index 54beae0..45b85f0 100644 (file)
@@ -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;
index 1de8d04..f82e2f2 100644 (file)
@@ -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
             {
index 17611ac..c6a6111 100644 (file)
@@ -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<object, EventHandler?>();
-            }
+            _valueChangedHandlers ??= new Dictionary<object, EventHandler?>();
 
             EventHandler? h = _valueChangedHandlers.GetValueOrDefault(component, defaultValue: null);
             _valueChangedHandlers[component] = (EventHandler?)Delegate.Combine(h, handler);
index 100beeb..9ce9f2a 100644 (file)
@@ -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)
                     {
index 05241af..310c8e3 100644 (file)
@@ -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)
                 {
index 00f8802..5f17e95 100644 (file)
@@ -578,10 +578,7 @@ namespace System.ComponentModel
             {
                 PropertyDescriptor[] propertyArray = ReflectGetExtendedProperties(extenders[idx]);
 
-                if (propertyList == null)
-                {
-                    propertyList = new List<PropertyDescriptor>(propertyArray.Length * extenders.Length);
-                }
+                propertyList ??= new List<PropertyDescriptor>(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.
index 050bb59..1cc9bf8 100644 (file)
@@ -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)
index b22befb..a91aac7 100644 (file)
@@ -426,10 +426,7 @@ namespace System.ComponentModel
             /// </summary>
             public StandardValuesCollection(ICollection? values)
             {
-                if (values == null)
-                {
-                    values = Array.Empty<object>();
-                }
+                values ??= Array.Empty<object>();
 
                 if (values is Array a)
                 {
index 4ac5a2f..9d965f4 100644 (file)
@@ -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;
index 1d8da04..35fc1c8 100644 (file)
@@ -79,11 +79,7 @@ namespace System.ComponentModel
                 {
                     if (o is WeakReference wr && !wr.IsAlive)
                     {
-                        if (cleanupList == null)
-                        {
-                            cleanupList = new List<object>();
-                        }
-
+                        cleanupList ??= new List<object>();
                         cleanupList.Add(wr);
                     }
                 }
index 9a6117b..1e9f3a8 100644 (file)
@@ -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));
index 0eee25d..c4f6f41 100644 (file)
@@ -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));
index 93d6ae1..da85f29 100644 (file)
@@ -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));
index 6bb0d10..a718bc8 100644 (file)
@@ -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));
index 3e3cdb3..c825178 100644 (file)
@@ -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));
index abd5238..3ff26ac 100644 (file)
@@ -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<Tuple<string, object>>();
-            }
+
+            _metadataItems ??= new List<Tuple<string, object>>();
             _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<Tuple<string, Func<Type, object>>>();
-            }
+            _metadataItemFuncs ??= new List<Tuple<string, Func<Type, object>>>();
             _metadataItemFuncs.Add(Tuple.Create(name, getValueFromPartType));
             return this;
         }
 
         internal void BuildAttributes(Type type, ref List<Attribute> attributes)
         {
-            if (attributes == null)
-            {
-                attributes = new List<Attribute>();
-            }
+            attributes ??= new List<Attribute>();
 
             var contractName = (_getContractNameFromPartType != null) ? _getContractNameFromPartType(type) : _contractName;
             attributes.Add(new ExportAttribute(contractName, _contractType));
index 804d9e5..3b9143b 100644 (file)
@@ -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<Tuple<string, object>>();
-            }
+
+            _metadataConstraintItems ??= new List<Tuple<string, object>>();
             _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<Tuple<string, Func<Type, object>>>();
-            }
+            _metadataConstraintItemFuncs ??= new List<Tuple<string, Func<Type, object>>>();
             _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<Attribute>();
-            }
-            attributes.Add(importAttribute);
 
+            attributes ??= new List<Attribute>();
+            attributes.Add(importAttribute);
 
             //Add metadata attributes from direct specification
             if (_metadataConstraintItems != null)
index cd30e94..6cadec4 100644 (file)
@@ -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<Tuple<string, object>>();
-            }
+            _metadataItems ??= new List<Tuple<string, object>>();
             _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<Tuple<string, Func<Type, object>>>();
-            }
+            _metadataItemFuncs ??= new List<Tuple<string, Func<Type, object>>>();
             _metadataItemFuncs.Add(Tuple.Create(name, getValueFromPartType));
             return this;
         }
@@ -651,10 +645,7 @@ namespace System.Composition.Convention
 
         private static void ConfigureConstructorAttributes(ConstructorInfo constructorInfo, ref List<Tuple<object, List<Attribute>>> configuredMembers, Action<ParameterInfo, ImportConventionBuilder> configureConstuctorImports)
         {
-            if (configuredMembers == null)
-            {
-                configuredMembers = new List<Tuple<object, List<Attribute>>>();
-            }
+            configuredMembers ??= new List<Tuple<object, List<Attribute>>>();
 
             // 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<Predicate<PropertyInfo>, Action<PropertyInfo, ImportConventionBuilder>> 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<Predicate<PropertyInfo>, Action<PropertyInfo, ExportConventionBuilder>, 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<Tuple<object, List<Attribute>>>();
-                        }
+                        configuredMembers ??= new List<Tuple<object, List<Attribute>>>();
 
                         configuredMembers.Add(Tuple.Create((object)pi, attributes));
                     }
index b60eb8a..73d2c5b 100644 (file)
@@ -187,10 +187,7 @@ namespace System.Composition.Convention
                             {
                                 var lambdaExpression = (LambdaExpression)parameter;
                                 Delegate importDelegate = lambdaExpression.Compile();
-                                if (_importBuilders == null)
-                                {
-                                    _importBuilders = new Dictionary<ParameterInfo, Action<ImportConventionBuilder>>();
-                                }
+                                _importBuilders ??= new Dictionary<ParameterInfo, Action<ImportConventionBuilder>>();
                                 _importBuilders.Add(parameterInfos[index], (Action<ImportConventionBuilder>)importDelegate);
                                 ++index;
                             }
index c1fc011..5e446b3 100644 (file)
@@ -59,8 +59,7 @@ namespace System.Composition.Hosting.Core
                 throw new ArgumentNullException(nameof(action));
             }
 
-            if (_nonPrerequisiteActions == null)
-                _nonPrerequisiteActions = new List<Action>();
+            _nonPrerequisiteActions ??= new List<Action>();
 
             _nonPrerequisiteActions.Add(action);
         }
@@ -77,8 +76,7 @@ namespace System.Composition.Hosting.Core
                 throw new ArgumentNullException(nameof(action));
             }
 
-            if (_postCompositionActions == null)
-                _postCompositionActions = new List<Action>();
+            _postCompositionActions ??= new List<Action>();
 
             _postCompositionActions.Add(action);
         }
index bd026a9..86d266d 100644 (file)
@@ -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);
         }
index 48e8d77..6fc4def 100644 (file)
@@ -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)
                 {
index 25af4ba..9840347 100644 (file)
@@ -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++)
                 {
index 71f04c1..2874181 100644 (file)
@@ -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<string, List<SectionInput>>(1);
+                                        indirectLocationInputs ??= new Dictionary<string, List<SectionInput>>(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<SectionRecord>();
+                            removes ??= new List<SectionRecord>();
 
                             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];
index a2a818b..7f6edad 100644 (file)
@@ -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))
index 13e4456..06a7887 100644 (file)
@@ -236,17 +236,8 @@ namespace System.Configuration
                 }
             }
 
-            internal static IInternalConfigConfigurationFactory ConfigFactory
-            {
-                get
-                {
-                    if (s_configFactory == null)
-                    {
-                        s_configFactory = TypeUtil.CreateInstance<IInternalConfigConfigurationFactory>(InternalConfigConfigurationFactoryTypeName);
-                    }
-                    return s_configFactory;
-                }
-            }
+            internal static IInternalConfigConfigurationFactory ConfigFactory =>
+                s_configFactory ??= TypeUtil.CreateInstance<IInternalConfigConfigurationFactory>(InternalConfigConfigurationFactoryTypeName);
 
             private ClientSettingsConfigurationHost() { }
 
index c1a2aad..53bdfed 100644 (file)
@@ -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<Type, ConfigurationValidatorBase>();
+            s_perTypeValidators ??= new Dictionary<Type, ConfigurationValidatorBase>();
 
             // 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)
                 {
index b6b1cf4..7301fc5 100644 (file)
@@ -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();
     }
 }
index b2ff1b7..a20e964 100644 (file)
@@ -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")
                 {
index 2ca9406..3d90f19 100644 (file)
@@ -23,7 +23,7 @@ namespace System.Configuration
             Debug.Assert(e != null, "e != null");
 
             // Create on demand
-            if (errors == null) errors = new List<ConfigurationException>();
+            errors ??= new List<ConfigurationException>();
 
             ConfigurationErrorsException ce = e as ConfigurationErrorsException;
             if (ce == null) errors.Add(e);
index 09081d9..828a359 100644 (file)
@@ -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();
 
         /// <summary>
         /// 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)
index 36c30ce..bb84b6f 100644 (file)
@@ -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);
                     }
                 }
index 74b7449..74b4520 100644 (file)
@@ -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;
index 2042139..76aeaa6 100644 (file)
@@ -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
         {
index 91a6ce2..aaeb706 100644 (file)
@@ -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<T>(string typeString)
index f8e7be8..3cdd1ab 100644 (file)
@@ -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);
         }
index 2e083fc..5b09f60 100644 (file)
@@ -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.
index f7e2810..e20465b 100644 (file)
@@ -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);
index 0ac9b5a..8f4d31c 100644 (file)
@@ -524,11 +524,7 @@ namespace System
             /// <returns>The formatted string.</returns>
             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
             /// <returns>The formatted string.</returns>
             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;
index 4f2a9ce..e148813 100644 (file)
@@ -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)
         {
index f960762..c82f3d3 100644 (file)
@@ -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)
                 {
index 089db87..1e2021a 100644 (file)
@@ -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("<ds.DataColumn.set_ColumnName|API> {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("<ds.DataColumn.set_Prefix|API> {0}, '{1}'", ObjectID, value);
 
@@ -733,10 +721,7 @@ namespace System.Data
             {
                 long logScopeId = DataCommonEventSource.Log.EnterScope("<ds.DataColumn.set_Expression|API> {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)
         {
index 3ef950a..2657da2 100644 (file)
@@ -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;
index 71170c5..d903c18 100644 (file)
@@ -359,10 +359,7 @@ namespace System.Data
                 long logScopeId = DataCommonEventSource.Log.EnterScope("<ds.DataRelation.set_RelationName|API> {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)
index 34679c6..c80fe12 100644 (file)
@@ -732,7 +732,7 @@ namespace System.Data
             long logScopeId = DataCommonEventSource.Log.EnterScope("<ds.DataRow.SetColumnError|API> {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);
         }
 
index fc153a2..b38833e 100644 (file)
@@ -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("<ds.DataSet.set_Namespace|API> {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)
                         {
index 7d601dc..a5cc7cb 100644 (file)
@@ -1767,10 +1767,7 @@ namespace System.Data
                 long logScopeId = DataCommonEventSource.Log.EnterScope("<ds.DataTable.set_TableName|API> {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("<ds.DataTable.set_Prefix|API> {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<DataTable>();
-                t_usedTables.Add(table);
+                (t_usedTables ??= new List<DataTable>()).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<DataTable>();
+                RowDiffIdUsageSection.t_usedTables ??= new List<DataTable>();
 #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<DataColumn>();
-            }
+            _dependentColumns ??= new List<DataColumn>();
 
             if (!_dependentColumns.Contains(expressionColumn))
             {
index 58d56a3..b37c297 100644 (file)
@@ -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;
index 6a94981..6f165eb 100644 (file)
@@ -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);
index 0e91087..0648759 100644 (file)
@@ -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)
                 {
index b47462c..9d2b2df 100644 (file)
@@ -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
index 9045b9a..0930071 100644 (file)
@@ -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);
             }
index 7719da0..ad9e74a 100644 (file)
@@ -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);
             }
index 5e9e2f5..ee53672 100644 (file)
@@ -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();
+                }
             }
         }
 
index 00fc6c2..fb4d729 100644 (file)
@@ -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<Func<Stream, XmlReaderSettings, XmlParserContext?, XmlReader>>();
         }
 
-        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
index 29c9c4d..2de32d6 100644 (file)
@@ -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;
index 9fbc276..2f94d51 100644 (file)
@@ -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()
index 568779d..c66e8f5 100644 (file)
@@ -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;
index f79179d..5bd3410 100644 (file)
@@ -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
                 {
index 1e97a9c..176a116 100644 (file)
@@ -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();
         }
index ec050d4..0b62490 100644 (file)
@@ -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
             //
index 69329e3..cf23b50 100644 (file)
@@ -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;
             }
         }
index d5e4a5c..ef5bc0b 100644 (file)
@@ -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
index 369bd2a..c7a9569 100644 (file)
@@ -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();
index b14b18c..03cf948 100644 (file)
@@ -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;
index 4c0296e..425457a 100644 (file)
@@ -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
index a8d700d..0b9102c 100644 (file)
@@ -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.
                 }
index 4b3c0f1..165b313 100644 (file)
@@ -117,10 +117,8 @@ namespace System.Diagnostics.Metrics
         /// <param name="measurementCallback">The callback which can be used to get measurement recording of numeric type T.</param>
         public void SetMeasurementEventCallback<T>(MeasurementCallback<T>? 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<byte>)(object)measurementCallback;
index 71c686e..dfb8c50 100644 (file)
@@ -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]
index e24ce1f..272d5d7 100644 (file)
@@ -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)
index 894437a..1c58e48 100644 (file)
@@ -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;
index 41ccebb..37f50c2 100644 (file)
@@ -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);
                 }
             }
         }
index 31bfdf8..8d97e21 100644 (file)
@@ -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();
 
index e43b7af..6be68d1 100644 (file)
@@ -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<EventLevel>)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevels);
+            _standardLevels ??= (List<EventLevel>)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<EventOpcode>)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodes);
+            _standardOpcodes ??= (List<EventOpcode>)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<EventKeyword>)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywords);
+            _standardKeywords ??= (List<EventKeyword>)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<EventTask>)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTasks);
+            _standardTasks ??= (List<EventTask>)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTasks);
             foreach (EventTask standardTask in _standardTasks)
             {
                 if (standardTask.Name == name && standardTask.Value == value)
index fc13490..09a07e0 100644 (file)
@@ -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;
             }
index d92a6bb..9b4f2c6 100644 (file)
@@ -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;
             }
index 220156f..927f9d1 100644 (file)
@@ -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))
index 15b5220..9f828f5 100644 (file)
@@ -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))
index a8ab0cf..4113c31 100644 (file)
@@ -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()
         {
index a7b4804..d807deb 100644 (file)
@@ -652,10 +652,7 @@ namespace System.Diagnostics
                             }
                             else
                             {
-                                if (additionalToRemove == null)
-                                {
-                                    additionalToRemove = new List<ProcessWaitState>();
-                                }
+                                additionalToRemove ??= new List<ProcessWaitState>();
                                 additionalToRemove.Add(pws);
                             }
                         }
index 4af317f..665b858 100644 (file)
@@ -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)
             {
index d8b98d8..1b50f00 100644 (file)
@@ -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
index cdc431d..43dd994 100644 (file)
@@ -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
         {
index e00b1f9..0ebc7fe 100644 (file)
@@ -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
         {
index 52e43b1..87944a1 100644 (file)
@@ -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();
 
         /// <devdoc>
         /// <para> Gets or sets a name for this <see cref='System.Diagnostics.TraceListener'/>.</para>
index 8747480..d8d2a39 100644 (file)
@@ -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();
             }
         }
 
index 087b1a5..fb9e6b1 100644 (file)
@@ -37,8 +37,7 @@ namespace System.DirectoryServices.AccountManagement
             LoadFilterMappingTable(mappingIndex, s_filterPropertiesTableRaw);
             LoadPropertyMappingTable(mappingIndex, s_propertyMappingTableRaw);
 
-            if (NonPresentAttrDefaultStateMapping == null)
-                NonPresentAttrDefaultStateMapping = new Dictionary<string, bool>();
+            NonPresentAttrDefaultStateMapping ??= new Dictionary<string, bool>();
 
             for (int i = 0; i < s_presenceStateTable.GetLength(0); i++)
             {
index 5932bf2..0ed20ee 100644 (file)
@@ -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);
                 }
index 5a274e3..f9d1fa7 100644 (file)
@@ -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;
 
index 828be6a..3155d39 100644 (file)
@@ -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);
                     }
index b4be630..acaf5a6 100644 (file)
@@ -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);
 
index 5355ec6..b02f4f6 100644 (file)
@@ -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);
                     }
index 33de32c..c5c0aa6 100644 (file)
@@ -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")]
index 8ff1ecc..650f9c4 100644 (file)
@@ -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<object>();
+            value ??= Array.Empty<object>();
 
             Debug.WriteLine("Begin encoding\n");
 
index 0165343..c6dd1c6 100644 (file)
@@ -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();
             }
         }
 
index 2f4a873..e46383f 100644 (file)
@@ -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);
index 7022619..3533048 100644 (file)
@@ -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
index fb6efff..07626c6 100644 (file)
@@ -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;
index a1a139d..c947713 100644 (file)
@@ -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
index 689fda3..47675bc 100644 (file)
@@ -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);
             }
         }
 
index 89c1c6b..7817e52 100644 (file)
@@ -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);
index b208550..1e9b45c 100644 (file)
@@ -196,11 +196,7 @@ namespace System.DirectoryServices.ActiveDirectory
             get
             {
                 CheckIfDisposed();
-                if (cachedPartitions == null)
-                {
-                    cachedPartitions = new ReadOnlyStringCollection(GetPartitions());
-                }
-                return cachedPartitions;
+                return cachedPartitions ??= new ReadOnlyStringCollection(GetPartitions());
             }
         }
 
index e828ec3..db1b624 100644 (file)
@@ -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);
             }
         }
 
index 6591bd0..2a5be2a 100644 (file)
@@ -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);
index 94df08c..19547e4 100644 (file)
@@ -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);
             }
         }
 
index 9918903..01c3958 100644 (file)
@@ -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]
         {
index ee3e353..5ab69ec 100644 (file)
@@ -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)
         {
index 01ce522..71d53ef 100644 (file)
@@ -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);
                 }
             }
 
index 7815049..d554e62 100644 (file)
@@ -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
         /// <devdoc>
         /// Gets a <see cref='System.DirectoryServices.PropertyCollection'/> of properties set on this object.
         /// </devdoc>
-        public PropertyCollection Properties
-        {
-            get
-            {
-                if (_propertyCollection == null)
-                {
-                    _propertyCollection = new PropertyCollection(this);
-                }
-
-                return _propertyCollection;
-            }
-        }
+        public PropertyCollection Properties =>
+            _propertyCollection ??= new PropertyCollection(this);
 
         /// <devdoc>
         /// Gets the name of the schema used for this <see cref='System.DirectoryServices.DirectoryEntry'/>
@@ -446,10 +435,7 @@ namespace System.DirectoryServices
                     _passwordIsNull = true;
                 }
 
-                if (value == null)
-                    _userNameIsNull = true;
-                else
-                    _userNameIsNull = false;
+                _userNameIsNull = value == null;
 
                 _credentials.UserName = value;
 
index 7548578..846fffa 100644 (file)
@@ -233,17 +233,8 @@ namespace System.DirectoryServices
         /// </devdoc>
         [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();
 
         /// <devdoc>
         /// 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)
index 63f1230..4711b60 100644 (file)
@@ -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
 
         /// <devdoc>
         /// 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();
                 }
             }
 
index 33433e2..d3de084 100644 (file)
@@ -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;
index 350eb93..1e2125a 100644 (file)
@@ -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);
index c146909..129c9bf 100644 (file)
@@ -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);
         }
index 48e0f1c..e0b8933 100644 (file)
@@ -250,10 +250,7 @@ namespace System.Drawing
                 {
                     // Construct the image array
                     //
-                    if (s_imageInfoList == null)
-                    {
-                        s_imageInfoList = new List<ImageInfo>();
-                    }
+                    s_imageInfoList ??= new List<ImageInfo>();
 
                     // Add the new image
                     //
index 150ba75..c8a16f1 100644 (file)
@@ -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}");
index 8cde405..04d64fe 100644 (file)
@@ -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];
index 42266a7..6d5bc85 100644 (file)
@@ -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];
index c94f82a..0c043e5 100644 (file)
@@ -255,13 +255,8 @@ namespace System.Drawing.Printing
         /// </summary>
         public PrinterSettings PrinterSettings
         {
-            get { return printerSettings; }
-            set
-            {
-                if (value == null)
-                    value = new PrinterSettings();
-                printerSettings = value;
-            }
+            get => printerSettings;
+            set => printerSettings = value ?? new PrinterSettings();
         }
 
         /// <summary>
index eaa7307..c315870 100644 (file)
@@ -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;
         }
 
         /// <summary>
@@ -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)
index a4de17e..933589d 100644 (file)
@@ -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();
index 3ae2152..ea8f3e5 100644 (file)
@@ -39,10 +39,7 @@ namespace System.Drawing.Printing
             }
             set
             {
-                if (value == null)
-                {
-                    value = new PageSettings();
-                }
+                value ??= new PageSettings();
                 _pageSettings = value;
                 PageSettingsChanged = true;
             }
index f1db851..1924f42 100644 (file)
@@ -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];
index 004d29a..2b91a3b 100644 (file)
@@ -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;
index 93f74c7..868531c 100644 (file)
@@ -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);
         }
     }
 }
index c250081..60476b1 100644 (file)
@@ -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)
                 {
index c43553f..52a3dc3 100644 (file)
@@ -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);
         }
     }
 }
index be2a5c7..0f086e9 100644 (file)
@@ -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)
index b64f7c4..35290aa 100644 (file)
@@ -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;
index d8a4dea..a9169ae 100644 (file)
@@ -18,18 +18,15 @@ namespace System.Drawing.Internal
         /// </summary>
         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);
             }
         }
 
index e36dd61..f1914c6 100644 (file)
@@ -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))
                         {
index db7bbee..19dc0e1 100644 (file)
@@ -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))
                         {
index 34343ad..d7052b7 100644 (file)
@@ -449,10 +449,7 @@ namespace System.Formats.Asn1
 
         private Scope PushTag(Asn1Tag tag, UniversalTagNumber tagType)
         {
-            if (_nestingStack == null)
-            {
-                _nestingStack = new Stack<StackFrame>();
-            }
+            _nestingStack ??= new Stack<StackFrame>();
 
             Debug.Assert(tag.IsConstructed);
             WriteTag(tag);
index c5f3773..cca0747 100644 (file)
@@ -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);
index f191c40..5841cb6 100644 (file)
@@ -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
index 3d1c537..ec906ee 100644 (file)
@@ -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
index 55cdbf0..7ce1382 100644 (file)
@@ -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<Stream>(); //Default capacity is 4
+            _requestedStreams ??= new List<Stream>(); //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
index db69f44..1695a4f 100644 (file)
@@ -817,8 +817,7 @@ namespace System.IO.Packaging
         /// </param>
         private void AddSubsumingNamespace(string namespaceName)
         {
-            if (_subsumingNamespaces == null)
-                _subsumingNamespaces = new Dictionary<string, object?>();
+            _subsumingNamespaces ??= new Dictionary<string, object?>();
             _subsumingNamespaces[namespaceName] = null;
         }
 
@@ -844,8 +843,7 @@ namespace System.IO.Packaging
         /// </param>
         private void AddKnownNamespace(string namespaceName)
         {
-            if (_knownNamespaces == null)
-                _knownNamespaces = new Dictionary<string, object?>();
+            _knownNamespaces ??= new Dictionary<string, object?>();
             _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<string, object?>();
-                    }
-
+                    _names ??= new Dictionary<string, object?>();
                     _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<string, string>();
-                    }
-
+                    _names ??= new Dictionary<string, string>();
                     _names.Add(itemName, itemName);
                 }
             }
index 3fb085f..b14ac61 100644 (file)
@@ -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<PackUriHelper.ValidatedPartUri, ContentType>(OverrideDictionaryInitialSize);
+                _overrideDictionary ??= new Dictionary<PackUriHelper.ValidatedPartUri, ContentType>(OverrideDictionaryInitialSize);
             }
 
             private void ParseContentTypesFile(System.Collections.ObjectModel.ReadOnlyCollection<ZipArchiveEntry> zipFiles)
index 47c9d06..76ac8b1 100644 (file)
@@ -50,11 +50,7 @@ namespace System.IO.Pipelines
             }
             catch (Exception ex)
             {
-                if (exceptions == null)
-                {
-                    exceptions = new List<Exception>();
-                }
-
+                exceptions ??= new List<Exception>();
                 exceptions.Add(ex);
             }
         }
index fad6054..3ec9cdd 100644 (file)
@@ -77,11 +77,7 @@ namespace System.IO.Pipelines
             {
                 lock (_lock)
                 {
-                    if (_internalTokenSource == null)
-                    {
-                        _internalTokenSource = new CancellationTokenSource();
-                    }
-                    return _internalTokenSource;
+                    return _internalTokenSource ??= new CancellationTokenSource();
                 }
             }
         }
index a836334..ce83c11 100644 (file)
@@ -38,11 +38,7 @@ namespace System.IO.Pipelines
             {
                 lock (_lockObject)
                 {
-                    if (_internalTokenSource == null)
-                    {
-                        _internalTokenSource = new CancellationTokenSource();
-                    }
-                    return _internalTokenSource;
+                    return _internalTokenSource ??= new CancellationTokenSource();
                 }
             }
         }
index 7e7d64c..f924518 100644 (file)
@@ -463,8 +463,7 @@ namespace System.Dynamic
 
                     if (variable.IsByRef)
                     {
-                        if (block == null)
-                            block = new ReadOnlyCollectionBuilder<Expression>();
+                        block ??= new ReadOnlyCollectionBuilder<Expression>();
 
                         block.Add(
                             Expression.Assign(
index 8451677..ac7cf78 100644 (file)
@@ -89,10 +89,7 @@ namespace System.Dynamic
         /// </summary>
         private List<WeakReference> GetTransitionList(int hashCode)
         {
-            if (_transitions == null)
-            {
-                _transitions = new Dictionary<int, List<WeakReference>>();
-            }
+            _transitions ??= new Dictionary<int, List<WeakReference>>();
 
             if (!_transitions.TryGetValue(hashCode, out List<WeakReference>? infos))
             {
index 8884a27..7735664 100644 (file)
@@ -67,10 +67,7 @@ namespace System.Linq.Expressions.Compiler
         {
             Type lookingUp = initialArg;
             TypeInfo nextTypeInfo;
-            if (curTypeInfo.TypeChain == null)
-            {
-                curTypeInfo.TypeChain = new Dictionary<Type, TypeInfo>();
-            }
+            curTypeInfo.TypeChain ??= new Dictionary<Type, TypeInfo>();
 
             if (!curTypeInfo.TypeChain.TryGetValue(lookingUp, out nextTypeInfo))
             {
index 427db15..4ac9a12 100644 (file)
@@ -381,10 +381,7 @@ namespace System.Linq.Expressions.Compiler
         {
             Debug.Assert(CanJumpInto);
 
-            if (_labels == null)
-            {
-                _labels = new Dictionary<LabelTarget, LabelInfo>();
-            }
+            _labels ??= new Dictionary<LabelTarget, LabelInfo>();
 
             _labels.Add(target, info);
         }
index 7281856..c141e54 100644 (file)
@@ -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)
             {
index 073071a..bf7bfd8 100644 (file)
@@ -529,10 +529,7 @@ namespace System.Linq.Expressions.Compiler
                     WriteBack? wb = EmitAddressWriteBack(argument, type);
                     if (wb != null)
                     {
-                        if (writeBacks == null)
-                        {
-                            writeBacks = new List<WriteBack>();
-                        }
+                        writeBacks ??= new List<WriteBack>();
 
                         writeBacks.Add(wb);
                     }
index f01cff0..730bbb3 100644 (file)
@@ -714,9 +714,7 @@ namespace System.Linq.Expressions.Compiler
             // if (switchValue == null) {
             //     switchIndex = nullCase;
             // } else {
-            //     if (_dictField == null) {
-            //         _dictField = new Dictionary<string, int>(count) { { ... }, ... };
-            //     }
+            //     _dictField ??= new Dictionary<string, int>(count) { { ... }, ... };
             //     if (!_dictField.TryGetValue(switchValue, out switchIndex)) {
             //         switchIndex = -1;
             //     }
index d8d978d..fcfda01 100644 (file)
@@ -350,10 +350,7 @@ namespace System.Linq.Expressions.Compiler
             /// </param>
             private void MarkRef(int index)
             {
-                if (_byRefs == null)
-                {
-                    _byRefs = new bool[_expressions.Length];
-                }
+                _byRefs ??= new bool[_expressions.Length];
 
                 _byRefs[index] = true;
             }
index d19ba67..ecae9cb 100644 (file)
@@ -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<ParameterExpression>();
-                }
+                _usedTemps ??= new Stack<ParameterExpression>();
 
                 _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<ParameterExpression>();
-                }
+                _freeTemps ??= new List<ParameterExpression>();
 
                 _freeTemps.Add(temp);
             }
index 86d2013..010ce55 100644 (file)
@@ -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)
index 47ae039..1791672 100644 (file)
@@ -178,10 +178,7 @@ namespace System.Linq.Expressions.Compiler
                     }
 
                     // Otherwise, merge it
-                    if (currentScope.MergedScopes == null)
-                    {
-                        currentScope.MergedScopes = new HashSet<BlockExpression>(ReferenceEqualityComparer.Instance);
-                    }
+                    currentScope.MergedScopes ??= new HashSet<BlockExpression>(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<ParameterExpression, int>();
-            }
+            referenceScope.ReferenceCount ??= new Dictionary<ParameterExpression, int>();
 
             Helpers.IncrementCount(node, referenceScope.ReferenceCount);
             return node;
index 7019a6d..02d5101 100644 (file)
@@ -399,10 +399,7 @@ namespace System.Linq.Expressions
         {
             Out($".Lambda {GetLambdaName(node)}<{node.Type}>");
 
-            if (_lambdas == null)
-            {
-                _lambdas = new Queue<LambdaExpression>();
-            }
+            _lambdas ??= new Queue<LambdaExpression>();
 
             // N^2 performance, for keeping the order of the lambdas.
             if (!_lambdas.Contains(node))
index 6bc6d13..526dcba 100644 (file)
@@ -35,10 +35,7 @@ namespace System.Linq.Expressions
 
         private int GetId(object o)
         {
-            if (_ids == null)
-            {
-                _ids = new Dictionary<object, int>();
-            }
+            _ids ??= new Dictionary<object, int>();
 
             int id;
             if (!_ids.TryGetValue(o, out id))
index 585d590..cdc11b8 100644 (file)
@@ -72,10 +72,7 @@ namespace System.Linq.Expressions.Interpreter
 
             if (_targetIndex == UnknownIndex)
             {
-                if (_forwardBranchFixups == null)
-                {
-                    _forwardBranchFixups = new List<int>();
-                }
+                _forwardBranchFixups ??= new List<int>();
                 _forwardBranchFixups.Add(branchIndex);
             }
             else
index 194af7b..2f4d6e4 100644 (file)
@@ -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);
         }
index 4e9725a..1b0e18c 100644 (file)
@@ -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<object>();
-                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<BranchLabel>();
-            }
+            _labels ??= new List<BranchLabel>();
 
             var label = new BranchLabel();
             _labels.Add(label);
index 18a2e3c..f95008a 100644 (file)
@@ -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<InterpretedFrameInfo>(GetStackTraceDebugInfo()).ToArray();
-            }
+            exception.Data[typeof(InterpretedFrameInfo)] ??= new List<InterpretedFrameInfo>(GetStackTraceDebugInfo()).ToArray();
         }
 
         public static InterpretedFrameInfo[]? GetExceptionStackTrace(Exception exception)
index 3fbc68e..fbc67fd 100644 (file)
@@ -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<LabelTarget, LabelInfo>();
-            }
+            _labels ??= new HybridReferenceDictionary<LabelTarget, LabelInfo>();
 
             _labels[target] = info;
         }
index a560068..068f933 100644 (file)
@@ -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<ByRefUpdater>();
-                        }
+                        updaters ??= new List<ByRefUpdater>();
 
                         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<ByRefUpdater>();
-                            }
+                            updaters ??= new List<ByRefUpdater>();
                             updaters.Add(updater);
                         }
                     }
index f42254d..8e64650 100644 (file)
@@ -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<VariableScope>();
-                }
+                existing.ChildScopes ??= new List<VariableScope>();
                 existing.ChildScopes.Add(newScope);
             }
             else
index 0743941..aa4128d 100644 (file)
@@ -613,11 +613,8 @@ namespace System.Linq.Expressions
             // method and call that will be used for creating instances of this
             // delegate type
             Func<Expression, string?, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>? fastPath;
-            CacheDict<Type, Func<Expression, string?, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>>? factories = s_lambdaFactories;
-            if (factories == null)
-            {
-                s_lambdaFactories = factories = new CacheDict<Type, Func<Expression, string?, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>>(50);
-            }
+            CacheDict<Type, Func<Expression, string?, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>>? factories =
+                s_lambdaFactories ??= new CacheDict<Type, Func<Expression, string?, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>>(50);
 
             if (!factories.TryGetValue(delegateType, out fastPath))
             {
index 25291ad..731c1e4 100644 (file)
@@ -1142,10 +1142,7 @@ namespace System.Linq.Expressions
         {
             ArgumentNullException.ThrowIfNull(instance);
             ArgumentNullException.ThrowIfNull(methodName);
-            if (arguments == null)
-            {
-                arguments = Array.Empty<Expression>();
-            }
+            arguments ??= Array.Empty<Expression>();
 
             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<Expression>();
-            BindingFlags flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy;
-            return Expression.Call(null, FindMethod(type, methodName, typeArguments, arguments, flags)!, arguments);
+            arguments ??= Array.Empty<Expression>();
+            const BindingFlags Flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy;
+            return Expression.Call(null, FindMethod(type, methodName, typeArguments, arguments, Flags)!, arguments);
         }
 
         /// <summary>Creates a <see cref="MethodCallExpression"/> that represents a method call.</summary>
index 110b6bb..968b272 100644 (file)
@@ -41,17 +41,7 @@ namespace System.Runtime.CompilerServices
         {
             private static LambdaSignature<T>? s_instance;
 
-            internal static LambdaSignature<T> Instance
-            {
-                get
-                {
-                    if (s_instance == null)
-                    {
-                        s_instance = new LambdaSignature<T>();
-                    }
-                    return s_instance;
-                }
-            }
+            internal static LambdaSignature<T> Instance => s_instance ??= new LambdaSignature<T>();
 
             internal readonly ReadOnlyCollection<ParameterExpression> Parameters;
             internal readonly LabelTarget ReturnLabel;
index 5e5413d..e33d959 100644 (file)
@@ -96,8 +96,7 @@ namespace System.Linq.Parallel
 
             internal override bool MoveNext(ref int currentElement, ref int currentKey)
             {
-                if (_currentCount == null)
-                    _currentCount = new Shared<int>(-1);
+                _currentCount ??= new Shared<int>(-1);
 
                 // Calculate the next index and ensure it falls within our range.
                 int nextCount = _currentCount.Value + 1;
index c56de6c..2e80fd0 100644 (file)
@@ -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<int>(-1);
+                _currentIndex ??= new Shared<int>(-1);
 
                 if (_currentIndex.Value < (_count - 1))
                 {
index 5a9ecf5..bce7107 100644 (file)
@@ -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.
index 477f0f1..e1e749e 100644 (file)
@@ -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.
index be2778b..cf86f5d 100644 (file)
@@ -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<int>(_startIndex);
-                }
+                _currentIndex ??= new Shared<int>(_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<int>(_startIndex);
-                }
+                _currentIndex ??= new Shared<int>(_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);
 
index a9136f0..eefc462 100644 (file)
@@ -325,12 +325,7 @@ namespace System.Linq.Parallel
 
                 _leftOrdered = leftOrdered;
                 _rightOrdered = rightOrdered;
-                _comparer = comparer;
-
-                if (_comparer == null)
-                {
-                    _comparer = EqualityComparer<TInputOutput>.Default;
-                }
+                _comparer = comparer ?? EqualityComparer<TInputOutput>.Default;
 
                 _cancellationToken = cancellationToken;
             }
index 9d0e5c1..7770866 100644 (file)
@@ -134,11 +134,7 @@ namespace System.Linq.Parallel
 
             QueryResults<TOutput> queryResults = GetQueryResults(querySettings);
 
-            if (mergeOptions == null)
-            {
-                mergeOptions = querySettings.MergeOptions;
-            }
-
+            mergeOptions ??= querySettings.MergeOptions;
             Debug.Assert(mergeOptions != null);
 
             // Top-level preemptive cancellation test.
index d8fa01b..93bcda2 100644 (file)
@@ -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;
index eb7464f..3a723a4 100644 (file)
@@ -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<TInput>.Default;
-            }
-            else
-            {
-                _comparer = comparer;
-            }
+            _comparer = comparer ?? EqualityComparer<TInput>.Default;
         }
 
         //---------------------------------------------------------------------------------------
index 27afe76..5ebbefa 100644 (file)
@@ -150,8 +150,7 @@ namespace System.Linq.Parallel
                 TKey keyUnused = default!;
                 Pair<TInputOutput, NoKeyMemoizationRequired> current = default(Pair<TInputOutput, NoKeyMemoizationRequired>);
 
-                if (_outputLoopCount == null)
-                    _outputLoopCount = new Shared<int>(0);
+                _outputLoopCount ??= new Shared<int>(0);
 
                 while (_source.MoveNext(ref current, ref keyUnused))
                 {
index 251e58e..5455982 100644 (file)
@@ -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<int>(0);
+                _outputLoopCount ??= new Shared<int>(0);
 
                 while (_source.MoveNext(ref currentElement!, ref currentKey))
                 {
index 7fb10e1..a1fe751 100644 (file)
@@ -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<TSortKey>();
-            }
-            else
-            {
-                _comparer = comparer;
-            }
-
+            _comparer = comparer ?? Util.GetDefaultComparer<TSortKey>();
             if (descending)
             {
                 _comparer = new ReverseComparer<TSortKey>(_comparer);
index b189b57..158795c 100644 (file)
@@ -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<int>(0);
+                _outputLoopCount ??= new Shared<int>(0);
 
                 while (_source.MoveNext(ref currentElement!, ref currentKey))
                 {
index f2f8f51..4bfc75c 100644 (file)
@@ -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<TKey>();
-                }
+                keys ??= new GrowingArray<TKey>();
 
                 if (hadNext)
                 {
index d3455ae..6ed1a19 100644 (file)
@@ -21,17 +21,8 @@ namespace System.Linq.Parallel
     {
         private readonly IEqualityComparer<T> _comparer;
 
-        internal WrapperEqualityComparer(IEqualityComparer<T>? comparer)
-        {
-            if (comparer == null)
-            {
-                _comparer = EqualityComparer<T>.Default;
-            }
-            else
-            {
-                _comparer = comparer;
-            }
-        }
+        internal WrapperEqualityComparer(IEqualityComparer<T>? comparer) =>
+            _comparer = comparer ?? EqualityComparer<T>.Default;
 
         public bool Equals(Wrapper<T> x, Wrapper<T> y)
         {
index faf127b..9a0e36f 100644 (file)
@@ -463,9 +463,14 @@ namespace System.Linq
         {
             LabelTarget? newTarget;
             if (_targetCache == null)
+            {
                 _targetCache = new Dictionary<LabelTarget, LabelTarget>();
+            }
             else if (_targetCache.TryGetValue(node!, out newTarget))
+            {
                 return newTarget;
+            }
+
             Type type = node!.Type;
             if (!typeof(IQueryable).IsAssignableFrom(type))
                 newTarget = base.VisitLabelTarget(node);
index 53997ce..bc5db3b 100644 (file)
@@ -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);
             }
         }
 
index 9161fd9..24f280e 100644 (file)
@@ -383,10 +383,7 @@ namespace System.Management
             {
                 Initialize(true);
 
-                if (methods == null)
-                    methods = new MethodDataCollection(this);
-
-                return methods;
+                return methods ??= new MethodDataCollection(this);
             }
         }
 
index ca70e41..26bc04d 100644 (file)
@@ -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();
         }
 
         /// <summary>
index 49c6a54..bb730db 100644 (file)
@@ -166,10 +166,7 @@ namespace System.Management
         {
             get
             {
-                if (context == null)
-                    return context = new ManagementNamedValueCollection();
-                else
-                    return context;
+                return context ??= new ManagementNamedValueCollection();
             }
             set
             {
index 633b306..2710b76 100644 (file)
@@ -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.
index 1024c87..720b15e 100644 (file)
@@ -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
             {
index 267ed84..d90ed8b 100644 (file)
@@ -240,15 +240,7 @@ namespace System.Management
         ///    qualifiers for this method.
         /// </value>
         /// <seealso cref='System.Management.QualifierData'/>
-        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
 }
index 62acc0e..07969d4 100644 (file)
@@ -250,16 +250,8 @@ namespace System.Management
         /// <para>A <see cref='System.Management.QualifierDataCollection'/> that represents
         ///    the set of qualifiers defined on the property.</para>
         /// </value>
-        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
index 9406209..63e80d4 100644 (file)
@@ -5775,10 +5775,7 @@ namespace System.Management
         /// </summary>
         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)
             {
index 4fa86dc..91ba3aa 100644 (file)
@@ -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<string, object> Properties
-        {
-            get
-            {
-                if (_properties == null)
-                {
-                    _properties = new Dictionary<string, object>();
-                }
-
-                return _properties;
-            }
-        }
+        public IDictionary<string, object> Properties => _properties ??= new Dictionary<string, object>();
         #endregion
 
         protected override void Dispose(bool disposing)
index fdba34a..0ced574 100644 (file)
@@ -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))
             {
index 8e508e8..0e2244c 100644 (file)
@@ -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
         {
index 9e5e1f5..ce03900 100644 (file)
@@ -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)
index d1de2d9..4cc2568 100644 (file)
@@ -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)
index dc796d8..b9f743a 100644 (file)
@@ -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;
index c5c29f1..8bfce77 100644 (file)
@@ -855,10 +855,7 @@ namespace System.Net.Http
             {
                 lock (SyncObj)
                 {
-                    if (_http3ConnectionCreateLock == null)
-                    {
-                        _http3ConnectionCreateLock = new SemaphoreSlim(1);
-                    }
+                    _http3ConnectionCreateLock ??= new SemaphoreSlim(1);
                 }
             }
 
index f466dbe..cddca3c 100644 (file)
@@ -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.
index 272235c..b5370b1 100644 (file)
@@ -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.
index a1e213c..8139792 100644 (file)
@@ -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<HttpListenerWebSocketContext> AcceptWebSocketAsync(string? subProtocol)
         {
index b44dc6d..473ae22 100644 (file)
@@ -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()
index b8aa859..bb52043 100644 (file)
@@ -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
             {
index bab09a5..96a85b9 100644 (file)
@@ -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++)
index 728e784..506a980 100644 (file)
@@ -52,10 +52,7 @@ namespace System.Net
 
         private void EnsureResponseStream()
         {
-            if (_responseStream == null)
-            {
-                _responseStream = _httpContext!.Connection.GetResponseStream();
-            }
+            _responseStream ??= _httpContext!.Connection.GetResponseStream();
         }
 
         public Version ProtocolVersion
index d0c5b1c..53be0f5 100644 (file)
@@ -88,8 +88,7 @@ namespace System.Net
             {
                 lock (_locker)
                 {
-                    if (_handle == null)
-                        _handle = new ManualResetEvent(_completed);
+                    _handle ??= new ManualResetEvent(_completed);
                 }
 
                 return _handle;
index 91cdec0..4e7d5b4 100644 (file)
@@ -220,8 +220,7 @@ namespace System.Net
 
                 lock (_locker)
                 {
-                    if (_handle == null)
-                        _handle = new ManualResetEvent(_completed);
+                    _handle ??= new ManualResetEvent(_completed);
                 }
 
                 return _handle;
index 39e1f42..013db59 100644 (file)
@@ -14,17 +14,7 @@ namespace System.Net
         private readonly List<string> _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()
         {
index 6c47d53..7a530aa 100644 (file)
@@ -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);
                 }
             }
index 2176ccd..8807cdc 100644 (file)
@@ -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;
index f4767d9..78b72b2 100644 (file)
@@ -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)
index 38ee04e..e39b53f 100644 (file)
@@ -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);
                 }
             }
         }
index 6ceea22..81a7c54 100644 (file)
@@ -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));
index 25ec53c..c7ffda1 100644 (file)
@@ -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)
             {
index fc44d01..a13e89b 100644 (file)
@@ -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<LineInfo>();
             }
 
-            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);
 
index 005f996..50f1d36 100644 (file)
@@ -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;
             }
index 59e630c..543e4db 100644 (file)
@@ -40,17 +40,7 @@ namespace System.Net.Mime
             ContentType.Boundary = GetNextBoundary();
         }
 
-        internal Collection<MimeBasePart> Parts
-        {
-            get
-            {
-                if (_parts == null)
-                {
-                    _parts = new Collection<MimeBasePart>();
-                }
-                return _parts;
-            }
-        }
+        internal Collection<MimeBasePart> Parts => _parts ??= new Collection<MimeBasePart>();
 
         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);
index cf00bba..6b78fd2 100644 (file)
@@ -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);
index e4ede0e..95da9b7 100644 (file)
@@ -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<string, object>();
-                    }
+                    _internalObjects ??= new Dictionary<string, object>();
 
                     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<string, object>();
-            }
+            _internalObjects ??= new Dictionary<string, object>();
 
             // always replace the existing value when we set internally
             _internalObjects[key] = value;
index 20ffcaa..bbce06d 100644 (file)
@@ -64,10 +64,7 @@ namespace System.Net.NetworkInformation
 
             internal void AddException(Exception e)
             {
-                if (_exceptions == null)
-                {
-                    _exceptions = new List<Exception>();
-                }
+                _exceptions ??= new List<Exception>();
                 _exceptions.Add(e);
             }
         }
index 7a9be6b..9884d09 100644 (file)
@@ -62,10 +62,7 @@ namespace System.Net.NetworkInformation
 
             internal void AddException(Exception e)
             {
-                if (_exceptions == null)
-                {
-                    _exceptions = new List<Exception>();
-                }
+                _exceptions ??= new List<Exception>();
                 _exceptions.Add(e);
             }
         }
index 73a38d9..f34c696 100644 (file)
@@ -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
index 86187da..829785b 100644 (file)
@@ -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<string>();
-                            }
-
                             // These candidates can only match CookieVariant.Plain cookies.
+                            domainAttributeMatchOnlyCookieVariantPlain ??= new System.Collections.Generic.List<string>();
                             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);
                         }
                     }
index 5369513..1065905 100644 (file)
@@ -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<CredentialKey, NetworkCredential>();
-            }
-
+            _cache ??= new Dictionary<CredentialKey, NetworkCredential>();
             _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<CredentialHostKey, NetworkCredential>();
-            }
-
+            _cacheForHosts ??= new Dictionary<CredentialHostKey, NetworkCredential>();
             _cacheForHosts.Add(key, credential);
         }
 
index a43c462..d1fefb0 100644 (file)
@@ -362,17 +362,10 @@ namespace System.Net
         ///     or standard IPv6 representation.
         ///   </para>
         /// </devdoc>
-        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<char> destination, out int charsWritten)
         {
index 5b21bd4..2394024 100644 (file)
@@ -64,10 +64,7 @@ namespace System.Net
             }
             set
             {
-                if (_credentials == null)
-                {
-                    _credentials = new WeakReference(null);
-                }
+                _credentials ??= new WeakReference(null);
                 _credentials.Target = value;
             }
         }
index 8bb7b99..79b050d 100644 (file)
@@ -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);
 
         /// <summary>
         ///    <para>Returns true if we should restart the request after an error</para>
@@ -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
index 0c1b2de..a19f168 100644 (file)
@@ -101,10 +101,7 @@ namespace System.Net
                 {
                     lock (this)
                     {
-                        if (_ftpRequestHeaders == null)
-                        {
-                            _ftpRequestHeaders = new WebHeaderCollection();
-                        }
+                        _ftpRequestHeaders ??= new WebHeaderCollection();
                     }
                 }
                 return _ftpRequestHeaders;
index 684c481..c5875e6 100644 (file)
@@ -76,10 +76,7 @@ namespace System.Net
                     catch { };
                 }
 
-                if (localId == null)
-                {
-                    localId = IdOf(innerStream);
-                }
+                localId ??= IdOf(innerStream);
 
                 SslStreamCtor(IdOf(sslStream), localId, remoteId);
             }
index 3b01821..3845144 100644 (file)
@@ -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();
         }
index bc7b968..f815a86 100644 (file)
@@ -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;
 
index 3baab06..ba41243 100644 (file)
@@ -493,10 +493,7 @@ namespace System.Net.Sockets
             PinSocketAddressBuffer();
 
             // Create a WSAMessageBuffer if none exists yet.
-            if (_wsaMessageBufferPinned == null)
-            {
-                _wsaMessageBufferPinned = GC.AllocateUninitializedArray<byte>(sizeof(Interop.Winsock.WSAMsg), pinned: true);
-            }
+            _wsaMessageBufferPinned ??= GC.AllocateUninitializedArray<byte>(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<WSABuffer>(1, pinned: true);
-                }
+                _wsaRecvMsgWSABufferArrayPinned ??= GC.AllocateUninitializedArray<WSABuffer>(1, pinned: true);
 
                 fixed (byte* bufferPtr = &MemoryMarshal.GetReference(_buffer.Span))
                 {
index d4a5013..83b10b0 100644 (file)
@@ -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();
index 24584ac..a73a0be 100644 (file)
@@ -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)
index 9956316..ef803b8 100644 (file)
@@ -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
         {
index 199bf2d..f17834f 100644 (file)
@@ -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<byte> namespaceBytes = new byte[] // rely on C# compiler optimization to remove byte[] allocation
             {
index 19bf2e0..9c30fdd 100644 (file)
@@ -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.
index 6fdbe7b..051eef8 100644 (file)
@@ -97,10 +97,7 @@ namespace System.Diagnostics.Tracing
                 this.name = eventAttrib.Name;
             }
 
-            if (this.name == null)
-            {
-                this.name = dataType.Name;
-            }
+            this.name ??= dataType.Name;
         }
     }
 }
index 8f9a555..e5c85f5 100644 (file)
@@ -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;
             }
index 6a3851b..af44c2d 100644 (file)
@@ -137,10 +137,7 @@ namespace System.Globalization
                 return c;
             }
 
-            if (casingTable == null)
-            {
-                casingTable = InitOrdinalCasingPage(pageNumber);
-            }
+            casingTable ??= InitOrdinalCasingPage(pageNumber);
 
             return (char) casingTable[((int)c) & 0xFF];
         }
index 9edb161..547601d 100644 (file)
@@ -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
index 5c25031..aabdf3c 100644 (file)
@@ -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;
index 430088b..7262476 100644 (file)
@@ -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));
                             }
                         }
index 30f447a..f183eae 100644 (file)
@@ -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
index c9ecc55..7336251 100644 (file)
@@ -331,8 +331,7 @@ namespace System.IO
                             }
                             catch (Exception e)
                             {
-                                if (exception == null)
-                                    exception = e;
+                                exception ??= e;
                             }
                         }
                         else
index 2b88da7..b0d39ed 100644 (file)
@@ -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)
             {
index d3c4ded..0c0c6e1 100644 (file)
@@ -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)
             {
index eba845f..97584ac 100644 (file)
@@ -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
index 131a019..a8ba471 100644 (file)
@@ -110,10 +110,7 @@ namespace System.IO
             get => CoreNewLineStr;
             set
             {
-                if (value == null)
-                {
-                    value = Environment.NewLineConst;
-                }
+                value ??= Environment.NewLineConst;
 
                 CoreNewLineStr = value;
                 CoreNewLine = value.ToCharArray();
index 257b0e1..56806be 100644 (file)
@@ -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;
             }
index 5c492e7..ad22a86 100644 (file)
@@ -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;
index 3b8f462..398bc70 100644 (file)
@@ -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);
index c5932c9..b9c1813 100644 (file)
@@ -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;
index a3277c5..4d9a68f 100644 (file)
@@ -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<ExceptionDispatchInfo>? exceptions = m_faultExceptions;
-            if (exceptions == null) m_faultExceptions = exceptions = new List<ExceptionDispatchInfo>(1);
-            else Debug.Assert(exceptions.Count > 0, "Expected existing exceptions list to have > 0 exceptions.");
+            List<ExceptionDispatchInfo>? exceptions = m_faultExceptions ??= new List<ExceptionDispatchInfo>(1);
 
             // Handle Exception by capturing it into an ExceptionDispatchInfo and storing that
             if (exceptionObject is Exception exception)
index 373f7ab..1177300 100644 (file)
@@ -59,11 +59,7 @@ namespace System.Threading
             {
                 if (!_isScheduled)
                 {
-                    List<TimerQueue>? timers = s_scheduledTimers;
-                    if (timers == null)
-                    {
-                        timers = InitializeScheduledTimerManager_Locked();
-                    }
+                    List<TimerQueue> timers = s_scheduledTimers ?? InitializeScheduledTimerManager_Locked();
 
                     timers.Add(this);
                     _isScheduled = true;
index beb3040..1200e4e 100644 (file)
@@ -204,18 +204,7 @@ namespace System.Runtime.Serialization
         }
 
         private Func<object>? _makeNewInstance;
-        private Func<object> MakeNewInstance
-        {
-            get
-            {
-                if (_makeNewInstance == null)
-                {
-                    _makeNewInstance = FastInvokerBuilder.GetMakeNewInstanceFunc(UnderlyingType);
-                }
-
-                return _makeNewInstance;
-            }
-        }
+        private Func<object> 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
             {
index 0879bcd..b39d1af 100644 (file)
@@ -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]);
index 41f0548..f566308 100644 (file)
@@ -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<T>()
             {
                 return (xmlwriter, obj, context) =>
                 {
                     context.IncrementCollectionCountGeneric<T>(xmlwriter, (ICollection<T>)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<K, V>()
             {
@@ -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);
                 }
             }
index b2d2ab2..402b990 100644 (file)
@@ -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<Type, DataContract?>();
+                    s_typeToBuiltInContract ??= new Dictionary<Type, DataContract?>();
 
                     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<XmlQualifiedName, DataContract?>();
+                    s_nameToBuiltInContract ??= new Dictionary<XmlQualifiedName, DataContract?>();
 
                     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<XmlQualifiedName, DataContract?>();
+                    s_nameToBuiltInContract ??= new Dictionary<XmlQualifiedName, DataContract?>();
 
                     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, string>();
-                    string? value;
-                    if (s_namespaces.TryGetValue(key, out value))
+                    s_namespaces ??= new Dictionary<string, string>();
+                    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);
                     }
index 4109703..c42b485 100644 (file)
@@ -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)
             {
index 51588fc..41bae41 100644 (file)
@@ -54,39 +54,14 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private Dictionary<XmlQualifiedName, DataContract> Contracts
-        {
-            get
-            {
-                if (_contracts == null)
-                {
-                    _contracts = new Dictionary<XmlQualifiedName, DataContract>();
-                }
-                return _contracts;
-            }
-        }
+        private Dictionary<XmlQualifiedName, DataContract> Contracts =>
+            _contracts ??= new Dictionary<XmlQualifiedName, DataContract>();
+
+        private Dictionary<DataContract, object> ProcessedContracts =>
+            _processedContracts ??= new Dictionary<DataContract, object>();
 
-        private Dictionary<DataContract, object> ProcessedContracts
-        {
-            get
-            {
-                if (_processedContracts == null)
-                {
-                    _processedContracts = new Dictionary<DataContract, object>();
-                }
-                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)]
index 5d2ccfa..251e896 100644 (file)
@@ -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
         {
index c1c60b5..435415d 100644 (file)
@@ -23,16 +23,6 @@ namespace System.Runtime.Serialization
         }
 #endif
 
-        public Collection<Type> KnownTypes
-        {
-            get
-            {
-                if (_knownTypes == null)
-                {
-                    _knownTypes = new Collection<Type>();
-                }
-                return _knownTypes;
-            }
-        }
+        public Collection<Type> KnownTypes => _knownTypes ??= new Collection<Type>();
     }
 }
index 0fe6ffb..df8b296 100644 (file)
@@ -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];
index 2e5368d..1ce12d3 100644 (file)
@@ -19,8 +19,7 @@ namespace System.Runtime.Serialization
 
         internal void Add(string id, object? obj)
         {
-            if (_objectDictionary == null)
-                _objectDictionary = new Dictionary<string, object?>();
+            _objectDictionary ??= new Dictionary<string, object?>();
 
             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<string, object?>();
-                _referencedObjectDictionary.Add(id, null);
-            }
-            else
-            {
-                _referencedObjectDictionary.TryAdd(id, null);
-            }
+            _referencedObjectDictionary ??= new Dictionary<string, object?>();
+            _referencedObjectDictionary.TryAdd(id, null);
 
             if (_objectDictionary != null)
             {
index 6403867..beeb3fa 100644 (file)
@@ -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,
index 472413f..4330703 100644 (file)
@@ -283,10 +283,7 @@ namespace System.Runtime.Serialization.Json
                         while (collectionDataContract != null)
                         {
                             DataContract itemContract = collectionDataContract.ItemContract;
-                            if (_knownDataContracts == null)
-                            {
-                                _knownDataContracts = new Dictionary<XmlQualifiedName, DataContract>();
-                            }
+                            _knownDataContracts ??= new Dictionary<XmlQualifiedName, DataContract>();
 
                             _knownDataContracts.TryAdd(itemContract.StableName, itemContract);
 
index f6a0516..74e85bc 100644 (file)
@@ -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))]
index bc47d9e..0df641f 100644 (file)
@@ -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
index d8b391b..afe02b0 100644 (file)
@@ -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;
index e36a4fe..b9a545d 100644 (file)
@@ -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)
         {
index a65a474..74fbefe 100644 (file)
@@ -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))
index b7edc56..fc508ff 100644 (file)
@@ -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)
index 2852f76..7b54448 100644 (file)
@@ -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)))
index fe7ad57..9c61887 100644 (file)
@@ -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)
index 7945a64..c6993ad 100644 (file)
@@ -33,8 +33,7 @@ namespace System.Runtime.Serialization
             }
             else
             {
-                if (_objectDictionary == null)
-                    _objectDictionary = new Dictionary<object, object?>();
+                _objectDictionary ??= new Dictionary<object, object?>();
 
                 _objectDictionary.Add(obj, null);
                 _count++;
index b5bfbbb..8cd388f 100644 (file)
@@ -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)
index dcffdbc..b28f417 100644 (file)
@@ -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)
index 6350fc0..dc70a9c 100644 (file)
@@ -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))
index 8b6a976..1c76e57 100644 (file)
@@ -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.
index 8a07b0e..da820ba 100644 (file)
@@ -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)
index 47fed53..727fc4e 100644 (file)
@@ -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<DataContractDictionary>(ref dataContractDictionaries, dataContractDictionaries.Length * 2);
+            }
+
             dataContractDictionaries[_count++] = dataContractDictionary;
         }
 
index dce6f2a..02b82aa 100644 (file)
@@ -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)
index a6371c4..6791ee9 100644 (file)
@@ -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;
index 165e0ab..b510882 100644 (file)
@@ -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;
index a5f70d7..8ba00fd 100644 (file)
@@ -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();
     }
 }
index fd87805..66ce7c6 100644 (file)
@@ -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)
index dc9f5c0..09fb6e2 100644 (file)
@@ -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<ExtensionDataMember>();
+            extensionData.Members ??= new List<ExtensionDataMember>();
             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<ExtensionDataMember>();
+                dataNode.Members ??= new List<ExtensionDataMember>();
                 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<IDataNode?>();
+                    dataNode.Items ??= new List<IDataNode?>();
                     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<ISerializableDataMember>();
+                dataNode.Members ??= new List<ISerializableDataMember>();
                 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<XmlAttribute>();
+                        xmlAttributes ??= new List<XmlAttribute>();
                         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<XmlNode>();
+                xmlChildNodes ??= new List<XmlNode>();
                 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)!;
index 4e7ebc9..00abd38 100644 (file)
@@ -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);
         }
 
index 29036c7..0d9437d 100644 (file)
@@ -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))]
index d09c801..4bc3d07 100644 (file)
@@ -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;
index 0790825..38e29e8 100644 (file)
@@ -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);
index d37fb67..f009bcc 100644 (file)
@@ -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);
index 5f8a487..2ecc252 100644 (file)
@@ -32,8 +32,7 @@ namespace System.Xml
             xmlString = new XmlDictionaryString(this, value, id);
             if (id >= MaxArrayEntries)
             {
-                if (_stringDict == null)
-                    _stringDict = new Dictionary<int, XmlDictionaryString>();
+                _stringDict ??= new Dictionary<int, XmlDictionaryString>();
 
                 _stringDict.Add(id, xmlString);
             }
index 7ed8b8e..ef401fd 100644 (file)
@@ -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)
                     {
index cfdaacd..aa52a87 100644 (file)
@@ -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;
index b72baab..fab4fb8 100644 (file)
@@ -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)
index 7af5afb..7ebc16d 100644 (file)
@@ -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)
index f58260c..e50ec38 100644 (file)
@@ -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)
         {
index 869d2bc..e07bd76 100644 (file)
@@ -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()
         {
index 2eb1a86..92b5bb6 100644 (file)
@@ -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);
index 97b285f..b98dfdc 100644 (file)
@@ -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()
index 091df90..b39afc2 100644 (file)
@@ -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);
         }
 
index 88fb622..3cd4abc 100644 (file)
@@ -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()
index a01ee61..7fb89ae 100644 (file)
@@ -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)
             {
index 0ee99f4..30a6fb5 100644 (file)
@@ -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;
 
index 5728503..2a1314d 100644 (file)
@@ -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)
         {
index 2304b40..6c93827 100644 (file)
@@ -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)
             {
index fba947f..05a3f5d 100644 (file)
@@ -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;
index d656e8f..cec8795 100644 (file)
@@ -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;
index 5e64253..88efc58 100644 (file)
@@ -78,26 +78,12 @@ namespace System.Xml.Linq
         /// <summary>
         /// Gets a comparer that can compare the relative position of two nodes.
         /// </summary>
-        public static XNodeDocumentOrderComparer DocumentOrderComparer
-        {
-            get
-            {
-                if (s_documentOrderComparer == null) s_documentOrderComparer = new XNodeDocumentOrderComparer();
-                return s_documentOrderComparer;
-            }
-        }
+        public static XNodeDocumentOrderComparer DocumentOrderComparer => s_documentOrderComparer ??= new XNodeDocumentOrderComparer();
 
         /// <summary>
         /// Gets a comparer that can compare two nodes for value equality.
         /// </summary>
-        public static XNodeEqualityComparer EqualityComparer
-        {
-            get
-            {
-                if (s_equalityComparer == null) s_equalityComparer = new XNodeEqualityComparer();
-                return s_equalityComparer;
-            }
-        }
+        public static XNodeEqualityComparer EqualityComparer => s_equalityComparer ??= new XNodeEqualityComparer();
 
         /// <overloads>
         /// Adds the specified content immediately after this node. The
index 1826064..812c1d5 100644 (file)
@@ -208,10 +208,7 @@ namespace System.Xml.Linq
 
         private void Add(object o)
         {
-            if (_content == null)
-            {
-                _content = new List<object>();
-            }
+            _content ??= new List<object>();
             _content.Add(o);
         }
 
index 4540cee..930dd70 100644 (file)
@@ -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)
index 372c606..5c98957 100644 (file)
@@ -153,10 +153,7 @@ namespace System.Xml.Schema
 
         private void ReplaceSchemaInfo(XObject o, XmlSchemaInfo schemaInfo)
         {
-            if (schemaInfos == null)
-            {
-                schemaInfos = new Dictionary<XmlSchemaInfo, XmlSchemaInfo>(new XmlSchemaInfoEqualityComparer());
-            }
+            schemaInfos ??= new Dictionary<XmlSchemaInfo, XmlSchemaInfo>(new XmlSchemaInfoEqualityComparer());
             XmlSchemaInfo? si = o.Annotation<XmlSchemaInfo>();
             if (si != null)
             {
index 881ddb9..ea7d1f2 100644 (file)
@@ -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)
index 829b2e3..a6444ad 100644 (file)
@@ -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;
index 2900713..720b5d4 100644 (file)
@@ -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];
index 0b4a3d2..3eb3a87 100644 (file)
@@ -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];
index fddf94c..6bba053 100644 (file)
@@ -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)
index 5482a32..913257a 100644 (file)
@@ -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.
index c8ec2d3..388852f 100644 (file)
@@ -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));
                 }
             }
         }
index d097357..493eee1 100644 (file)
@@ -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);
                     }
                 }
index e30d1c8..fd11ea2 100644 (file)
@@ -451,10 +451,7 @@ namespace System.Xml
         {
             base.RawText("<META http-equiv=\"Content-Type\"");
 
-            if (_mediaType == null)
-            {
-                _mediaType = "text/html";
-            }
+            _mediaType ??= "text/html";
 
             base.RawText(" content=\"");
             base.RawText(_mediaType);
index 5bf76a9..dcaf52c 100644 (file)
@@ -428,10 +428,7 @@ namespace System.Xml
         {
             base.RawText("<META http-equiv=\"Content-Type\"");
 
-            if (_mediaType == null)
-            {
-                _mediaType = "text/html";
-            }
+            _mediaType ??= "text/html";
 
             base.RawText(" content=\"");
             base.RawText(_mediaType);
index 64b0a22..015403e 100644 (file)
@@ -224,10 +224,7 @@ namespace System.Xml
 
         public override void WriteWhitespace(string? ws)
         {
-            if (ws == null)
-            {
-                ws = string.Empty;
-            }
+            ws ??= string.Empty;
 
             // "checkNames" is intentional here; if false, the whitespace is checked in XmlWellformedWriter
             if (_checkNames)
@@ -406,10 +403,7 @@ namespace System.Xml
                     {
                         continue;
                     }
-                    if (sb == null)
-                    {
-                        sb = new StringBuilder(str.Length + 5);
-                    }
+                    sb ??= new StringBuilder(str.Length + 5);
                     sb.Append(str, start, i - start);
                 }
                 else if (ch == '\r')
@@ -422,11 +416,7 @@ namespace System.Xml
                             continue;
                         }
 
-                        if (sb == null)
-                        {
-                            sb = new StringBuilder(str.Length + 5);
-                        }
-
+                        sb ??= new StringBuilder(str.Length + 5);
                         sb.Append(str, start, i - start);
                         i++;
                     }
index 20fa431..8975998 100644 (file)
@@ -171,10 +171,7 @@ namespace System.Xml
 
         public override Task WriteWhitespaceAsync(string? ws)
         {
-            if (ws == null)
-            {
-                ws = string.Empty;
-            }
+            ws ??= string.Empty;
 
             // "checkNames" is intentional here; if false, the whitespace is checked in XmlWellformedWriter
             if (_checkNames)
index 6fae9da..63c07ae 100644 (file)
@@ -86,10 +86,7 @@ namespace System.Xml
         // By default, convert base64 value to string and call WriteString.
         public override void WriteBase64(byte[] buffer, int index, int count)
         {
-            if (_base64Encoder == null)
-            {
-                _base64Encoder = new XmlRawWriterBase64Encoder(this);
-            }
+            _base64Encoder ??= new XmlRawWriterBase64Encoder(this);
 
             // Encode will call WriteRaw to write out the encoded characters
             _base64Encoder.Encode(buffer, index, count);
index 5cd1605..ee72198 100644 (file)
@@ -79,10 +79,8 @@ namespace System.Xml
         // By default, convert base64 value to string and call WriteString.
         public override Task WriteBase64Async(byte[] buffer, int index, int count)
         {
-            if (_base64Encoder == null)
-            {
-                _base64Encoder = new XmlRawWriterBase64Encoder(this);
-            }
+            _base64Encoder ??= new XmlRawWriterBase64Encoder(this);
+
             // Encode will call WriteRaw to write out the encoded characters
             return _base64Encoder.EncodeAsync(buffer, index, count);
         }
index 3ed4021..b3b025e 100644 (file)
@@ -1484,11 +1484,7 @@ namespace System.Xml
                         }
                         else
                         {
-                            if (sb == null)
-                            {
-                                sb = new StringBuilder();
-                                sb.Append(value);
-                            }
+                            sb ??= new StringBuilder().Append(value);
                             sb.Append(Value);
                         }
                         break;
index 594220d..7339f7f 100644 (file)
@@ -339,11 +339,7 @@ namespace System.Xml
                         }
                         else
                         {
-                            if (sb == null)
-                            {
-                                sb = new StringBuilder();
-                                sb.Append(value);
-                            }
+                            sb ??= new StringBuilder().Append(value);
                             sb.Append(await GetValueAsync().ConfigureAwait(false));
                         }
                         break;
index aebe458..f399f2c 100644 (file)
@@ -1300,10 +1300,7 @@ namespace System.Xml
             _nsManager.AddNamespace(prefix, ns);
 
             int index = _nsAttrCount++;
-            if (_nsAttributes == null)
-            {
-                _nsAttributes = new NodeData[InitialNamespaceAttributeCount];
-            }
+            _nsAttributes ??= new NodeData[InitialNamespaceAttributeCount];
 
             if (index == _nsAttributes.Length)
             {
index 8150e7a..3927f99 100644 (file)
@@ -528,10 +528,7 @@ namespace System.Xml
         internal XmlTextReaderImpl(string xmlFragment, XmlNodeType fragType, XmlParserContext? context)
             : this(null == context || null == context.NameTable ? new NameTable() : context.NameTable)
         {
-            if (xmlFragment == null)
-            {
-                xmlFragment = string.Empty;
-            }
+            xmlFragment ??= string.Empty;
 
             if (context == null)
             {
@@ -2265,10 +2262,7 @@ namespace System.Xml
             {
                 if (_incReadDecoder != _readCharsDecoder)
                 { // mixing ReadChars with ReadBase64 or ReadBinHex
-                    if (_readCharsDecoder == null)
-                    {
-                        _readCharsDecoder = new IncrementalReadCharsDecoder();
-                    }
+                    _readCharsDecoder ??= new IncrementalReadCharsDecoder();
                     _readCharsDecoder.Reset();
                     _incReadDecoder = _readCharsDecoder;
                 }
@@ -2286,10 +2280,7 @@ namespace System.Xml
                     return 0;
                 }
 
-                if (_readCharsDecoder == null)
-                {
-                    _readCharsDecoder = new IncrementalReadCharsDecoder();
-                }
+                _readCharsDecoder ??= new IncrementalReadCharsDecoder();
 
                 InitIncrementalRead(_readCharsDecoder);
                 return IncrementalRead(buffer, index, count);
@@ -2323,10 +2314,7 @@ namespace System.Xml
                     return 0;
                 }
 
-                if (_base64Decoder == null)
-                {
-                    _base64Decoder = new Base64Decoder();
-                }
+                _base64Decoder ??= new Base64Decoder();
 
                 InitIncrementalRead(_base64Decoder);
                 return IncrementalRead(array, offset, len);
@@ -2360,10 +2348,7 @@ namespace System.Xml
                     return 0;
                 }
 
-                if (_binHexDecoder == null)
-                {
-                    _binHexDecoder = new BinHexDecoder();
-                }
+                _binHexDecoder ??= new BinHexDecoder();
 
                 InitIncrementalRead(_binHexDecoder);
                 return IncrementalRead(array, offset, len);
@@ -2962,11 +2947,7 @@ namespace System.Xml
             }
 
             // detect & setup encoding
-            if (encoding == null)
-            {
-                encoding = DetectEncoding();
-            }
-
+            encoding ??= DetectEncoding();
             SetupEncoding(encoding);
 
             // eat preamble
@@ -7734,12 +7715,7 @@ namespace System.Xml
             }
             Debug.Assert(nodeIndex < _nodes.Length);
 
-            NodeData node = _nodes[nodeIndex];
-            if (node == null)
-            {
-                node = new NodeData();
-                _nodes[nodeIndex] = node;
-            }
+            NodeData node = _nodes[nodeIndex] ??= new NodeData();
             node.depth = nodeDepth;
             return node;
         }
@@ -9142,10 +9118,7 @@ namespace System.Xml
             _nameTable = nt;
 
             // make sure we have namespace manager
-            if (_namespaceManager == null)
-            {
-                _namespaceManager = new XmlNamespaceManager(nt);
-            }
+            _namespaceManager ??= new XmlNamespaceManager(nt);
 
             // copy xml:space and xml:lang
             _xmlContext.xmlSpace = context.XmlSpace;
@@ -9609,10 +9582,7 @@ namespace System.Xml
                 return uri1Str == uri2Str;
             }
 
-            if (uri1 == null)
-            {
-                uri1 = resolver.ResolveUri(null, uri1Str);
-            }
+            uri1 ??= resolver.ResolveUri(null, uri1Str);
 
             Uri uri2 = resolver.ResolveUri(null, uri2Str);
             return uri1.Equals(uri2);
index 971c5e4..3467963 100644 (file)
@@ -965,10 +965,7 @@ namespace System.Xml
             }
 
             // detect & setup encoding
-            if (encoding == null)
-            {
-                encoding = DetectEncoding();
-            }
+            encoding ??= DetectEncoding();
             SetupEncoding(encoding);
 
             // eat preamble
index 0e4e73c..18dd3a6 100644 (file)
@@ -666,10 +666,7 @@ namespace System.Xml
                             }
                             else
                             {
-                                if (prefix == null)
-                                {
-                                    prefix = GeneratePrefix(); // need a prefix if
-                                }
+                                prefix ??= GeneratePrefix(); // need a prefix if
                                 PushNamespace(prefix, ns, false);
                             }
                         }
index c2cd387..9017c36 100644 (file)
@@ -1082,9 +1082,7 @@ namespace System.Xml
             if (tempResolver == null && !_coreReaderImpl.IsResolverSet)
             {
                 // it is safe to return valid resolver as it'll be used in the schema validation
-                if (s_tempResolver == null)
-                    s_tempResolver = new XmlUrlResolver();
-                return s_tempResolver;
+                return s_tempResolver ??= new XmlUrlResolver();
             }
 
             return tempResolver;
index e498e69..6bd337b 100644 (file)
@@ -443,18 +443,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);
@@ -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);
             }
index 1129fad..3770909 100644 (file)
@@ -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);
index 2d3660b..0e026f8 100644 (file)
@@ -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;
index c43f4b1..5176203 100644 (file)
@@ -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)
index e8277ad..3359f31 100644 (file)
@@ -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.");
     }
 }
index d1ffd7a..e7e2210 100644 (file)
@@ -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
         {
index 069d4d5..28296c0 100644 (file)
@@ -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);
 
index ae6a6c3..0f42ece 100644 (file)
@@ -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<XmlElement>(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
index 4d468eb..fffb34a 100644 (file)
@@ -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
index 15193b4..44a32c3 100644 (file)
@@ -242,10 +242,7 @@ namespace System.Xml
                 {
                     lock (OwnerDocument.objLock)
                     {
-                        if (_attributes == null)
-                        {
-                            _attributes = new XmlAttributeCollection(this);
-                        }
+                        _attributes ??= new XmlAttributeCollection(this);
                     }
                 }
 
index 83fdf7c..c251362 100644 (file)
@@ -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;
index 4d9ee0d..be0897f 100644 (file)
@@ -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
index c5386af..46faa53 100644 (file)
@@ -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);
 
index 3e311a6..e3ec143 100644 (file)
@@ -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;
index e63a9e0..10fa6f1 100644 (file)
@@ -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
         {
index c730929..4a2f2ea 100644 (file)
@@ -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
index cb155a7..7ff823d 100644 (file)
@@ -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);
         }
index 551e977..b490e2b 100644 (file)
@@ -1358,10 +1358,7 @@ namespace System.Xml
 
         private void AddUndeclaredNotation(string notationName)
         {
-            if (_undeclaredNotations == null)
-            {
-                _undeclaredNotations = new Dictionary<string, UndeclaredNotation>();
-            }
+            _undeclaredNotations ??= new Dictionary<string, UndeclaredNotation>();
             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;
index 4c0964a..fefc1fd 100644 (file)
@@ -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)
                 {
index cd109ff..8e0219f 100644 (file)
@@ -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);
                 }
 
index c5a5a88..3f0d065 100644 (file)
@@ -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;
index 88b9949..fd6222a 100644 (file)
@@ -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<Uri, XmlSchema> 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)
index 345b81e..436da7c 100644 (file)
@@ -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;
             }
index c46f062..2b6eae8 100644 (file)
@@ -97,10 +97,7 @@ namespace System.Xml.Schema
 
         internal void AddValue(string value)
         {
-            if (values == null)
-            {
-                values = new List<string>();
-            }
+            values ??= new List<string>();
             values.Add(value);
         }
 
index 0e7d7b4..72b3645 100644 (file)
@@ -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<IDtdDefaultAttributeInfo>();
-                }
+                _defaultAttdefs ??= new List<IDtdDefaultAttributeInfo>();
                 _defaultAttdefs.Add(attdef);
             }
         }
index f85e435..7fc94ac 100644 (file)
@@ -70,29 +70,11 @@ namespace System.Xml.Schema
             get { return _undeclaredElementDecls; }
         }
 
-        internal Dictionary<XmlQualifiedName, SchemaEntity> GeneralEntities
-        {
-            get
-            {
-                if (_generalEntities == null)
-                {
-                    _generalEntities = new Dictionary<XmlQualifiedName, SchemaEntity>();
-                }
-                return _generalEntities;
-            }
-        }
+        internal Dictionary<XmlQualifiedName, SchemaEntity> GeneralEntities =>
+            _generalEntities ??= new Dictionary<XmlQualifiedName, SchemaEntity>();
 
-        internal Dictionary<XmlQualifiedName, SchemaEntity> ParameterEntities
-        {
-            get
-            {
-                if (_parameterEntities == null)
-                {
-                    _parameterEntities = new Dictionary<XmlQualifiedName, SchemaEntity>();
-                }
-                return _parameterEntities;
-            }
-        }
+        internal Dictionary<XmlQualifiedName, SchemaEntity> ParameterEntities =>
+            _parameterEntities ??= new Dictionary<XmlQualifiedName, SchemaEntity>();
 
         internal SchemaType SchemaType
         {
@@ -115,17 +97,8 @@ namespace System.Xml.Schema
             get { return _attributeDecls; }
         }
 
-        internal Dictionary<string, SchemaNotation> Notations
-        {
-            get
-            {
-                if (_notations == null)
-                {
-                    _notations = new Dictionary<string, SchemaNotation>();
-                }
-                return _notations;
-            }
-        }
+        internal Dictionary<string, SchemaNotation> Notations =>
+            _notations ??= new Dictionary<string, SchemaNotation>();
 
         internal int ErrorCount
         {
index 2d53454..d74f357 100644 (file)
@@ -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;
                 }
             }
index 1c7ba68..17825cd 100644 (file)
@@ -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;
         }
 
index 71a81d7..7ee3d20 100644 (file)
@@ -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);
         }
index 383f372..9698559 100644 (file)
@@ -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)
         {
index 4397a92..65960d5 100644 (file)
@@ -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
index 7f18467..2dc4d66 100644 (file)
@@ -290,11 +290,7 @@ namespace System.Xml.Schema
             }
             else
             {
-                if (_schemaNames == null)
-                {
-                    _schemaNames = new SchemaNames(_nameTable);
-                }
-                return _schemaNames;
+                return _schemaNames ??= new SchemaNames(_nameTable);
             }
         }
 
index 0837f29..b2f8534 100644 (file)
@@ -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)
         {
index aa22f5e..375ee27 100644 (file)
@@ -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
index 7a2882e..62c070b 100644 (file)
@@ -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) { }
index 5bf1358..3bee462 100644 (file)
@@ -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();
 
         /// <summary>
         /// Table of all types extensions
@@ -253,17 +207,8 @@ namespace System.Xml.Schema
         /// <summary>
         /// Table of all types extensions
         /// </summary>
-        internal XmlSchemaObjectTable TypeExtensions
-        {
-            get
-            {
-                if (_typeExtensions == null)
-                {
-                    _typeExtensions = new XmlSchemaObjectTable();
-                }
-                return _typeExtensions;
-            }
-        }
+        internal XmlSchemaObjectTable TypeExtensions => _typeExtensions ??= new XmlSchemaObjectTable();
+
         //Public Methods
 
         /// <summary>
@@ -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<XmlSchemaElement>();
-                            }
+                            newMembers ??= new List<XmlSchemaElement>();
                             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)
index f3f8193..ce3757b 100644 (file)
@@ -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;
         }
index 9a9e08e..7fc4393 100644 (file)
@@ -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;
index 85898fa..7d148ec 100644 (file)
@@ -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<XmlQualifiedName>();
-                    }
+                    _namespaces ??= new List<XmlQualifiedName>();
                     _namespaces.Add(new XmlQualifiedName((name == _schemaNames.QnXmlNs.Name) ? string.Empty : name, value));
                 }
                 else
index 65e6798..3e892ab 100644 (file)
@@ -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);
         }
index d0cfe8c..493a5ca 100644 (file)
@@ -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);
index bb49980..3870118 100644 (file)
@@ -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)
                     {
index 9dd6582..1a09c21 100644 (file)
@@ -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)
index 6b09354..20db540 100644 (file)
@@ -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;
 
index 08e4c7d..8208a68 100644 (file)
@@ -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);
                             };
index 1d7a207..3fbfc26 100644 (file)
@@ -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)
                     {
index ef7a31f..65de47c 100644 (file)
@@ -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()
index 286a8ba..ad97d7e 100644 (file)
@@ -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;
index c1f868c..e7b6c39 100644 (file)
@@ -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<string, MemberInfo>();
-                    }
+                    replaceList ??= new Dictionary<string, MemberInfo>();
 
                     replaceList.Add(pair.Key, replacedInfo);
                 }
index 771dfb7..efd4335 100644 (file)
@@ -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}";
         }
 
index 8ff088b..13f679a 100644 (file)
@@ -74,12 +74,8 @@ namespace System.Xml.Serialization
         /// </devdoc>
         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();
     }
 }
index cef6c76..682c011 100644 (file)
@@ -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();
index f619247..7a1a454 100644 (file)
@@ -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)
index 154d804..50eecb8 100644 (file)
@@ -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)
         {
index eeab379..82b930a 100644 (file)
@@ -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
         {
index 181daac..a11fd84 100644 (file)
@@ -24,17 +24,7 @@ namespace System.Xml.Serialization
         private Dictionary<string, EnumMapping>? _enums;
         private int _nextIdNumber;
 
-        internal Dictionary<string, EnumMapping> Enums
-        {
-            get
-            {
-                if (_enums == null)
-                {
-                    _enums = new Dictionary<string, EnumMapping>();
-                }
-                return _enums;
-            }
-        }
+        internal Dictionary<string, EnumMapping> Enums => _enums ??= new Dictionary<string, EnumMapping>();
 
         private sealed class Member
         {
index 00b1d1f..31f7d73 100644 (file)
@@ -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)
                     {
index df96500..1ff8e3a 100644 (file)
@@ -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)
                     {
index dc04841..6331b41 100644 (file)
@@ -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)]
index c514bd7..79bc2c6 100644 (file)
@@ -100,15 +100,7 @@ namespace System.Xml.Serialization
 
         internal Dictionary<string, XmlQualifiedName>.ValueCollection Namespaces => NamespacesInternal.Values;
 
-        private Dictionary<string, XmlQualifiedName> NamespacesInternal
-        {
-            get
-            {
-                if (_namespaces == null)
-                    _namespaces = new Dictionary<string, XmlQualifiedName>();
-                return _namespaces;
-            }
-        }
+        private Dictionary<string, XmlQualifiedName> NamespacesInternal => _namespaces ??= new Dictionary<string, XmlQualifiedName>();
 
         internal ArrayList? NamespaceList
         {
index 59de59e..77693c6 100644 (file)
@@ -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);
index e66266c..4f847ab 100644 (file)
@@ -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)
index e9de690..a38aad8 100644 (file)
@@ -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;
index 62458a0..b32e858 100644 (file)
@@ -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<XPathNodeRef, XPathNodeRef>();
+            _mapNmsp ??= new Dictionary<XPathNodeRef, XPathNodeRef>();
 
             _mapNmsp.Add(new XPathNodeRef(pageElem, idxElem), new XPathNodeRef(pageNmsp, idxNmsp));
         }
@@ -413,8 +412,7 @@ namespace System.Xml.XPath
         /// </summary>
         internal void AddIdElement(string id, XPathNode[] pageElem, int idxElem)
         {
-            if (_idValueMap == null)
-                _idValueMap = new Dictionary<string, XPathNodeRef>();
+             _idValueMap ??= new Dictionary<string, XPathNodeRef>();
 
             if (!_idValueMap.ContainsKey(id))
                 _idValueMap.Add(id, new XPathNodeRef(pageElem, idxElem));
index c22ec80..bca6862 100644 (file)
@@ -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
index 861960a..8e995b3 100644 (file)
@@ -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);
 
index 03c1a02..3f07b88 100644 (file)
@@ -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
index 569faff..7af21f8 100644 (file)
@@ -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);
index 4f5b3fb..e24e909 100644 (file)
@@ -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);
index ced264a..d510249 100644 (file)
@@ -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!);
         }
index 9b0d7cb..255a6e5 100644 (file)
@@ -75,8 +75,7 @@ namespace System.Xml.Xsl.IlGen
         /// </summary>
         public int DeclareName(string name)
         {
-            if (_uniqueNames == null)
-                _uniqueNames = new UniqueList<string>();
+            _uniqueNames ??= new UniqueList<string>();
 
             return _uniqueNames.Add(name);
         }
@@ -95,8 +94,7 @@ namespace System.Xml.Xsl.IlGen
         /// </summary>
         public int DeclareNameFilter(string locName, string nsUri)
         {
-            if (_uniqueFilters == null)
-                _uniqueFilters = new UniqueList<Int32Pair>();
+            _uniqueFilters ??= new UniqueList<Int32Pair>();
 
             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<StringPair[]>();
+            _prefixMappingsList ??= new List<StringPair[]>();
 
             _prefixMappingsList.Add(prefixMappings);
             return _prefixMappingsList.Count - 1;
@@ -153,8 +150,7 @@ namespace System.Xml.Xsl.IlGen
         {
             int idx;
 
-            if (_globalNames == null)
-                _globalNames = new List<string>();
+            _globalNames ??= new List<string>();
 
             idx = _globalNames.Count;
             _globalNames.Add(name);
@@ -175,8 +171,7 @@ namespace System.Xml.Xsl.IlGen
         /// </summary>
         public int DeclareEarlyBound(string namespaceUri, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type ebType)
         {
-            if (_earlyInfo == null)
-                _earlyInfo = new UniqueList<EarlyBoundInfo>();
+            _earlyInfo ??= new UniqueList<EarlyBoundInfo>();
 
             return _earlyInfo.Add(new EarlyBoundInfo(namespaceUri, ebType));
         }
@@ -184,16 +179,7 @@ namespace System.Xml.Xsl.IlGen
         /// <summary>
         /// Return an array of all early bound information that is used by the query (null if none is used).
         /// </summary>
-        public EarlyBoundInfo[]? EarlyBound
-        {
-            get
-            {
-                if (_earlyInfo != null)
-                    return _earlyInfo.ToArray();
-
-                return null;
-            }
-        }
+        public EarlyBoundInfo[]? EarlyBound => _earlyInfo?.ToArray();
 
         /// <summary>
         /// 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
         /// </summary>
         public int DeclareXmlType(XmlQueryType type)
         {
-            if (_uniqueXmlTypes == null)
-                _uniqueXmlTypes = new UniqueList<XmlQueryType>();
+            _uniqueXmlTypes ??= new UniqueList<XmlQueryType>();
 
             XmlQueryTypeFactory.CheckSerializability(type);
             return _uniqueXmlTypes.Add(type);
@@ -222,8 +207,7 @@ namespace System.Xml.Xsl.IlGen
         /// </summary>
         public int DeclareCollation(string collation)
         {
-            if (_uniqueCollations == null)
-                _uniqueCollations = new UniqueList<XmlCollation>();
+            _uniqueCollations ??= new UniqueList<XmlCollation>();
 
             return _uniqueCollations.Add(XmlCollation.Create(collation));
         }
index 2ca446e..65d93ea 100644 (file)
@@ -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.
         /// </summary>
-        public ArrayList CallersInfo
-        {
-            get
-            {
-                if (_callersInfo == null)
-                    _callersInfo = new ArrayList();
-
-                return _callersInfo;
-            }
-        }
+        public ArrayList CallersInfo => _callersInfo ??= new ArrayList();
 
         /// <summary>
         /// Return name of this annotation.
index 0c7db85..fc1e40a 100644 (file)
@@ -123,10 +123,7 @@ namespace System.Xml.Xsl.IlGen
         /// </summary>
         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
index 1029354..bce34b4 100644 (file)
@@ -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
                 {
index 7946d52..83f5876 100644 (file)
@@ -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);
index 4641526..f9d6dee 100644 (file)
@@ -36,8 +36,7 @@ namespace System.Xml.Xsl.Runtime
             }
 
             // Use this.roots to impose stable ordering
-            if (_roots == null)
-                _roots = new List<XPathNavigator>();
+            _roots ??= new List<XPathNavigator>();
 
             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<XPathNavigator>();
+            _roots ??= new List<XPathNavigator>();
 
             // Position navigator to root
             navRoot = nav.Clone();
index 2ad5fea..496eeb8 100644 (file)
@@ -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;
index c932dca..56c26ba 100644 (file)
@@ -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);
index 1f0519f..7821643 100644 (file)
@@ -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);
index cd34007..fdb8db8 100644 (file)
@@ -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<string, string>(16);
+            _conflictPrefixes ??= new Dictionary<string, string>(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<string>(15);
+            _stkNames ??= new Stack<string>(15);
 
             _stkNames.Push(prefix);
             _stkNames.Push(localName);
index 45746ac..064e333 100644 (file)
@@ -239,18 +239,7 @@ namespace System.Xml.Xsl.Runtime
         /// <summary>
         /// Return the object that manages the state needed to implement various Xslt functions.
         /// </summary>
-        public XsltLibrary XsltFunctions
-        {
-            get
-            {
-                if (_xsltLib == null)
-                {
-                    _xsltLib = new XsltLibrary(this);
-                }
-
-                return _xsltLib;
-            }
-        }
+        public XsltLibrary XsltFunctions => _xsltLib ??= new XsltLibrary(this);
 
         /// <summary>
         /// Get the early-bound extension object identified by "index".  If it does not yet exist, create an instance using the
index 29fc8c7..180f4f6 100644 (file)
@@ -29,8 +29,7 @@ namespace System.Xml.Xsl.Runtime
         /// </summary>
         public void Create()
         {
-            if (_keys == null)
-                _keys = new XmlSortKey[DefaultSortKeyCount];
+            _keys ??= new XmlSortKey[DefaultSortKeyCount];
 
             _pos = 0;
             _keys[0] = null;
index 038e99f..2a6a8ce 100644 (file)
@@ -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;
                     }
index d834225..df96ed6 100644 (file)
@@ -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<XmlQualifiedName, DecimalFormat>();
-            }
+            _decimalFormats ??= new Dictionary<XmlQualifiedName, DecimalFormat>();
             _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<DecimalFormatter>();
-            }
+            _decimalFormatters ??= new List<DecimalFormatter>();
             _decimalFormatters.Add(new DecimalFormatter(formatPicture, CreateDecimalFormat(infinitySymbol, nanSymbol, characters)));
             return _decimalFormatters.Count - 1;
         }
index 0ee028b..53ffbdd 100644 (file)
@@ -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));
         }
index 2b17f4a..043f0f7 100644 (file)
@@ -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)
             {
index b611469..818364a 100644 (file)
@@ -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()!));
index 96010a3..0bcb516 100644 (file)
@@ -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()));
index 224c77d..7009a42 100644 (file)
@@ -117,10 +117,7 @@ namespace System.Xml.Xsl.Xslt
         public void AddContent(XslNode node)
         {
             Debug.Assert(node != null);
-            if (_content == null)
-            {
-                _content = new List<XslNode>();
-            }
+            _content ??= new List<XslNode>();
             _content.Add(node);
         }
 
index b003680..1032449 100644 (file)
@@ -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<XslNode> 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());
index 739fb2a..3a9d084 100644 (file)
@@ -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)
index b6ea0dd..fd6e21a 100644 (file)
@@ -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)
             {
index 14c86ee..9c31386 100644 (file)
@@ -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;
         }
index de35b02..c9ae1d0 100644 (file)
@@ -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;
                         }
index 93e73c0..607bde8 100644 (file)
@@ -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;
         }
 
index 6813edc..b467573 100644 (file)
@@ -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)
index dd263bf..b4e4b19 100644 (file)
@@ -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++)
             {
index 0a1f386..9031e06 100644 (file)
@@ -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;
index cb5ffc7..845fafa 100644 (file)
@@ -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<Key>? _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<Key>();
-            }
+            _keyList ??= new List<Key>();
             _keyList.Add(new Key(name, MatchKey, UseKey));
         }
 
index 27eac7e..2cabf79 100644 (file)
@@ -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());
         }
index 4c06483..907bfbe 100644 (file)
@@ -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)
index fed4d7a..2308a68 100644 (file)
@@ -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)
index 609d790..bab1745 100644 (file)
@@ -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);
         }
index 6c68964..fb9c7fb 100644 (file)
@@ -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++)
                 {
index 5a048fc..543e113 100644 (file)
@@ -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<PropertyInfo> NewProperties
-        {
-            get
-            {
-                if (_newProperties == null)
-                {
-                    _newProperties = ReflectionContext.GetNewPropertiesForType(this);
-                }
-
-                return _newProperties;
-            }
-        }
+        private IEnumerable<PropertyInfo> NewProperties => _newProperties ??= ReflectionContext.GetNewPropertiesForType(this);
     }
 }
index 832312a..c779ad0 100644 (file)
@@ -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,
index 037ddf6..95b2e13 100644 (file)
@@ -215,10 +215,7 @@ namespace System.Reflection.Metadata.Ecma335
             ValidateLabel(handlerStart, nameof(handlerStart));
             ValidateLabel(handlerEnd, nameof(handlerEnd));
 
-            if (_lazyExceptionHandlers == null)
-            {
-                _lazyExceptionHandlers = ImmutableArray.CreateBuilder<ExceptionHandlerInfo>();
-            }
+            _lazyExceptionHandlers ??= ImmutableArray.CreateBuilder<ExceptionHandlerInfo>();
 
             _lazyExceptionHandlers.Add(new ExceptionHandlerInfo(kind, tryStart, tryEnd, handlerStart, handlerEnd, filterStart, catchType));
         }
index 30f2027..bf66a5a 100644 (file)
@@ -178,10 +178,7 @@ namespace System.Reflection.Metadata.Ecma335
                     Debug.Assert(data.Namespaces!.Count == 0);
                     data.MergeInto(existingRecord);
 
-                    if (remaps == null)
-                    {
-                        remaps = new List<KeyValuePair<NamespaceDefinitionHandle, NamespaceDataBuilder>>();
-                    }
+                    remaps ??= new List<KeyValuePair<NamespaceDefinitionHandle, NamespaceDataBuilder>>();
                     remaps.Add(new KeyValuePair<NamespaceDefinitionHandle, NamespaceDataBuilder>(group.Key, existingRecord));
                 }
                 else
index 7c9f080..89a221b 100644 (file)
@@ -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))
             {
index 5cacd03..0f6dc1e 100644 (file)
@@ -84,8 +84,7 @@ namespace System.Reflection.Metadata
                         break;
 
                     case MethodSemanticsAttributes.Other:
-                        if (other == null)
-                            other = ImmutableArray.CreateBuilder<MethodDefinitionHandle>();
+                        other ??= ImmutableArray.CreateBuilder<MethodDefinitionHandle>();
 
                         other.Add(_reader.MethodSemanticsTable.GetMethod(rowId));
                         break;
index c527ef4..00b28b1 100644 (file)
@@ -91,8 +91,7 @@ namespace System.Reflection.Metadata
                         break;
 
                     case MethodSemanticsAttributes.Other:
-                        if (other == null)
-                            other = ImmutableArray.CreateBuilder<MethodDefinitionHandle>();
+                        other ??= ImmutableArray.CreateBuilder<MethodDefinitionHandle>();
 
                         other.Add(_reader.MethodSemanticsTable.GetMethod(rowId));
                         break;
index 98808e1..73e8dcb 100644 (file)
@@ -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;
     }
 }
index daebb5e..6a951b7 100644 (file)
@@ -44,10 +44,7 @@ namespace System.Reflection.TypeLoading
                     }
                     else
                     {
-                        if (exceptions == null)
-                        {
-                            exceptions = new List<Exception>();
-                        }
+                        exceptions ??= new List<Exception>();
                         exceptions.Add(exception!);
                     }
                 }
index 7817703..5b8b52a 100644 (file)
@@ -278,8 +278,7 @@ namespace System.Reflection.TypeLoading
             Func<Assembly?, string, bool, Type?> typeResolver =
                 delegate (Assembly? assembly, string fullName, bool ignoreCase2)
                 {
-                    if (assembly == null)
-                        assembly = defaultAssembly;
+                    assembly ??= defaultAssembly;
 
                     Debug.Assert(assembly is RoAssembly);
                     RoAssembly roAssembly = (RoAssembly)assembly;
index 23341e6..288d658 100644 (file)
@@ -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;
index 1615da1..8644574 100644 (file)
@@ -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);
             }
index 49cadc1..716001e 100644 (file)
@@ -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);
         }
index fdd3d52..79e06d1 100644 (file)
@@ -21,17 +21,7 @@ namespace System.Runtime.Caching
             set { _absExpiry = value; }
         }
 
-        public Collection<ChangeMonitor> ChangeMonitors
-        {
-            get
-            {
-                if (_changeMonitors == null)
-                {
-                    _changeMonitors = new Collection<ChangeMonitor>();
-                }
-                return _changeMonitors;
-            }
-        }
+        public Collection<ChangeMonitor> ChangeMonitors => _changeMonitors ??= new Collection<ChangeMonitor>();
 
         public CacheItemPriority Priority
         {
index 6241c44..c135219 100644 (file)
@@ -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<ChangeMonitor>();
-            }
+            changeMonitors ??= new Collection<ChangeMonitor>();
             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<string, object>();
-                        }
+                        values ??= new Dictionary<string, object>();
                         values[key] = value;
                     }
                 }
index c84a72f..dcf2a6d 100644 (file)
@@ -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<MemoryCacheEntryChangeMonitor, MemoryCacheEntryChangeMonitor>();
-                }
+
+                _fields ??= new SeldomUsedFields();
+                _fields._cache ??= cache;
+                _fields._dependents ??= new Dictionary<MemoryCacheEntryChangeMonitor, MemoryCacheEntryChangeMonitor>();
                 _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);
             }
         }
index 2d224e9..c7ede67 100644 (file)
@@ -53,12 +53,9 @@ namespace Microsoft.Interop.Analyzers
 
         private static async Task<Solution> 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);
 
index b52328e..2cee662 100644 (file)
@@ -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))
             {
index 214e7fe..ca64749 100644 (file)
@@ -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;
index a11b6f6..27b8a9a 100644 (file)
@@ -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<MethodInfo>();
+                        mi ??= new List<MethodInfo>();
                         mi.Add(m);
                     }
                 }
index e192e60..6158716 100644 (file)
@@ -341,17 +341,7 @@ namespace System.Security.Claims
         /// <summary>
         /// Gets the collection of Properties associated with the <see cref="Claim"/>.
         /// </summary>
-        public IDictionary<string, string> Properties
-        {
-            get
-            {
-                if (_properties == null)
-                {
-                    _properties = new Dictionary<string, string>();
-                }
-                return _properties;
-            }
-        }
+        public IDictionary<string, string> Properties => _properties ??= new Dictionary<string, string>();
 
         /// <summary>
         /// Gets the subject of the <see cref="Claim"/>.
index a0f3e6b..282c8fe 100644 (file)
@@ -343,17 +343,7 @@ namespace System.Security.Claims
         /// Allow the association of claims with this instance of <see cref="ClaimsIdentity"/>.
         /// The claims will not be serialized or added in Clone(). They will be included in searches, finds and returned from the call to <see cref="ClaimsIdentity.Claims"/>.
         /// </summary>
-        internal List<List<Claim>> ExternalClaims
-        {
-            get
-            {
-                if (_externalClaims == null)
-                {
-                    _externalClaims = new List<List<Claim>>();
-                }
-                return _externalClaims;
-            }
-        }
+        internal List<List<Claim>> ExternalClaims => _externalClaims ??= new List<List<Claim>>();
 
         /// <summary>
         /// Gets or sets the label for this <see cref="ClaimsIdentity"/>
index 008cebd..a7cba21 100644 (file)
@@ -57,10 +57,7 @@ namespace System.Security.Cryptography.Pkcs
 
             byte[] encrypted = safeContents.Encrypt(ReadOnlySpan<char>.Empty, passwordBytes, pbeParameters);
 
-            if (_contents == null)
-            {
-                _contents = new List<ContentInfoAsn>();
-            }
+            _contents ??= new List<ContentInfoAsn>();
 
             _contents.Add(
                 new ContentInfoAsn
@@ -110,10 +107,7 @@ namespace System.Security.Cryptography.Pkcs
 
             byte[] encrypted = safeContents.Encrypt(password, ReadOnlySpan<byte>.Empty, pbeParameters);
 
-            if (_contents == null)
-            {
-                _contents = new List<ContentInfoAsn>();
-            }
+            _contents ??= new List<ContentInfoAsn>();
 
             _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<ContentInfoAsn>();
-            }
+            _contents ??= new List<ContentInfoAsn>();
 
             _contents.Add(safeContents.EncodeToContentInfo());
         }
index e0a2108..0c7eb16 100644 (file)
@@ -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();
         }
index e2dcd03..e9edb96 100644 (file)
@@ -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();
         }
index e2f7666..bcf62d5 100644 (file)
@@ -65,10 +65,7 @@ namespace System.Security.Cryptography.Pkcs
             if (IsReadOnly)
                 throw new InvalidOperationException(SR.Cryptography_Pkcs12_SafeContentsIsReadOnly);
 
-            if (_bags == null)
-            {
-                _bags = new List<Pkcs12SafeBag>();
-            }
+            _bags ??= new List<Pkcs12SafeBag>();
 
             _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);
index 7709f27..c214def 100644 (file)
@@ -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();
         }
index a677fcd..2ee1049 100644 (file)
@@ -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<byte> 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
         {
index 4d8d96a..47f374e 100644 (file)
@@ -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)
         {
index e8e282f..315e5ea 100644 (file)
@@ -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;
index 2e5680f..61c5339 100644 (file)
@@ -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)
index 4be3199..537d1a5 100644 (file)
@@ -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;
         }
 
         //
index d56ce81..81bad80 100644 (file)
@@ -99,8 +99,7 @@ namespace System.Security.Cryptography.Xml
 
                     KeyInfoClause keyInfoClause = CryptoHelpers.CreateFromName<KeyInfoClause>(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);
index 53104e7..f92b4db 100644 (file)
@@ -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));
         }
 
index 6cad039..32a7cc4 100644 (file)
@@ -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;
index ac61737..e88334f 100644 (file)
@@ -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
index c2d6881..a717789 100644 (file)
@@ -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);
 
index 513b1a8..6920c73 100644 (file)
@@ -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)
         {
index 429f925..996a9fb 100644 (file)
@@ -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)))
index 9357680..53ad764 100644 (file)
@@ -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)
index 550b4ce..e184e13 100644 (file)
@@ -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;
index e53b628..68b0889 100644 (file)
@@ -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;
         }
index 25ced97..945918a 100644 (file)
@@ -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];
index 51b244f..f5ee38e 100644 (file)
@@ -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;
index 574cdf8..cfa39e5 100644 (file)
@@ -42,10 +42,7 @@ namespace System.Security.Cryptography
 
         public override void AppendHashData(ReadOnlySpan<byte> data)
         {
-            if (buffer == null)
-            {
-                buffer = new MemoryStream(1000);
-            }
+            buffer ??= new MemoryStream(1000);
 
             buffer.Write(data);
         }
index c62dc60..c35b33b 100644 (file)
@@ -243,11 +243,7 @@ namespace System.Security.Cryptography.X509Certificates
                         e = value;
                         break;
                     default:
-                        if (firstRdn == null)
-                        {
-                            firstRdn = value;
-                        }
-
+                        firstRdn ??= value;
                         break;
                 }
             }
index 3096f31..ba5e813 100644 (file)
@@ -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<X509ChainStatus>();
-                    }
+                    statuses[i] ??= new List<X509ChainStatus>();
 
                     AddUniqueStatus(statuses[i], ref statusToSet);
                 }
index 0b1d6dd..780262e 100644 (file)
@@ -262,10 +262,7 @@ namespace System.Security.Cryptography.X509Certificates
                         break;
                     }
 
-                    if (downloadedCerts == null)
-                    {
-                        downloadedCerts = new List<X509Certificate2>();
-                    }
+                    downloadedCerts ??= new List<X509Certificate2>();
 
                     AddToStackAndUpRef(downloaded.Handle, _untrustedLookup);
                     downloadedCerts.Add(downloaded);
@@ -917,10 +914,7 @@ namespace System.Security.Cryptography.X509Certificates
 
             if (failsPolicyChecks)
             {
-                if (overallStatus == null)
-                {
-                    overallStatus = new List<X509ChainStatus>();
-                }
+                overallStatus ??= new List<X509ChainStatus>();
 
                 X509ChainStatus chainStatus = new X509ChainStatus
                 {
index f7454d5..a9a89f6 100644 (file)
@@ -275,10 +275,7 @@ namespace System.Security.Cryptography.X509Certificates
 
         private void Decrypt(ReadOnlySpan<char> password, ReadOnlyMemory<byte> 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.
index 1da4b68..90c4aee 100644 (file)
@@ -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)
         {
index 4cfddb4..072923e 100644 (file)
@@ -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;
             }
index 7a9286a..e7b5cb1 100644 (file)
@@ -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<X509ChainStatus>() : _pal.ChainStatus!);
-                return chainStatus;
+                return _lazyChainStatus ??= (_pal == null ? Array.Empty<X509ChainStatus>() : _pal.ChainStatus!);
             }
         }
 
index 0ba24b4..e493ab5 100644 (file)
@@ -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);
index 4121e19..d8e3947 100644 (file)
@@ -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;
index 848efb5..060fd7b 100644 (file)
@@ -161,8 +161,7 @@ namespace System.Security.Permissions
                         }
                         if (addToNewIDRoles)
                         {
-                            if (idroles == null)
-                                idroles = new List<IDRole>();
+                            idroles ??= new List<IDRole>();
                             idroles.Add(new IDRole(newAuthenticated, newID, newRole));
                         }
                     }
index 5cfa788..b9f353f 100644 (file)
@@ -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();
     }
 }
index 1a21a72..3eca69a 100644 (file)
@@ -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;
             }
index 2050b17..ec4388d 100644 (file)
@@ -582,10 +582,7 @@ namespace System.ServiceModel.Syndication
                     if (preserveAttributeExtensions)
                     {
                         string value = reader.Value;
-                        if (attrs == null)
-                        {
-                            attrs = new Dictionary<XmlQualifiedName, string>();
-                        }
+                        attrs ??= new Dictionary<XmlQualifiedName, string>();
                         attrs.Add(new XmlQualifiedName(name, ns), value);
                     }
                 }
index b37e04b..a679681 100644 (file)
@@ -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))
index c645a58..31e669a 100644 (file)
@@ -124,14 +124,7 @@ namespace System.ServiceModel.Syndication
             _extensions.LoadElementExtensions(buffer);
         }
 
-        private static IEnumerable<string> CreateSingleEmptyAccept()
-        {
-            if (s_singleEmptyAccept == null)
-            {
-                s_singleEmptyAccept = new List<string>(1) { string.Empty }.AsReadOnly();
-            }
-
-            return s_singleEmptyAccept;
-        }
+        private static IEnumerable<string> CreateSingleEmptyAccept() =>
+            s_singleEmptyAccept ??= new List<string>(1) { string.Empty }.AsReadOnly();
     }
 }
index 980318e..8baf3c9 100644 (file)
@@ -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;
index df531ef..5829235 100644 (file)
@@ -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);
         }
index 3188e57..f3a4d74 100644 (file)
@@ -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<TExtension> results = new Collection<TExtension>();
             for (int i = 0; i < Count; ++i)
             {
index e7ba697..c9b5d43 100644 (file)
@@ -100,10 +100,7 @@ namespace System.ServiceModel.Syndication
 
         public TContent ReadContent<TContent>(XmlObjectSerializer dataContractSerializer)
         {
-            if (dataContractSerializer == null)
-            {
-                dataContractSerializer = new DataContractSerializer(typeof(TContent));
-            }
+            dataContractSerializer ??= new DataContractSerializer(typeof(TContent));
             if (Extension != null)
             {
                 return Extension.GetObject<TContent>(dataContractSerializer);
@@ -122,10 +119,7 @@ namespace System.ServiceModel.Syndication
 
         public TContent ReadContent<TContent>(XmlSerializer serializer)
         {
-            if (serializer == null)
-            {
-                serializer = new XmlSerializer(typeof(TContent));
-            }
+            serializer ??= new XmlSerializer(typeof(TContent));
             if (Extension != null)
             {
                 return Extension.GetObject<TContent>(serializer);
index 09df969..ddc3e2e 100644 (file)
@@ -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.
         /// </summary>
         [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
index 088c41c..017c75c 100644 (file)
@@ -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);
         }
 
         /// <summary>
index 0f57d4c..7a3135d 100644 (file)
@@ -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
         {
index 7754e73..c91a07e 100644 (file)
@@ -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";
index d68ccd6..10f432b 100644 (file)
@@ -201,16 +201,7 @@ namespace System.Speech.Synthesis
             }
         }
         [EditorBrowsable(EditorBrowsableState.Advanced)]
-        public IDictionary<string, string> AdditionalInfo
-        {
-            get
-            {
-                if (_attributes == null)
-                    _attributes = new ReadOnlyDictionary<string, string>(new Dictionary<string, string>(0));
-                return _attributes;
-            }
-        }
-
+        public IDictionary<string, string> AdditionalInfo => _attributes ??= new ReadOnlyDictionary<string, string>(new Dictionary<string, string>(0));
         #endregion
 
         #region Internal Methods
index 846da4c..571aa1f 100644 (file)
@@ -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();
                 }
             }
         }
index e232be8..95a038e 100644 (file)
@@ -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();
                 }
             }
         }
index 12255d9..40d70a5 100644 (file)
@@ -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;
 
index decf879..fef9b48 100644 (file)
@@ -108,11 +108,7 @@ namespace System.Text.Json.Nodes
             }
             else
             {
-                JsonNode? jNode = value as JsonNode;
-                if (jNode == null)
-                {
-                    jNode = new JsonValueNotTrimmable<T>(value);
-                }
+                JsonNode jNode = value as JsonNode ?? new JsonValueNotTrimmable<T>(value);
 
                 // Call the IList.Add() implementation.
                 Add(jNode);
index 53a13a2..c9a66ed 100644 (file)
@@ -24,10 +24,7 @@ namespace System.Text.Json.Serialization
         {
             var wrappedValue = new ReferenceEqualsWrapper(value);
 
-            if (_stackForCycleDetection is null)
-            {
-                _stackForCycleDetection = new Stack<ReferenceEqualsWrapper>();
-            }
+            _stackForCycleDetection ??= new Stack<ReferenceEqualsWrapper>();
 
             Debug.Assert(!_stackForCycleDetection.Contains(wrappedValue));
             _stackForCycleDetection.Push(wrappedValue);
index ff47237..2dd8adf 100644 (file)
@@ -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)
index 7b1202a..3d99324 100644 (file)
@@ -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<PropertyRef>();
-                    }
+                    frame.PropertyRefCache ??= new List<PropertyRef>();
 
                     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<ParameterRef>();
-                    }
+                    frame.CtorArgumentState.ParameterRefCache ??= new List<ParameterRef>();
 
                     parameterRef = new ParameterRef(key, info!, utf8PropertyName);
                     frame.CtorArgumentState.ParameterRefCache.Add(parameterRef);
index fc86396..439de06 100644 (file)
@@ -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<Task<bool>>();
+                                    _tempSendAsyncTaskList ??= new List<Task<bool>>();
 
                                     // Add the task to the list
                                     _tempSendAsyncTaskList.Add(sendAsyncTask);
index 56ee24c..05ca506 100644 (file)
@@ -1101,7 +1101,7 @@ namespace System.Threading.Tasks.Dataflow
                         catch (Exception e)
                         {
                             if (throwOnFirstException) throw;
-                            if (exceptions == null) exceptions = new List<Exception>(1);
+                            exceptions ??= new List<Exception>(1);
                             exceptions.Add(e);
                         }
                     }
index 85a980d..927e971 100644 (file)
@@ -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<TOutput>? itemAsTrustedList = item as TOutput[];
-            if (itemAsTrustedList == null) itemAsTrustedList = item as List<TOutput>;
+            IList<TOutput>? itemAsTrustedList = (IList<TOutput>?)(item as TOutput[]) ?? item as List<TOutput>;
             if (itemAsTrustedList != null && isBounded)
             {
                 UpdateBoundingCountWithOutputCount(count: itemAsTrustedList.Count);
index 9fd0653..e222fa3 100644 (file)
@@ -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;
index b9e08e7..a7b9aa1 100644 (file)
@@ -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
index 7b16ffc..4126a75 100644 (file)
@@ -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)
index c27adcf..c4d3c4a 100644 (file)
@@ -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;
index 34bc3b8..1329ab1 100644 (file)
@@ -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;
index ee42f6d..995ea8c 100644 (file)
@@ -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();
index 7873186..360dc3e 100644 (file)
@@ -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);
index e6e90c7..9971f14 100644 (file)
@@ -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;
                 }
index c970d47..b1ce057 100644 (file)
@@ -85,10 +85,7 @@ namespace System.Media
             get => _soundLocation;
             set
             {
-                if (value == null)
-                {
-                    value = string.Empty;
-                }
+                value ??= string.Empty;
 
                 if (_soundLocation.Equals(value))
                 {
index c0c16a9..54cc282 100644 (file)
@@ -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");
index 55d3aa8..9ae8182 100644 (file)
@@ -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<Type, AttributeUsageAttribute>();
+            usage_cache ??= new Dictionary<Type, AttributeUsageAttribute>();
             if (usage_cache.TryGetValue(attributeType, out usageAttribute))
                 return usageAttribute;
             usageAttribute = RetrieveAttributeUsageNoCache(attributeType);
index ea546a5..eeb3a37 100644 (file)
@@ -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);
         }
         */
index c1f4df1..3f7f25a 100644 (file)
@@ -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];
index bc40ef5..478e66c 100644 (file)
@@ -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;
         }
index 5dbafb8..8ccdd30 100644 (file)
@@ -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
index 84a0090..45c734e 100644 (file)
@@ -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.");
index b2ee5ca..4178b25 100644 (file)
@@ -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,
index 88a493f..48bed67 100644 (file)
@@ -177,29 +177,32 @@ namespace System.Reflection.Emit
 
         internal override MethodInfo GetMethod(MethodInfo fromNoninstanciated)
         {
-            if (methods == null)
-                methods = new Dictionary<MethodInfo, MethodInfo>();
-            if (!methods.ContainsKey(fromNoninstanciated))
-                methods[fromNoninstanciated] = new MethodOnTypeBuilderInst(this, fromNoninstanciated);
-            return methods[fromNoninstanciated]!;
+            methods ??= new Dictionary<MethodInfo, MethodInfo>();
+            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<ConstructorInfo, ConstructorInfo>();
-            if (!ctors.ContainsKey(fromNoninstanciated))
-                ctors[fromNoninstanciated] = new ConstructorOnTypeBuilderInst(this, fromNoninstanciated);
-            return ctors[fromNoninstanciated]!;
+            ctors ??= new Dictionary<ConstructorInfo, ConstructorInfo>();
+            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<FieldInfo, FieldInfo>();
-            if (!fields.ContainsKey(fromNoninstanciated))
-                fields[fromNoninstanciated] = new FieldOnTypeBuilderInst(this, fromNoninstanciated);
-            return fields[fromNoninstanciated]!;
+            fields ??= new Dictionary<FieldInfo, FieldInfo>();
+            if (!fields.TryGetValue(fromNoninstanciated, out FieldInfo? fi))
+            {
+                fields[fromNoninstanciated] = fi = new FieldOnTypeBuilderInst(this, fromNoninstanciated);
+            }
+            return fi;
         }
 
         [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)]
index a9844f7..f59e3e2 100644 (file)
@@ -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);
         }
index 73aa474..1fcb299 100644 (file)
@@ -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)
             {
index 32c447f..d44dbff 100644 (file)
@@ -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<RuntimeType>(2);
+                list ??= new List<RuntimeType>(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
index 6d966fb..db6db62 100644 (file)
@@ -307,16 +307,14 @@ namespace System
                         pos++;
                         isbyref = true;
                         isptr = false;
-                        if (res.Modifiers == null)
-                            res.Modifiers = new List<int>();
+                        res.Modifiers ??= new List<int>();
                         res.Modifiers.Add(0);
                         break;
                     case '*':
                         if (isbyref)
                             return null;
                         pos++;
-                        if (res.Modifiers == null)
-                            res.Modifiers = new List<int>();
+                        res.Modifiers ??= new List<int>();
                         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<int>();
+                            res.Modifiers ??= new List<int>();
                             if (bounded)
                                 res.Modifiers.Add(-2);
                             res.Modifiers.Add(rank);
index 23749b5..516975f 100644 (file)
@@ -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<ITypeIdentifier>();
+                nested ??= new List<ITypeIdentifier>();
                 nested.Add(ParsedTypeIdentifier(type_name));
             }
         }
 
-        private void AddModifier(IModifierSpec md)
-        {
-            if (modifier_spec == null)
-                modifier_spec = new List<IModifierSpec>();
-            modifier_spec.Add(md);
-        }
+        private void AddModifier(IModifierSpec md) => modifier_spec ??= new List<IModifierSpec>();
 
         private static void SkipSpace(string name, ref int pos)
         {