From 6fa9f8134619f43b0a847b249453790f009fe0ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20K=C3=B6plinger?= Date: Mon, 15 Sep 2025 18:05:39 +0200 Subject: [PATCH 1/7] Use null-coalescing operator in LocalDataFlowState.cs Fixes https://github.com/dotnet/runtime/issues/119391 --- .../src/ILLink.RoslynAnalyzer/DataFlow/LocalDataFlowState.cs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/tools/illink/src/ILLink.RoslynAnalyzer/DataFlow/LocalDataFlowState.cs b/src/tools/illink/src/ILLink.RoslynAnalyzer/DataFlow/LocalDataFlowState.cs index 6b9c673438f99f..e6fa0d5ca2b1a0 100644 --- a/src/tools/illink/src/ILLink.RoslynAnalyzer/DataFlow/LocalDataFlowState.cs +++ b/src/tools/illink/src/ILLink.RoslynAnalyzer/DataFlow/LocalDataFlowState.cs @@ -27,9 +27,8 @@ public LocalStateAndContext Current public void Set(LocalKey key, TValue value) { current.LocalState.Set(key, value); - if (Exception != null) - // TODO: optimize this to not meet the whole value, but just modify one value without copying. - Exception.Value = Lattice.Meet(Exception.Value, current); + // TODO: optimize this to not meet the whole value, but just modify one value without copying. + Exception?.Value = Lattice.Meet(Exception.Value, current); } public TValue Get(LocalKey key) => current.LocalState.Get(key); From 06be5b650e99c0ca0f06052f1891a1c9393f1b29 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20K=C3=B6plinger?= Date: Mon, 15 Sep 2025 18:18:23 +0200 Subject: [PATCH 2/7] Copilot feedback --- .../src/ILLink.RoslynAnalyzer/DataFlow/LocalDataFlowState.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/illink/src/ILLink.RoslynAnalyzer/DataFlow/LocalDataFlowState.cs b/src/tools/illink/src/ILLink.RoslynAnalyzer/DataFlow/LocalDataFlowState.cs index e6fa0d5ca2b1a0..4c44d46874bb92 100644 --- a/src/tools/illink/src/ILLink.RoslynAnalyzer/DataFlow/LocalDataFlowState.cs +++ b/src/tools/illink/src/ILLink.RoslynAnalyzer/DataFlow/LocalDataFlowState.cs @@ -28,7 +28,7 @@ public void Set(LocalKey key, TValue value) { current.LocalState.Set(key, value); // TODO: optimize this to not meet the whole value, but just modify one value without copying. - Exception?.Value = Lattice.Meet(Exception.Value, current); + Exception?.Value = Lattice.Meet(Exception?.Value, current); } public TValue Get(LocalKey key) => current.LocalState.Get(key); From 2df2d475c390519b3ae30545eaf2f167e3e69557 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20K=C3=B6plinger?= Date: Mon, 15 Sep 2025 18:29:45 +0200 Subject: [PATCH 3/7] Revert Copilot feedback --- .../src/ILLink.RoslynAnalyzer/DataFlow/LocalDataFlowState.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/illink/src/ILLink.RoslynAnalyzer/DataFlow/LocalDataFlowState.cs b/src/tools/illink/src/ILLink.RoslynAnalyzer/DataFlow/LocalDataFlowState.cs index 4c44d46874bb92..e6fa0d5ca2b1a0 100644 --- a/src/tools/illink/src/ILLink.RoslynAnalyzer/DataFlow/LocalDataFlowState.cs +++ b/src/tools/illink/src/ILLink.RoslynAnalyzer/DataFlow/LocalDataFlowState.cs @@ -28,7 +28,7 @@ public void Set(LocalKey key, TValue value) { current.LocalState.Set(key, value); // TODO: optimize this to not meet the whole value, but just modify one value without copying. - Exception?.Value = Lattice.Meet(Exception?.Value, current); + Exception?.Value = Lattice.Meet(Exception.Value, current); } public TValue Get(LocalKey key) => current.LocalState.Get(key); From d87af8e99d7700b6551db326b4ae412dd406e5a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20K=C3=B6plinger?= Date: Mon, 15 Sep 2025 20:22:01 +0200 Subject: [PATCH 4/7] Fix IDE0031 analyzer findings --- .../RuntimeConstructorInfo.CoreCLR.cs | 3 +-- .../Reflection/RuntimeMethodInfo.CoreCLR.cs | 3 +-- .../System/Collections/Generic/SortedSet.cs | 5 +---- .../Composition/Hosting/AtomicComposition.cs | 5 +---- .../System/ComponentModel/EventHandlerList.cs | 5 +---- .../ReflectTypeDescriptionProvider.cs | 10 ++-------- .../Configuration/ConfigurationValues.cs | 2 +- .../System/Configuration/SectionUpdates.cs | 2 +- .../src/System/Data/DataColumn.cs | 18 +++++------------ .../src/System/Data/DataColumnCollection.cs | 5 +---- .../src/System/Data/DataSet.cs | 9 +++------ .../src/System/Data/DataTable.cs | 5 +---- .../src/System/Data/Merger.cs | 5 +---- .../src/System/Data/Select.cs | 18 ++++------------- .../src/System/Data/XMLSchema.cs | 20 +++++-------------- .../src/System/Xml/XmlDataDocument.cs | 6 ++---- .../src/System/Data/Odbc/OdbcCommand.cs | 10 ++-------- .../System/Data/Odbc/OdbcConnectionFactory.cs | 5 +---- .../Protocols/ldap/LdapConnection.cs | 10 ++-------- .../System/Dynamic/Utils/ExpressionUtils.cs | 5 +---- .../Linq/Expressions/Compiler/StackSpiller.cs | 20 ++++--------------- .../Linq/Expressions/IndexExpression.cs | 5 +---- .../Linq/Expressions/NewArrayExpression.cs | 5 +---- .../System/Linq/Expressions/NewExpression.cs | 10 ++-------- .../Net/Http/HttpMethod.SocketsHttpHandler.cs | 15 +++----------- .../ConnectionSetupDistributedTracing.cs | 5 +---- .../src/System/Net/Sockets/TCPClient.cs | 5 +---- .../src/System/Net/Sockets/TCPListener.cs | 5 +---- .../System/Net/WebSockets/ClientWebSocket.cs | 5 +---- .../src/System/Array.cs | 12 ++++------- .../Tracing/TraceLogging/FieldMetadata.cs | 10 ++-------- .../Tracing/TraceLogging/Statics.cs | 5 +---- .../Threading/CancellationTokenSource.cs | 20 ++++--------------- .../src/System/Threading/SemaphoreSlim.cs | 4 ++-- .../src/System/Threading/ThreadLocal.cs | 10 ++-------- .../src/System/Threading/Timer.cs | 15 +++----------- .../Runtime/Serialization/SchemaExporter.cs | 15 ++++++-------- .../Xml/Core/XmlEncodedRawTextWriter.cs | 5 +---- .../Xml/Core/XmlEncodedRawTextWriterAsync.cs | 5 +---- .../System/Xml/Core/XmlWellFormedWriter.cs | 5 +---- .../src/System/Xml/Dom/XmlDocument.cs | 5 +---- .../src/System/Xml/Dom/XmlLoader.cs | 5 +---- .../Xml/Resolvers/XmlPreloadedResolver.cs | 5 +---- .../src/System/Xml/Schema/Asttree.cs | 5 +---- .../Schema/SchemaCollectionpreProcessor.cs | 5 +---- .../System/Xml/Schema/XmlSchemaValidator.cs | 11 +++------- .../Xml/Serialization/XmlSchemaExporter.cs | 17 ++++++---------- .../Xml/Xsl/Runtime/XmlAttributeCache.cs | 3 +-- .../System/Xml/Xsl/Runtime/XmlQueryOutput.cs | 3 +-- .../Runtime/Caching/MemoryCacheStore.cs | 5 +---- .../Formatters/Binary/BinaryObjectReader.cs | 5 +---- .../src/System/Text/SBCSCodePageEncoding.cs | 6 ++---- .../System/Text/Json/Nodes/JsonArray.IList.cs | 5 +---- .../Text/Json/Nodes/JsonObject.IDictionary.cs | 5 +---- .../src/System/Text/Json/Nodes/JsonObject.cs | 5 +---- .../Serialization/JsonSerializerOptions.cs | 5 +---- .../src/System/Threading/Tasks/Parallel.cs | 5 ++--- .../System/Transactions/TransactionState.cs | 7 ++----- .../System/Transactions/TransactionTable.cs | 9 +++------ .../src/linker/Linker/DynamicDependency.cs | 3 +-- 60 files changed, 111 insertions(+), 340 deletions(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeConstructorInfo.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeConstructorInfo.CoreCLR.cs index dd855b65fdee93..d47d19050c4d64 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeConstructorInfo.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeConstructorInfo.CoreCLR.cs @@ -221,8 +221,7 @@ private void InvokeClassConstructor() public override MethodBody? GetMethodBody() { RuntimeMethodBody? mb = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal); - if (mb != null) - mb._methodBase = this; + mb?._methodBase = this; return mb; } diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeMethodInfo.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeMethodInfo.CoreCLR.cs index 16ff331c2fdd7c..a593aa335b3a96 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeMethodInfo.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeMethodInfo.CoreCLR.cs @@ -274,8 +274,7 @@ public override MethodImplAttributes GetMethodImplementationFlags() public override MethodBody? GetMethodBody() { RuntimeMethodBody? mb = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal); - if (mb != null) - mb._methodBase = this; + mb?._methodBase = this; return mb; } diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.cs b/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.cs index 4ab5df4f1274c1..8af41f5b5b5079 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.cs @@ -682,10 +682,7 @@ private void ReplaceNode(Node match, Node parentOfMatch, Node successor, Node pa successor.Left = match.Left; } - if (successor != null) - { - successor.Color = match.Color; - } + successor?.Color = match.Color; ReplaceChildOrRoot(parentOfMatch, match, successor!); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AtomicComposition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AtomicComposition.cs index df7f091ed1c295..1a54ba2880643d 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AtomicComposition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AtomicComposition.cs @@ -137,10 +137,7 @@ protected virtual void Dispose(bool disposing) ThrowIfDisposed(); _isDisposed = true; - if (_outerAtomicComposition != null) - { - _outerAtomicComposition.ContainsInnerAtomicComposition = false; - } + _outerAtomicComposition?.ContainsInnerAtomicComposition = false; // Revert is always immediate and involves forgetting information and // exceuting any appropriate revert actions diff --git a/src/libraries/System.ComponentModel.Primitives/src/System/ComponentModel/EventHandlerList.cs b/src/libraries/System.ComponentModel.Primitives/src/System/ComponentModel/EventHandlerList.cs index b59376691ccced..f0ad031d05b5b6 100644 --- a/src/libraries/System.ComponentModel.Primitives/src/System/ComponentModel/EventHandlerList.cs +++ b/src/libraries/System.ComponentModel.Primitives/src/System/ComponentModel/EventHandlerList.cs @@ -100,10 +100,7 @@ public void AddHandlers(EventHandlerList listToAddFrom) public void RemoveHandler(object key, Delegate? value) { ListEntry? e = Find(key); - if (e != null) - { - e._handler = Delegate.Remove(e._handler, value); - } + e?._handler = Delegate.Remove(e._handler, value); } private sealed class ListEntry diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.cs index a889ae78692168..dd302158103b5c 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.cs @@ -637,10 +637,7 @@ internal PropertyDescriptorCollection GetExtendedProperties(object instance) properties = PropertyDescriptorCollection.Empty; } - if (cache != null) - { - cache[s_extenderPropertiesKey] = properties; - } + cache?[s_extenderPropertiesKey] = properties; return properties; } @@ -1312,10 +1309,7 @@ private static PropertyDescriptor[] ReflectGetExtendedProperties(IExtenderProvid properties[idx] = new ExtendedPropertyDescriptor(rpd, rpd.ExtenderGetReceiverType(), provider, null); } - if (cache != null) - { - cache[s_extenderProviderPropertiesKey] = properties; - } + cache?[s_extenderProviderPropertiesKey] = properties; return properties; } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationValues.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationValues.cs index a1baf82ff80881..7ec5ffdb73ce28 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationValues.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationValues.cs @@ -83,7 +83,7 @@ internal PropertySourceInfo GetSourceInfo(string key) internal void ChangeSourceInfo(string key, PropertySourceInfo sourceInfo) { ConfigurationValue configurationValue = GetConfigValue(key); - if (configurationValue != null) configurationValue.SourceInfo = sourceInfo; + configurationValue?.SourceInfo = sourceInfo; } private ConfigurationValue CreateConfigValue(object value, ConfigurationValueFlags valueFlags, diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SectionUpdates.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SectionUpdates.cs index d67be0bafaa62c..779152c7ef687a 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SectionUpdates.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SectionUpdates.cs @@ -146,7 +146,7 @@ internal void MarkAsRetrieved() { _cUnretrieved = 0; foreach (SectionUpdates sectionUpdates in _groups.Values) sectionUpdates.MarkAsRetrieved(); - if (_sectionGroupUpdate != null) _sectionGroupUpdate.Retrieved = true; + _sectionGroupUpdate?.Retrieved = true; } internal void MarkGroupAsRetrieved(string groupName) diff --git a/src/libraries/System.Data.Common/src/System/Data/DataColumn.cs b/src/libraries/System.Data.Common/src/System/Data/DataColumn.cs index bcbb537791e0e1..f65d56ac5cc227 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataColumn.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataColumn.cs @@ -1158,11 +1158,8 @@ internal object this[int record] { // if and only if it is Expression column, we will cache LastChangedColumn, otherwise DO NOT DataRow dr = GetDataRow(record); - if (dr != null) - { - // at initialization time (datatable.NewRow(), we would fill the storage with default value, but at that time we won't have datarow) - dr.LastChangedColumn = this; - } + // at initialization time (datatable.NewRow(), we would fill the storage with default value, but at that time we won't have datarow) + dr?.LastChangedColumn = this; } } } @@ -1190,10 +1187,8 @@ internal void SetValue(int record, object value) } DataRow dr = GetDataRow(record); - if (dr != null) - { // at initialization time (datatable.NewRow(), we would fill the storage with default value, but at that time we won't have datarow) - dr.LastChangedColumn = this; - } + // at initialization time (datatable.NewRow(), we would fill the storage with default value, but at that time we won't have datarow) + dr?.LastChangedColumn = this; } internal void FreeRecord(int record) @@ -1349,10 +1344,7 @@ public virtual MappingType ColumnMapping if (value == MappingType.SimpleContent) { _columnUri = null; - if (_table != null) - { - _table.XmlText = this; - } + _table?.XmlText = this; SimpleType = null; } } diff --git a/src/libraries/System.Data.Common/src/System/Data/DataColumnCollection.cs b/src/libraries/System.Data.Common/src/System/Data/DataColumnCollection.cs index 5d9b8c4380094c..0fc2d02bb71eb1 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataColumnCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataColumnCollection.cs @@ -824,10 +824,7 @@ internal void RegisterColumnName(string name, DataColumn? column) { _columnFromName.Add(name, column); - if (null != column) - { - column._hashCode = _table.GetSpecialHashCode(name); - } + column?._hashCode = _table.GetSpecialHashCode(name); } catch (ArgumentException) { diff --git a/src/libraries/System.Data.Common/src/System/Data/DataSet.cs b/src/libraries/System.Data.Common/src/System/Data/DataSet.cs index 5ee844a415f8a6..aa283840a1cd4a 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataSet.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataSet.cs @@ -1373,10 +1373,7 @@ internal bool this[int index] } } - if (null != dsNew) - { - dsNew.EnforceConstraints = fEnforceConstraints; - } + dsNew?.EnforceConstraints = fEnforceConstraints; return dsNew; } finally @@ -3575,9 +3572,9 @@ void IXmlSerializable.ReadXml(XmlReader reader) { xmlTextParser.Normalized = fNormalization; } - else if (xmlTextReader != null) + else { - xmlTextReader.Normalization = fNormalization; + xmlTextReader?.Normalization = fNormalization; } } diff --git a/src/libraries/System.Data.Common/src/System/Data/DataTable.cs b/src/libraries/System.Data.Common/src/System/Data/DataTable.cs index 996f52cc479710..49c97189429815 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataTable.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataTable.cs @@ -6757,10 +6757,7 @@ void IXmlSerializable.ReadXml(XmlReader reader) } ReadXmlSerializableInternal(reader); - if (textReader != null) - { - textReader.Normalized = fNormalization; - } + textReader?.Normalized = fNormalization; } [RequiresUnreferencedCode("DataTable.ReadXml uses XmlSerialization underneath which is not trimming safe. Members from serialized types may be trimmed if not referenced directly.")] diff --git a/src/libraries/System.Data.Common/src/System/Data/Merger.cs b/src/libraries/System.Data.Common/src/System/Data/Merger.cs index 500029b89e6983..c60bea2e31584a 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Merger.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Merger.cs @@ -181,10 +181,7 @@ internal void MergeTable(DataTable src) } catch (ConstraintException) { - if (_dataTable.DataSet != null) - { - _dataTable.DataSet.EnforceConstraints = false; - } + _dataTable.DataSet?.EnforceConstraints = false; throw; } } diff --git a/src/libraries/System.Data.Common/src/System/Data/Select.cs b/src/libraries/System.Data.Common/src/System/Data/Select.cs index 1113211bef2693..6c0c440a80ff79 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Select.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Select.cs @@ -370,19 +370,13 @@ private void CreateIndex() if (canColumn == null || canColumn.flag) { // if sort column is not a filter col , or not processed ndxFields[j++] = _indexFields[i]; - if (canColumn != null) - { - canColumn.flag = false; - } + canColumn?.flag = false; } } for (i = 0; i < _candidateColumns.Length; i++) { - if (_candidateColumns[i] != null) - { - _candidateColumns[i].flag = false; // same as before, it is false when it returns - } + _candidateColumns[i]?.flag = false; // same as before, it is false when it returns } // Debug.Assert(j == candidatesNotInIndex, "Whole ndxDesc should be filled!"); @@ -404,8 +398,7 @@ private void CreateIndex() { ndxFields[i] = _indexFields[i]; ColumnInfo canColumn = _candidateColumns[_indexFields[i].Column.Ordinal]; - if (canColumn != null) - canColumn.flag = true; + canColumn?.flag = true; } j = i; for (i = 0; i < lenCanColumns; i++) @@ -441,10 +434,7 @@ private void CreateIndex() } for (i = 0; i < _candidateColumns.Length; i++) { - if (_candidateColumns[i] != null) - { - _candidateColumns[i].flag = false; // same as before, it is false when it returns - } + _candidateColumns[i]?.flag = false; // same as before, it is false when it returns } } } diff --git a/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs b/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs index b5868c6d51af23..208667286d3345 100644 --- a/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs +++ b/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs @@ -278,10 +278,7 @@ internal static void SetProperties(object instance, XmlAttribute[]? attrs) if (name == "DataType") { DataColumn? col = instance as DataColumn; - if (col != null) - { - col.DataType = DataStorage.GetType(value); - } + col?.DataType = DataStorage.GetType(value); continue; } @@ -826,9 +823,8 @@ public void LoadSchema(XmlSchemaSet schemaSet, DataSet ds) } DataTable? tmpTable = ds.Tables[ds.DataSetName, ds.Namespace]; - if (tmpTable != null) // this fix is done to support round-trip problem in case if there is one table with same name and NS - tmpTable._fNestedInDataset = true; - + // this fix is done to support round-trip problem in case if there is one table with same name and NS + tmpTable?._fNestedInDataset = true; // this fix is for backward compatibility with old inference engine if (FromInference && ds.Tables.Count == 0 && string.Equals(ds.DataSetName, "NewDataSet", StringComparison.Ordinal)) @@ -2660,10 +2656,7 @@ internal void HandleDataSet(XmlSchemaElement node, bool isNewDataSet) } DataTable? child = HandleTable((XmlSchemaElement)el); - if (child != null) - { - child._fNestedInDataset = true; - } + child?._fNestedInDataset = true; if (FromInference) { tableSequenceList.Add(child!); @@ -2688,10 +2681,7 @@ internal void HandleDataSet(XmlSchemaElement node, bool isNewDataSet) { tableSequenceList.Add(child); } - if (child != null) - { - child._fNestedInDataset = true; - } + child?._fNestedInDataset = true; } } } diff --git a/src/libraries/System.Data.Common/src/System/Xml/XmlDataDocument.cs b/src/libraries/System.Data.Common/src/System/Xml/XmlDataDocument.cs index 663303a194ed43..9e1db9f04655cc 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/XmlDataDocument.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/XmlDataDocument.cs @@ -1469,8 +1469,7 @@ private void OnColumnValueChanged(DataRow row, DataColumn col, XmlBoundElement r { //make sure that if rowElement has Attribute xsi:nil, its value is false XmlAttribute? attr = rowElement.GetAttributeNode(XSI_NIL); - if (attr != null) - attr.Value = Keywords.FALSE; + attr?.Value = Keywords.FALSE; } ReplaceInitialChildText(rowElement, col.ConvertObjectToXml(value)); goto lblDoNestedRelationSync; @@ -1539,8 +1538,7 @@ private void OnColumnValueChanged(DataRow row, DataColumn col, XmlBoundElement r ReplaceInitialChildText(e, col.ConvertObjectToXml(value)); //make sure that if the Element has Attribute xsi:nil, its value is false XmlAttribute? attr = e.GetAttributeNode(XSI_NIL); - if (attr != null) - attr.Value = Keywords.FALSE; + attr?.Value = Keywords.FALSE; // no need to look any further. goto lblDoNestedRelationSync; } diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcCommand.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcCommand.cs index a0fd1e4ea87b9f..7d796da66d542d 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcCommand.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcCommand.cs @@ -110,10 +110,7 @@ internal void DisconnectFromDataReaderAndConnection() } // remove reference to this from the live datareader - if (liveReader != null) - { - liveReader.Command = null; - } + liveReader?.Command = null; _transaction = null; @@ -510,10 +507,7 @@ private void CloseCommandWrapper() internal void CloseFromConnection() { - if (null != _parameterCollection) - { - _parameterCollection.RebindCollection = true; - } + _parameterCollection?.RebindCollection = true; DisposeDataReader(); CloseCommandWrapper(); _isPrepared = false; diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionFactory.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionFactory.cs index 4b6b3076bb05ff..610bf64457864f 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionFactory.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionFactory.cs @@ -103,10 +103,7 @@ internal override void PermissionDemand(DbConnection outerConnection) internal override void SetConnectionPoolGroup(DbConnection outerConnection, DbConnectionPoolGroup poolGroup) { OdbcConnection? c = (outerConnection as OdbcConnection); - if (null != c) - { - c.PoolGroup = poolGroup; - } + c?.PoolGroup = poolGroup; } internal override void SetInnerConnectionEvent(DbConnection owningObject, DbConnectionInternal to) diff --git a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.cs b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.cs index 4ad3ebc7082bb6..6d5a6e94b60b9c 100644 --- a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.cs +++ b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.cs @@ -162,10 +162,7 @@ internal bool NeedDispose get => _needDispose; set { - if (_ldapHandle != null) - { - _ldapHandle._needDispose = value; - } + _ldapHandle?._needDispose = value; _needDispose = value; } @@ -419,10 +416,7 @@ public void Abort(IAsyncResult asyncResult) LdapPal.CancelDirectoryAsyncOperation(_ldapHandle, messageId); LdapRequestState resultObject = result._resultObject; - if (resultObject != null) - { - resultObject._abortCalled = true; - } + resultObject?._abortCalled = true; } public PartialResultsCollection GetPartialResults(IAsyncResult asyncResult) diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/ExpressionUtils.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/ExpressionUtils.cs index 83be5cf584b926..c41214633c38d6 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/ExpressionUtils.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/ExpressionUtils.cs @@ -120,10 +120,7 @@ public static void ValidateArgumentTypes(MethodBase method, ExpressionType nodeK newArgs[j] = arguments[j]; } } - if (newArgs != null) - { - newArgs[i] = arg; - } + newArgs?[i] = arg; } if (newArgs != null) { diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/StackSpiller.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/StackSpiller.cs index 791d00074e770f..f3d805698765d7 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/StackSpiller.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/StackSpiller.cs @@ -793,10 +793,7 @@ private Result RewriteBlockExpression(Expression expr, Stack stack) clone = Clone(node.Expressions, i); } - if (clone != null) - { - clone[i] = rewritten.Node; - } + clone?[i] = rewritten.Node; } if (action != RewriteAction.None) @@ -902,10 +899,7 @@ private Result RewriteSwitchExpression(Expression expr, Stack stack) cloneTests = Clone(testValues, j); } - if (cloneTests != null) - { - cloneTests[j] = test.Node; - } + cloneTests?[j] = test.Node; } // And all the cases also run on the same stack level. @@ -924,10 +918,7 @@ private Result RewriteSwitchExpression(Expression expr, Stack stack) clone ??= Clone(cases, i); } - if (clone != null) - { - clone[i] = @case; - } + clone?[i] = @case; } // default body also runs on initial stack @@ -989,10 +980,7 @@ private Result RewriteTryExpression(Expression expr, Stack stack) clone ??= Clone(handlers, i); } - if (clone != null) - { - clone[i] = handler; - } + clone?[i] = handler; } } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/IndexExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/IndexExpression.cs index 1d5c8c79398e2c..ff5f77f3354803 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/IndexExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/IndexExpression.cs @@ -520,10 +520,7 @@ private static void ValidateAccessorArgumentTypes(MethodInfo method, ParameterIn newArgs[j] = arguments[j]; } } - if (newArgs != null) - { - newArgs[i] = arg; - } + newArgs?[i] = arg; } if (newArgs != null) { diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/NewArrayExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/NewArrayExpression.cs index 05f97c0f15ad3f..f8f14f3d5cf339 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/NewArrayExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/NewArrayExpression.cs @@ -165,10 +165,7 @@ public static NewArrayExpression NewArrayInit(Type type, IEnumerable } } } - if (newList != null) - { - newList[i] = expr; - } + newList?[i] = expr; } if (newList != null) { diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/NewExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/NewExpression.cs index eecc82942c59ed..1b376e29879000 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/NewExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/NewExpression.cs @@ -272,10 +272,7 @@ private static void ValidateNewArgs(ConstructorInfo constructor, ref ReadOnlyCol newArguments[j] = arguments[j]; } } - if (newArguments != null) - { - newArguments[i] = arg; - } + newArguments?[i] = arg; if (newMembers == null && member != members[i]) { @@ -285,10 +282,7 @@ private static void ValidateNewArgs(ConstructorInfo constructor, ref ReadOnlyCol newMembers[j] = members[j]; } } - if (newMembers != null) - { - newMembers[i] = member; - } + newMembers?[i] = member; } if (newArguments != null) { diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpMethod.SocketsHttpHandler.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpMethod.SocketsHttpHandler.cs index c833d1e4da7148..6ee6bc7b7d1eda 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpMethod.SocketsHttpHandler.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpMethod.SocketsHttpHandler.cs @@ -60,10 +60,7 @@ private byte[] CreateHttp1EncodedBytes() Ascii.FromUtf16(method, bytes, out _); bytes[^1] = (byte)' '; - if (knownMethod is not null) - { - knownMethod._http1EncodedBytes = bytes; - } + knownMethod?._http1EncodedBytes = bytes; } _http1EncodedBytes = bytes; @@ -84,10 +81,7 @@ private byte[] CreateHttp2EncodedBytes() _ => HPackEncoder.EncodeLiteralHeaderFieldWithoutIndexingToAllocatedArray(H2StaticTable.MethodGet, knownMethod?.Method ?? Method) }; - if (knownMethod is not null) - { - knownMethod._http2EncodedBytes = bytes; - } + knownMethod?._http2EncodedBytes = bytes; } _http2EncodedBytes = bytes; @@ -105,10 +99,7 @@ private byte[] CreateHttp3EncodedBytes() ? QPackEncoder.EncodeStaticIndexedHeaderFieldToArray(_http3Index) : QPackEncoder.EncodeLiteralHeaderFieldWithStaticNameReferenceToArray(H3StaticTable.MethodGet, knownMethod?.Method ?? Method); - if (knownMethod is not null) - { - knownMethod._http3EncodedBytes = bytes; - } + knownMethod?._http3EncodedBytes = bytes; } _http3EncodedBytes = bytes; diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ConnectionPool/ConnectionSetupDistributedTracing.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ConnectionPool/ConnectionSetupDistributedTracing.cs index 3a65389d20e045..dd82b0831b735b 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ConnectionPool/ConnectionSetupDistributedTracing.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ConnectionPool/ConnectionSetupDistributedTracing.cs @@ -73,10 +73,7 @@ public static void ReportError(Activity? activity, Exception exception) public static Activity? StartWaitForConnectionActivity(HttpAuthority authority) { Activity? activity = s_connectionsActivitySource.StartActivity(DiagnosticsHandlerLoggingStrings.WaitForConnectionActivityName); - if (activity is not null) - { - activity.DisplayName = $"HTTP wait_for_connection {authority.HostValue}:{authority.Port}"; - } + activity?.DisplayName = $"HTTP wait_for_connection {authority.HostValue}:{authority.Port}"; return activity; } diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/TCPClient.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/TCPClient.cs index 41d54eba71d1c2..f14995e9af76e1 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/TCPClient.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/TCPClient.cs @@ -113,10 +113,7 @@ public bool ExclusiveAddressUse get { return Client?.ExclusiveAddressUse ?? false; } set { - if (_clientSocket != null) - { - _clientSocket.ExclusiveAddressUse = value; - } + _clientSocket?.ExclusiveAddressUse = value; } } diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/TCPListener.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/TCPListener.cs index 647bed93739da8..e394006587f20f 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/TCPListener.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/TCPListener.cs @@ -100,10 +100,7 @@ public bool ExclusiveAddressUse throw new InvalidOperationException(SR.net_tcplistener_mustbestopped); } - if (_serverSocket != null) - { - _serverSocket.ExclusiveAddressUse = value; - } + _serverSocket?.ExclusiveAddressUse = value; _exclusiveAddressUse = value; } } diff --git a/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/ClientWebSocket.cs b/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/ClientWebSocket.cs index 37b5565b74675e..692e03103e1c6b 100644 --- a/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/ClientWebSocket.cs +++ b/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/ClientWebSocket.cs @@ -66,10 +66,7 @@ public IReadOnlyDictionary>? HttpResponseHeaders get => _innerWebSocket?.HttpResponseHeaders; set { - if (_innerWebSocket != null) - { - _innerWebSocket.HttpResponseHeaders = value; - } + _innerWebSocket?.HttpResponseHeaders = value; } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Array.cs b/src/libraries/System.Private.CoreLib/src/System/Array.cs index a98f5b0256c122..5ff7790fad3ae0 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Array.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Array.cs @@ -2807,13 +2807,11 @@ private void DownHeap(int i, int n, int lo) if (!(comparer.Compare(d, keys[lo + child - 1]) < 0)) break; keys[lo + i - 1] = keys[lo + child - 1]; - if (items != null) - items[lo + i - 1] = items[lo + child - 1]; + items?[lo + i - 1] = items[lo + child - 1]; i = child; } keys[lo + i - 1] = d; - if (items != null) - items[lo + i - 1] = dt; + items?[lo + i - 1] = dt; } private void InsertionSort(int lo, int hi) @@ -2829,13 +2827,11 @@ private void InsertionSort(int lo, int hi) while (j >= lo && comparer.Compare(t, keys[j]) < 0) { keys[j + 1] = keys[j]; - if (items != null) - items[j + 1] = items[j]; + items?[j + 1] = items[j]; j--; } keys[j + 1] = t; - if (items != null) - items[j + 1] = ti; + items?[j + 1] = ti; } } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/FieldMetadata.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/FieldMetadata.cs index bc6bf4fd066ff9..925044259b962d 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/FieldMetadata.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/FieldMetadata.cs @@ -173,19 +173,13 @@ public void Encode(ref int pos, byte[]? metadata) pos += this.nameSize; // Write 1 byte for inType - if (metadata != null) - { - metadata[pos] = this.inType; - } + metadata?[pos] = this.inType; pos++; // If InTypeChainFlag set, then write out the outType if (0 != (this.inType & Statics.InTypeChainFlag)) { - if (metadata != null) - { - metadata[pos] = this.outType; - } + metadata?[pos] = this.outType; pos++; // If OutTypeChainFlag set, then write out tags diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/Statics.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/Statics.cs index ecd470dac69bb9..70f7c34b3a2380 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/Statics.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/Statics.cs @@ -116,10 +116,7 @@ public static void EncodeTags(int tags, ref int pos, byte[]? metadata) current |= (byte)(more ? 0x80 : 0x00); tagsLeft <<= 7; - if (metadata != null) - { - metadata[pos] = current; - } + metadata?[pos] = current; pos++; } while (more); diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/CancellationTokenSource.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/CancellationTokenSource.cs index 7ea36b67c970be..cf81e05824d457 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/CancellationTokenSource.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/CancellationTokenSource.cs @@ -632,10 +632,7 @@ internal CancellationTokenRegistration Register( node.SynchronizationContext = syncContext; node.Next = registrations.Callbacks; registrations.Callbacks = node; - if (node.Next != null) - { - node.Next.Prev = node; - } + node.Next?.Prev = node; } } finally @@ -663,10 +660,7 @@ internal CancellationTokenRegistration Register( { node.Id = id = registrations.NextAvailableId++; node.Next = registrations.Callbacks; - if (node.Next != null) - { - node.Next.Prev = node; - } + node.Next?.Prev = node; registrations.Callbacks = node; } finally @@ -773,10 +767,7 @@ private void ExecuteCallbackHandlers(bool throwOnFirstException) Debug.Assert(node.Registrations.Source == this); Debug.Assert(node.Prev == null); - if (node.Next != null) - { - node.Next.Prev = null; - } + node.Next?.Prev = null; registrations.Callbacks = node.Next; // Publish the intended callback ID, to ensure ctr.Dispose can tell if a wait is necessary. @@ -1094,10 +1085,7 @@ public bool Unregister(long id, CallbackNode node) node.Prev.Next = node.Next; } - if (node.Next != null) - { - node.Next.Prev = node.Prev; - } + node.Next?.Prev = node.Prev; Recycle(node); diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/SemaphoreSlim.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/SemaphoreSlim.cs index bae72e8311816b..a208ee4a1f610c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/SemaphoreSlim.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/SemaphoreSlim.cs @@ -756,8 +756,8 @@ private bool RemoveAsyncWaiter(TaskNode task) bool wasInList = m_asyncHead == task || task.Prev is not null; // Remove it from the linked list - if (task.Next is not null) task.Next.Prev = task.Prev; - if (task.Prev is not null) task.Prev.Next = task.Next; + task.Next?.Prev = task.Prev; + task.Prev?.Next = task.Next; if (m_asyncHead == task) m_asyncHead = task.Next; if (m_asyncTail == task) m_asyncTail = task.Prev; Debug.Assert((m_asyncHead is null) == (m_asyncTail is null), "Head is null iff tail is null"); diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadLocal.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadLocal.cs index a67c7325ae983f..26404af8d42e3d 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadLocal.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadLocal.cs @@ -402,10 +402,7 @@ private void CreateLinkedSlot(LinkedSlotVolatile[] slotArray, int id, T value) linkedSlot._previous = _linkedSlot; linkedSlot._value = value; - if (firstRealNode != null) - { - firstRealNode._previous = linkedSlot; - } + firstRealNode?._previous = linkedSlot; _linkedSlot._next = linkedSlot; // Assigning the slot under a lock prevents a race condition with Dispose (dispose also acquires the lock). @@ -742,10 +739,7 @@ internal FinalizationHelper(LinkedSlotVolatile[] slotArray) idsThatDoNotTrackAllValuesCountRemaining--; } - if (linkedSlot._next != null) - { - linkedSlot._next._previous = linkedSlot._previous; - } + linkedSlot._next?._previous = linkedSlot._previous; // Since the list uses a dummy head node, the Previous reference should never be null. Debug.Assert(linkedSlot._previous != null); diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Timer.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Timer.cs index 46636426768513..c9747d2cbdec55 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Timer.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Timer.cs @@ -387,10 +387,7 @@ private void LinkTimer(TimerQueueTimer timer) // Use timer._short to decide to which list to add. ref TimerQueueTimer? listHead = ref timer._short ? ref _shortTimers : ref _longTimers; timer._next = listHead; - if (timer._next != null) - { - timer._next._prev = timer; - } + timer._next?._prev = timer; timer._prev = null; listHead = timer; } @@ -398,10 +395,7 @@ private void LinkTimer(TimerQueueTimer timer) private void UnlinkTimer(TimerQueueTimer timer) { TimerQueueTimer? t = timer._next; - if (t != null) - { - t._prev = timer._prev; - } + t?._prev = timer._prev; if (_shortTimers == timer) { @@ -415,10 +409,7 @@ private void UnlinkTimer(TimerQueueTimer timer) } t = timer._prev; - if (t != null) - { - t._next = timer._next; - } + t?._next = timer._next; // At this point the timer is no longer in a list, but its next and prev // references may still point to other nodes. UnlinkTimer should thus be diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaExporter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaExporter.cs index 3733783c3b3800..86a826e88108d3 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaExporter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaExporter.cs @@ -536,15 +536,12 @@ private void ExportXmlDataContract(XmlDataContract dataContract) { throw new InvalidDataContractException(SR.Format(SR.MissingSchemaType, typeQName, DataContract.GetClrTypeFullName(clrType))); } - if (xsdType != null) - { - xsdType.Annotation = GetSchemaAnnotation( - ExportSurrogateData(dataContract), - dataContract.IsValueType ? - GetAnnotationMarkup(IsValueTypeName, XmlConvert.ToString(dataContract.IsValueType), schema!) : - null - ); - } + xsdType?.Annotation = GetSchemaAnnotation( + ExportSurrogateData(dataContract), + dataContract.IsValueType ? + GetAnnotationMarkup(IsValueTypeName, XmlConvert.ToString(dataContract.IsValueType), schema!) : + null + ); } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEncodedRawTextWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEncodedRawTextWriter.cs index d583927b3f86b6..775a21509661ca 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEncodedRawTextWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEncodedRawTextWriter.cs @@ -850,10 +850,7 @@ private void EncodeChars(int startOffset, int endOffset, bool writeAllToStream) int bEnc; while (startOffset < endOffset) { - if (_charEntityFallback != null) - { - _charEntityFallback.StartOffset = startOffset; - } + _charEntityFallback?.StartOffset = startOffset; _encoder!.Convert(_bufChars, startOffset, endOffset - startOffset, _bufBytes!, _bufBytesUsed, _bufBytes!.Length - _bufBytesUsed, false, out chEnc, out bEnc, out _); startOffset += chEnc; _bufBytesUsed += bEnc; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEncodedRawTextWriterAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEncodedRawTextWriterAsync.cs index 8e1969ee573514..a29e9812de9b4e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEncodedRawTextWriterAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEncodedRawTextWriterAsync.cs @@ -682,10 +682,7 @@ private async Task EncodeCharsAsync(int startOffset, int endOffset, bool writeAl int bEnc; while (startOffset < endOffset) { - if (_charEntityFallback != null) - { - _charEntityFallback.StartOffset = startOffset; - } + _charEntityFallback?.StartOffset = startOffset; _encoder!.Convert(_bufChars, startOffset, endOffset - startOffset, _bufBytes!, _bufBytesUsed, _bufBytes!.Length - _bufBytesUsed, false, out chEnc, out bEnc, out _); startOffset += chEnc; _bufBytesUsed += bEnc; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriter.cs index da153709c854bd..ce2c6690ea3e73 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriter.cs @@ -245,10 +245,7 @@ internal XmlWellFormedWriter(XmlWriter writer, XmlWriterSettings settings) _rawWriter = writer as XmlRawWriter; _predefinedNamespaces = writer as IXmlNamespaceResolver; - if (_rawWriter != null) - { - _rawWriter.NamespaceResolver = new NamespaceResolverProxy(this); - } + _rawWriter?.NamespaceResolver = new NamespaceResolverProxy(this); _checkCharacters = settings.CheckCharacters; _omitDuplNamespaces = (settings.NamespaceHandling & NamespaceHandling.OmitDuplicates) != 0; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocument.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocument.cs index c53b6a7b25be82..48e9d169054e15 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocument.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocument.cs @@ -452,10 +452,7 @@ public virtual XmlResolver? XmlResolver bSetResolver = true; XmlDocumentType? dtd = this.DocumentType; - if (dtd != null) - { - dtd.DtdSchemaInfo = null; - } + dtd?.DtdSchemaInfo = null; } } internal override bool IsValidChildType(XmlNodeType type) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlLoader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlLoader.cs index 4fa22f323b094d..bd5ea77bfddd9f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlLoader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlLoader.cs @@ -151,10 +151,7 @@ private void LoadDocSequence(XmlDocument parentDoc) if (schemaInfo != null) { element = parent as XmlElement; - if (element != null) - { - element.XmlName = _doc!.AddXmlName(element.Prefix, element.LocalName, element.NamespaceURI, schemaInfo); - } + element?.XmlName = _doc!.AddXmlName(element.Prefix, element.LocalName, element.NamespaceURI, schemaInfo); } if (parent.ParentNode == null) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Resolvers/XmlPreloadedResolver.cs b/src/libraries/System.Private.Xml/src/System/Xml/Resolvers/XmlPreloadedResolver.cs index 6dc4f5e00dff44..1756485ad05b12 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Resolvers/XmlPreloadedResolver.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Resolvers/XmlPreloadedResolver.cs @@ -255,10 +255,7 @@ public override ICredentials Credentials { set { - if (_fallbackResolver != null) - { - _fallbackResolver.Credentials = value; - } + _fallbackResolver?.Credentials = value; } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Asttree.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Asttree.cs index 09c98d1dcd2eab..60656df5338b4e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Asttree.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Asttree.cs @@ -421,10 +421,7 @@ internal DoubleLinkAxis(Axis axis, DoubleLinkAxis? inputaxis) this.next = null; this.Urn = axis.Urn; this.abbrAxis = axis.AbbrAxis; - if (inputaxis != null) - { - inputaxis.Next = this; - } + inputaxis?.Next = this; } // recursive here diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionpreProcessor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionpreProcessor.cs index 971f7b5280633d..e98111ca67e5ce 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionpreProcessor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionpreProcessor.cs @@ -71,10 +71,7 @@ public bool Execute(XmlSchema schema, string? targetNamespace, bool loadExternal for (int i = 0; i < schema.Includes.Count; ++i) { XmlSchemaExternal include = (XmlSchemaExternal)schema.Includes[i]; - if (include.Schema != null) - { - include.Schema.IsPreprocessed = true; - } + include.Schema?.IsPreprocessed = true; } } return !HasErrors; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidator.cs index 85b63ed663fec5..81ccdd1ac1d75f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidator.cs @@ -716,10 +716,8 @@ public void ValidateEndOfAttributes(XmlSchemaInfo? schemaInfo) _context.CheckRequiredAttribute = false; CheckRequiredAttributes(currentElementDecl); } - if (schemaInfo != null) - { //set validity depending on whether all required attributes were validated successfully - schemaInfo.Validity = _context.Validity; - } + //set validity depending on whether all required attributes were validated successfully + schemaInfo?.Validity = _context.Validity; } public void ValidateText(string elementValue) @@ -2084,10 +2082,7 @@ private void CheckStateTransition(ValidatorState toState, string methodName) private void ClearPSVI() { - if (_textValue != null) - { - _textValue.Length = 0; - } + _textValue?.Length = 0; _attPresence.Clear(); //Clear attributes hashtable for every element _wildID = null; //clear it for every element diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs index 05f91cbce20e19..74f21b5657dc3b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs @@ -427,8 +427,7 @@ private XmlQualifiedName ExportNonXsdPrimitiveMapping(PrimitiveMapping mapping, } seq.Items.Add(any); type.Particle = seq; - if (element != null) - element.SchemaType = type; + element?.SchemaType = type; return type; } case TypeKind.Serializable: @@ -463,8 +462,7 @@ private XmlQualifiedName ExportNonXsdPrimitiveMapping(PrimitiveMapping mapping, } seq.Items.Add(any); type.Particle = seq; - if (element != null) - element.SchemaType = type; + element?.SchemaType = type; return type; } else if (serializableMapping.XsiType != null || serializableMapping.XsdType != null) @@ -510,8 +508,7 @@ private XmlQualifiedName ExportNonXsdPrimitiveMapping(PrimitiveMapping mapping, { throw new InvalidOperationException(SR.Format(SR.XmlDuplicateNamespace, anyNs)); } - if (element != null) - element.SchemaType = type; + element?.SchemaType = type; // check for duplicate top-level elements XmlAttributes serializableMapping.CheckDuplicateElement(element, ns); @@ -528,8 +525,7 @@ private XmlQualifiedName ExportNonXsdPrimitiveMapping(PrimitiveMapping mapping, seq.Items.Add(new XmlSchemaAny()); type.Particle = seq; AddSchemaImport(XmlSchema.Namespace, ns); - if (element != null) - element.SchemaType = type; + element?.SchemaType = type; return type; } } @@ -1022,14 +1018,13 @@ private XmlQualifiedName ExportStructMapping(StructMapping mapping, string? ns, if (mapping.IsAnonymousType) { _references[mapping] = null; - if (element != null) - element.SchemaType = type; + element?.SchemaType = type; return XmlQualifiedName.Empty; } else { XmlQualifiedName qname = new XmlQualifiedName(type.Name, mapping.Namespace); - if (element != null) element.SchemaTypeName = qname; + element?.SchemaTypeName = qname; return qname; } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlAttributeCache.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlAttributeCache.cs index 381e386ea73b85..41a3a972e6791d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlAttributeCache.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlAttributeCache.cs @@ -66,8 +66,7 @@ private void SetWrappedWriter(XmlRawWriter? writer) { // If new writer might remove itself from pipeline, have it callback on this method when its ready to go IRemovableWriter? removable = writer as IRemovableWriter; - if (removable != null) - removable.OnRemoveWriterEvent = SetWrappedWriter; + removable?.OnRemoveWriterEvent = SetWrappedWriter; _wrapped = writer; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryOutput.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryOutput.cs index 3c62109ce05481..64bc683fe941e7 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryOutput.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryOutput.cs @@ -96,8 +96,7 @@ internal XmlRawWriter? Writer { // If new writer might remove itself from pipeline, have it callback on this method when it's ready to go IRemovableWriter? removable = value as IRemovableWriter; - if (removable != null) - removable.OnRemoveWriterEvent = SetWrappedWriter; + removable?.OnRemoveWriterEvent = SetWrappedWriter; _xwrt = value; } diff --git a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCacheStore.cs b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCacheStore.cs index 24a9821a75c88e..f826063e801dba 100644 --- a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCacheStore.cs +++ b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCacheStore.cs @@ -342,10 +342,7 @@ internal void Set(MemoryCacheKey key, MemoryCacheEntry entry) if (_disposed == 0) { existingEntry = _entries[key] as MemoryCacheEntry; - if (existingEntry != null) - { - existingEntry.State = EntryState.RemovingFromCache; - } + existingEntry?.State = EntryState.RemovingFromCache; entry.State = EntryState.AddingToCache; added = true; _entries[key] = entry; diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectReader.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectReader.cs index 9f8f1a389409cc..74350287d5a20f 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectReader.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectReader.cs @@ -57,10 +57,7 @@ internal object? TopObject set { _topObject = value; - if (_objectManager != null) - { - _objectManager.TopObject = value; - } + _objectManager?.TopObject = value; } } diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/SBCSCodePageEncoding.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/SBCSCodePageEncoding.cs index 5fda8e1215bf37..de62ed27628870 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/SBCSCodePageEncoding.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/SBCSCodePageEncoding.cs @@ -811,8 +811,7 @@ public override unsafe int GetChars(byte* bytes, int byteCount, } // bytes & chars used are the same - if (decoder != null) - decoder.m_bytesUsed = (int)(bytes - byteStart); + decoder?.m_bytesUsed = (int)(bytes - byteStart); return (int)(chars - charStart); } @@ -879,8 +878,7 @@ public override unsafe int GetChars(byte* bytes, int byteCount, } // Might have had decoder fallback stuff. - if (decoder != null) - decoder.m_bytesUsed = (int)(bytes - byteStart); + decoder?.m_bytesUsed = (int)(bytes - byteStart); // Expect Empty fallback buffer for GetChars Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonArray.IList.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonArray.IList.cs index 7ffe4e7b56644c..f44acc03a016f8 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonArray.IList.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonArray.IList.cs @@ -230,10 +230,7 @@ public void RemoveRange(int index, int count) private static void DetachParent(JsonNode? item) { - if (item != null) - { - item.Parent = null; - } + item?.Parent = null; } } } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.IDictionary.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.IDictionary.cs index f86362c9eea2ca..dab36e4ed3ce92 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.IDictionary.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.IDictionary.cs @@ -257,10 +257,7 @@ public bool Remove(string propertyName) foreach (JsonProperty jElementProperty in jsonElement.Value.EnumerateObject()) { JsonNode? node = JsonNodeConverter.Create(jElementProperty.Value, Options); - if (node != null) - { - node.Parent = this; - } + node?.Parent = this; dictionary.Add(jElementProperty.Name, node); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.cs index be00902ce449f4..9cfe0b8cb8fc86 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.cs @@ -296,10 +296,7 @@ private void DetachParent(JsonNode? item) { Debug.Assert(_dictionary != null, "Cannot have detachable nodes without a materialized dictionary."); - if (item != null) - { - item.Parent = null; - } + item?.Parent = null; } private KeyValuePair? FindValue(JsonNode? value) diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.cs index 00f913e068ee38..9af7bd341bbc19 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.cs @@ -1159,10 +1159,7 @@ protected override void OnCollectionModified() { // Collection modified by the user: replace the main // resolver with the resolver chain as our source of truth. - if (_options is not null) - { - _options._typeInfoResolver = this; - } + _options?._typeInfoResolver = this; } } diff --git a/src/libraries/System.Threading.Tasks.Parallel/src/System/Threading/Tasks/Parallel.cs b/src/libraries/System.Threading.Tasks.Parallel/src/System/Threading/Tasks/Parallel.cs index eadc4bc1ba659f..6d986051ebb508 100644 --- a/src/libraries/System.Threading.Tasks.Parallel/src/System/Threading/Tasks/Parallel.cs +++ b/src/libraries/System.Threading.Tasks.Parallel/src/System/Threading/Tasks/Parallel.cs @@ -2649,7 +2649,7 @@ private static ParallelLoopResult PartitionerForEachWorker( TSource value = kvp.Value; // Update our iteration index - if (state != null) state.CurrentIteration = index; + state?.CurrentIteration = index; if (simpleBody != null) simpleBody(value); @@ -2689,8 +2689,7 @@ private static ParallelLoopResult PartitionerForEachWorker( throw new InvalidOperationException(SR.Parallel_ForEach_NullEnumerator); // I'm not going to try to maintain this - if (state != null) - state.CurrentIteration = 0; + state?.CurrentIteration = 0; while (myPartition.MoveNext()) { diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionState.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionState.cs index d3c7b8ee2b9555..8f4a6803181977 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionState.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionState.cs @@ -2577,11 +2577,8 @@ internal override void EnterState(InternalTransaction tx) { CommonEnterState(tx); - if (tx._committableTransaction != null) - { - // If we have a committable transaction then mark it as complete. - tx._committableTransaction._complete = true; - } + // If we have a committable transaction then mark it as complete. + tx._committableTransaction?._complete = true; // If at this point there are phase1 dependent clones abort the transaction if (tx._phase1Volatiles._dependentClones != 0) diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionTable.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionTable.cs index da3445133f006f..c12809c5f99203 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionTable.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionTable.cs @@ -339,12 +339,9 @@ private void AddIter(InternalTransaction txNew) if (oldNextSetWeak != null) { BucketSet? oldSet = (BucketSet?)oldNextSetWeak.Target; - if (oldSet != null) - { - // prev references are just there to root things for the GC. If this object is - // gone we don't really care. - oldSet.prevSet = newBucketSet; - } + // prev references are just there to root things for the GC. If this object is + // gone we don't really care. + oldSet?.prevSet = newBucketSet; } newBucketSet.prevSet = lastBucketSet; } diff --git a/src/tools/illink/src/linker/Linker/DynamicDependency.cs b/src/tools/illink/src/linker/Linker/DynamicDependency.cs index 8bf34c9f446877..7eccf3daca3b7f 100644 --- a/src/tools/illink/src/linker/Linker/DynamicDependency.cs +++ b/src/tools/illink/src/linker/Linker/DynamicDependency.cs @@ -105,8 +105,7 @@ public DynamicDependency(DynamicallyAccessedMemberTypes memberTypes, string type _ => null, }; - if (result != null) - result.OriginalAttribute = ca; + result?.OriginalAttribute = ca; return result; } From 6dac8bbe48265e528e76ac185d59cce82a8c0f9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20K=C3=B6plinger?= Date: Mon, 15 Sep 2025 20:23:23 +0200 Subject: [PATCH 5/7] Don't set severity for dotnet_style_null_propagation So the value in eng/CodeAnalysis.src.globalconfig takes precedence --- .editorconfig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.editorconfig b/.editorconfig index 51a96c1b2781ba..6150b854a44879 100644 --- a/.editorconfig +++ b/.editorconfig @@ -99,7 +99,7 @@ dotnet_style_collection_initializer = true:suggestion dotnet_style_prefer_collection_expression = when_types_exactly_match dotnet_style_explicit_tuple_names = true:suggestion dotnet_style_coalesce_expression = true:suggestion -dotnet_style_null_propagation = true:suggestion +dotnet_style_null_propagation = true dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion dotnet_style_prefer_inferred_tuple_names = true:suggestion dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion From 3fb4ac6a60687572270fabf714386f7aa421a2d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20K=C3=B6plinger?= Date: Mon, 15 Sep 2025 21:33:49 +0200 Subject: [PATCH 6/7] Fix more IDE0031 --- .../src/System/Threading/Condition.cs | 3 +-- ...ronment.ConstructedGenericsRegistration.cs | 9 +++---- .../InteropServices/ComEventsMethod.cs | 5 +--- .../Runtime/InteropServices/ComEventsSink.cs | 5 +--- .../System.Data.OleDb/src/DbBindings.cs | 10 ++------ .../System.Data.OleDb/src/OleDbConnection.cs | 5 +--- .../src/OleDbConnectionFactory.cs | 5 +--- .../System.Data.OleDb/src/OleDbDataReader.cs | 6 ++--- .../System.Data.OleDb/src/OleDbTransaction.cs | 4 +-- .../Net/Windows/HttpListener.Windows.cs | 5 +--- .../src/System/Threading/NamedMutex.Unix.cs | 5 +--- .../System.Speech/src/Internal/RBList.cs | 25 ++++--------------- .../src/Internal/SrgsCompiler/State.cs | 10 ++------ .../src/Internal/Synthesis/VoiceSynthesis.cs | 5 +--- .../Emit/RuntimeFieldBuilder.Mono.cs | 3 +-- src/tasks/WasmAppBuilder/WasmAppBuilder.cs | 3 +-- 16 files changed, 26 insertions(+), 82 deletions(-) diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/Condition.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/Condition.cs index 2321c5bafe14b7..62092167090942 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/Condition.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/Condition.cs @@ -62,8 +62,7 @@ private unsafe void AddWaiter(Waiter waiter) AssertIsNotInList(waiter); waiter.prev = _waitersTail; - if (waiter.prev != null) - waiter.prev.next = waiter; + waiter.prev?.next = waiter; _waitersTail = waiter; diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.ConstructedGenericsRegistration.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.ConstructedGenericsRegistration.cs index 72c65865ff2afe..69c8d772d4f613 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.ConstructedGenericsRegistration.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.ConstructedGenericsRegistration.cs @@ -102,19 +102,16 @@ internal void RegisterDynamicGenericTypesAndMethods(DynamicGenericsRegistrationD var typeEntry = registeredTypes[i]; // There is no Remove feature in the LockFreeReaderHashtable... GenericTypeEntry failedEntry = _dynamicGenericTypes.GetValueIfExists(typeEntry); - if (failedEntry != null) - failedEntry._isRegisteredSuccessfully = false; + failedEntry?._isRegisteredSuccessfully = false; } for (int i = 0; i < registeredMethodsCount; i++) { // There is no Remove feature in the LockFreeReaderHashtable... GenericMethodEntry failedEntry = _dynamicGenericMethods.GetValueIfExists(registeredMethods[i]); - if (failedEntry != null) - failedEntry._isRegisteredSuccessfully = false; + failedEntry?._isRegisteredSuccessfully = false; failedEntry = _dynamicGenericMethodComponents.GetValueIfExists(registeredMethods[i]); - if (failedEntry != null) - failedEntry._isRegisteredSuccessfully = false; + failedEntry?._isRegisteredSuccessfully = false; } } catch (Exception e) diff --git a/src/libraries/Common/src/System/Runtime/InteropServices/ComEventsMethod.cs b/src/libraries/Common/src/System/Runtime/InteropServices/ComEventsMethod.cs index 7f965abcea769a..5cef837b927c73 100644 --- a/src/libraries/Common/src/System/Runtime/InteropServices/ComEventsMethod.cs +++ b/src/libraries/Common/src/System/Runtime/InteropServices/ComEventsMethod.cs @@ -144,10 +144,7 @@ public static ComEventsMethod Add(ComEventsMethod? methods, ComEventsMethod meth current = current._next; } - if (current != null) - { - current._next = method._next; - } + current?._next = method._next; return methods; } diff --git a/src/libraries/Common/src/System/Runtime/InteropServices/ComEventsSink.cs b/src/libraries/Common/src/System/Runtime/InteropServices/ComEventsSink.cs index 5155bea123ce01..ff804a6f9fae0d 100644 --- a/src/libraries/Common/src/System/Runtime/InteropServices/ComEventsSink.cs +++ b/src/libraries/Common/src/System/Runtime/InteropServices/ComEventsSink.cs @@ -73,10 +73,7 @@ public static ComEventsSink Add(ComEventsSink? sinks, ComEventsSink sink) current = current._next; } - if (current != null) - { - current._next = sink._next; - } + current?._next = sink._next; } sink.Unadvise(); diff --git a/src/libraries/System.Data.OleDb/src/DbBindings.cs b/src/libraries/System.Data.OleDb/src/DbBindings.cs index 2575cfd46761c1..a0672d1a7b4118 100644 --- a/src/libraries/System.Data.OleDb/src/DbBindings.cs +++ b/src/libraries/System.Data.OleDb/src/DbBindings.cs @@ -222,10 +222,7 @@ internal byte Precision #endif set { - if (null != _bindInfo) - { - _bindInfo[_index].bPrecision = value; - } + _bindInfo?[_index].bPrecision = value; _dbbindings[_index].bPrecision = value; _dbcolumns[_index].bPrecision = value; } @@ -237,10 +234,7 @@ internal byte Scale #endif set { - if (null != _bindInfo) - { - _bindInfo[_index].bScale = value; - } + _bindInfo?[_index].bScale = value; _dbbindings[_index].bScale = value; _dbcolumns[_index].bScale = value; } diff --git a/src/libraries/System.Data.OleDb/src/OleDbConnection.cs b/src/libraries/System.Data.OleDb/src/OleDbConnection.cs index 686aa0ee323308..08a73afefc7ab7 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbConnection.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbConnection.cs @@ -163,10 +163,7 @@ internal OleDbTransaction? LocalTransaction { OleDbConnectionInternal openConnection = GetOpenConnection(); - if (null != openConnection) - { - openConnection.LocalTransaction = value; - } + openConnection?.LocalTransaction = value; } } diff --git a/src/libraries/System.Data.OleDb/src/OleDbConnectionFactory.cs b/src/libraries/System.Data.OleDb/src/OleDbConnectionFactory.cs index ea4f81c99203c3..8261357fa1820c 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbConnectionFactory.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbConnectionFactory.cs @@ -133,10 +133,7 @@ internal override void PermissionDemand(DbConnection outerConnection) internal override void SetConnectionPoolGroup(DbConnection outerConnection, DbConnectionPoolGroup poolGroup) { OleDbConnection? c = (outerConnection as OleDbConnection); - if (null != c) - { - c.PoolGroup = poolGroup; - } + c?.PoolGroup = poolGroup; } internal override void SetInnerConnectionEvent(DbConnection owningObject, DbConnectionInternal to) diff --git a/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs b/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs index 5aed9b32222f6f..59662e12c00ec8 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs @@ -723,10 +723,8 @@ internal void CloseReaderFromConnection(bool canceling) // being called from the connection, we will have a command. that command // may be Disposed, but it doesn't matter since another command can't execute // until all DataReader are closed - if (null != _command) - { // UNDONE: understand why this could be null, it shouldn't be but was - _command.canceling = canceling; - } + // UNDONE: understand why this could be null, it shouldn't be but was + _command?.canceling = canceling; // called from the connection which will remove this from its ReferenceCollection // we want the NextResult behavior, but no errors diff --git a/src/libraries/System.Data.OleDb/src/OleDbTransaction.cs b/src/libraries/System.Data.OleDb/src/OleDbTransaction.cs index 3099e82752447f..2d5f1d999d3caa 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbTransaction.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbTransaction.cs @@ -288,9 +288,9 @@ private void DisposeManaged() _parentTransaction._nestedTransaction = null; //_parentTransaction = null; } - else if (null != _parentConnection) + else { - _parentConnection.LocalTransaction = null; + _parentConnection?.LocalTransaction = null; } _parentConnection = null!; } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs index 394307721541f3..5e0e6b4648a899 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs @@ -722,10 +722,7 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) { // They sent an authorization - destroy their previous credentials. if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "Clearing principal cache"); - if (disconnectResult != null) - { - disconnectResult.AuthenticatedConnection = null; - } + disconnectResult?.AuthenticatedConnection = null; } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/NamedMutex.Unix.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/NamedMutex.Unix.cs index c359770f19b59d..59b0738abc31ae 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/NamedMutex.Unix.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/NamedMutex.Unix.cs @@ -36,10 +36,7 @@ public void Remove(NamedMutexProcessDataBase namedMutex) previous = previous?.NextOwnedNamedMutex; } - if (previous is not null) - { - previous.NextOwnedNamedMutex = namedMutex.NextOwnedNamedMutex; - } + previous?.NextOwnedNamedMutex = namedMutex.NextOwnedNamedMutex; } namedMutex.NextOwnedNamedMutex = null; diff --git a/src/libraries/System.Speech/src/Internal/RBList.cs b/src/libraries/System.Speech/src/Internal/RBList.cs index faed7c8a397cfc..7de38896ead9dc 100644 --- a/src/libraries/System.Speech/src/Internal/RBList.cs +++ b/src/libraries/System.Speech/src/Internal/RBList.cs @@ -181,10 +181,7 @@ private static void TakeParent(TreeNode node, TreeNode newNode) { if (node.Parent == null) { - if (newNode != null) - { - newNode.Parent = null; - } + newNode?.Parent = null; } else if (node.Parent.Left == node) { @@ -599,10 +596,7 @@ public bool MoveNext() _node = _root != null ? FindMinSubTree(_root) : null; _moved = true; #if DEBUG - if (_root != null) - { - _root._inEnumaration = true; - } + _root?._inEnumaration = true; #endif } else @@ -610,10 +604,7 @@ public bool MoveNext() _node = _node != null ? FindSuccessor(_node) : null; } #if DEBUG - if (_root != null) - { - _root._inEnumaration = _node != null; - } + _root?._inEnumaration = _node != null; #endif return _node != null; } @@ -648,10 +639,7 @@ internal TreeNode Left set { _leftChild = value; - if (_leftChild != null) - { - _leftChild._parent = this; - } + _leftChild?._parent = this; } } @@ -664,10 +652,7 @@ internal TreeNode Right set { _rightChild = value; - if (_rightChild != null) - { - _rightChild._parent = this; - } + _rightChild?._parent = this; } } diff --git a/src/libraries/System.Speech/src/Internal/SrgsCompiler/State.cs b/src/libraries/System.Speech/src/Internal/SrgsCompiler/State.cs index 4ed91e27a7791e..b24c16390b0493 100644 --- a/src/libraries/System.Speech/src/Internal/SrgsCompiler/State.cs +++ b/src/libraries/System.Speech/src/Internal/SrgsCompiler/State.cs @@ -158,14 +158,8 @@ internal State Add(State state) internal void Remove() { - if (_prev != null) - { - _prev._next = _next; - } - if (_next != null) - { - _next._prev = _prev; - } + _prev?._next = _next; + _next?._prev = _prev; _next = _prev = null; } diff --git a/src/libraries/System.Speech/src/Internal/Synthesis/VoiceSynthesis.cs b/src/libraries/System.Speech/src/Internal/Synthesis/VoiceSynthesis.cs index 101ccb07123504..64d9ac3cf49423 100644 --- a/src/libraries/System.Speech/src/Internal/Synthesis/VoiceSynthesis.cs +++ b/src/libraries/System.Speech/src/Internal/Synthesis/VoiceSynthesis.cs @@ -390,10 +390,7 @@ internal void Abort() foreach (Parameters parameter in parameters) { ParametersSpeak paramSpeak = parameter._parameter as ParametersSpeak; - if (paramSpeak != null) - { - paramSpeak._prompt.Exception = new OperationCanceledException(SR.Get(SRID.PromptAsyncOperationCancelled)); - } + paramSpeak?._prompt.Exception = new OperationCanceledException(SR.Get(SRID.PromptAsyncOperationCancelled)); } // Restart the worker thread _evtPendingSpeak.Set(); diff --git a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/RuntimeFieldBuilder.Mono.cs b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/RuntimeFieldBuilder.Mono.cs index 2bf9bf01df3163..c73eba841a69dc 100644 --- a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/RuntimeFieldBuilder.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/RuntimeFieldBuilder.Mono.cs @@ -247,8 +247,7 @@ internal void ResolveUserTypes() type = RuntimeTypeBuilder.ResolveUserType(type); RuntimeTypeBuilder.ResolveUserTypes(modReq); RuntimeTypeBuilder.ResolveUserTypes(modOpt); - if (marshal_info != null) - marshal_info.marshaltyperef = RuntimeTypeBuilder.ResolveUserType(marshal_info.marshaltyperef); + marshal_info?.marshaltyperef = RuntimeTypeBuilder.ResolveUserType(marshal_info.marshaltyperef); } internal FieldInfo RuntimeResolve() diff --git a/src/tasks/WasmAppBuilder/WasmAppBuilder.cs b/src/tasks/WasmAppBuilder/WasmAppBuilder.cs index ae2aa23c93e796..6e45e51e4fd860 100644 --- a/src/tasks/WasmAppBuilder/WasmAppBuilder.cs +++ b/src/tasks/WasmAppBuilder/WasmAppBuilder.cs @@ -183,8 +183,7 @@ protected override bool ExecuteInternal() var itemHash = Utils.ComputeIntegrity(item.ItemSpec); Dictionary? resourceList = helper.GetNativeResourceTargetInBootConfig(bootConfig, name); - if (resourceList != null) - resourceList[name] = itemHash; + resourceList?[name] = itemHash; } string packageJsonPath = Path.Combine(AppDir, "package.json"); From 81bf0368512192117e8cbc7c7fb55370e4f4fdbe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20K=C3=B6plinger?= Date: Mon, 15 Sep 2025 22:15:35 +0200 Subject: [PATCH 7/7] Fix more IDE0031 --- .../System.Data.Common/src/System/Data/DataTable.cs | 2 ++ src/mono/wasm/host/Options.cs | 5 +---- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/libraries/System.Data.Common/src/System/Data/DataTable.cs b/src/libraries/System.Data.Common/src/System/Data/DataTable.cs index 49c97189429815..e377d06af229ef 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataTable.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataTable.cs @@ -6842,6 +6842,7 @@ internal void Prepare(DataTable table) [Conditional("DEBUG")] internal void Cleanup() { +#pragma warning disable IDE0031 // Null check can be simplified // cannot assume target table was set if (_targetTable != null) { @@ -6856,6 +6857,7 @@ internal void Cleanup() #endif _targetTable._rowDiffId = null; } +#pragma warning restore IDE0031 } [Conditional("DEBUG")] diff --git a/src/mono/wasm/host/Options.cs b/src/mono/wasm/host/Options.cs index 9743297cfd0a70..b29cb7caf11ad7 100644 --- a/src/mono/wasm/host/Options.cs +++ b/src/mono/wasm/host/Options.cs @@ -1738,10 +1738,7 @@ private void AddCommand(Command value) throw new ArgumentException("Command instances can only be added to a single CommandSet.", nameof(value)); } value.CommandSet = this; - if (value.Options != null) - { - value.Options.MessageLocalizer = options.MessageLocalizer; - } + value.Options?.MessageLocalizer = options.MessageLocalizer; base.Add(value);