diff --git a/eng/Versions.props b/eng/Versions.props index afe55bd258e1c7..a738d4b487bbc7 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -65,6 +65,8 @@ 4.4.0 4.8.0 + + 5.0.0-2.26070.104 - 4.14.0 + 5.4.0-2.26060.102 3.3.5-beta1.23270.2 diff --git a/src/coreclr/System.Private.CoreLib/src/System/StubHelpers.cs b/src/coreclr/System.Private.CoreLib/src/System/StubHelpers.cs index 880c3516e81032..27810e5beced91 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/StubHelpers.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/StubHelpers.cs @@ -1351,11 +1351,8 @@ internal static IntPtr AddToCleanupList(ref CleanupWorkListElement? pCleanupWork internal static void DestroyCleanupList(ref CleanupWorkListElement? pCleanupWorkList) { - if (pCleanupWorkList != null) - { - pCleanupWorkList.Destroy(); - pCleanupWorkList = null; - } + pCleanupWorkList?.Destroy(); + pCleanupWorkList = null; } internal static Exception GetHRExceptionObject(int hr) diff --git a/src/libraries/Common/src/Interop/Windows/BCrypt/Cng.cs b/src/libraries/Common/src/Interop/Windows/BCrypt/Cng.cs index 6d8324b7eef531..876543dea8a89b 100644 --- a/src/libraries/Common/src/Interop/Windows/BCrypt/Cng.cs +++ b/src/libraries/Common/src/Interop/Windows/BCrypt/Cng.cs @@ -177,11 +177,8 @@ public void SetParentHandle(SafeAlgorithmHandle parentHandle) protected sealed override bool ReleaseHandle() { - if (_parentHandle != null) - { - _parentHandle.DangerousRelease(); - _parentHandle = null; - } + _parentHandle?.DangerousRelease(); + _parentHandle = null; uint ntStatus = BCryptDestroyKey(handle); return ntStatus == 0; diff --git a/src/libraries/Common/src/Interop/Windows/WinHttp/Interop.SafeWinHttpHandle.cs b/src/libraries/Common/src/Interop/Windows/WinHttp/Interop.SafeWinHttpHandle.cs index e2fc1cd3d46d49..d5d3bf2d954d55 100644 --- a/src/libraries/Common/src/Interop/Windows/WinHttp/Interop.SafeWinHttpHandle.cs +++ b/src/libraries/Common/src/Interop/Windows/WinHttp/Interop.SafeWinHttpHandle.cs @@ -23,11 +23,8 @@ public SafeWinHttpHandle() : base(true) public static void DisposeAndClearHandle(ref SafeWinHttpHandle? safeHandle) { - if (safeHandle != null) - { - safeHandle.Dispose(); - safeHandle = null; - } + safeHandle?.Dispose(); + safeHandle = null; } public void SetParentHandle(SafeWinHttpHandle parentHandle) @@ -47,11 +44,8 @@ public void SetParentHandle(SafeWinHttpHandle parentHandle) // calls in progress. protected override bool ReleaseHandle() { - if (_parentHandle != null) - { - _parentHandle.DangerousRelease(); - _parentHandle = null; - } + _parentHandle?.DangerousRelease(); + _parentHandle = null; return Interop.WinHttp.WinHttpCloseHandle(handle); } diff --git a/src/libraries/Common/src/Microsoft/Win32/SafeHandles/SafeZstdHandle.cs b/src/libraries/Common/src/Microsoft/Win32/SafeHandles/SafeZstdHandle.cs index 5e6dc922157d39..c901cc78bb319c 100644 --- a/src/libraries/Common/src/Microsoft/Win32/SafeHandles/SafeZstdHandle.cs +++ b/src/libraries/Common/src/Microsoft/Win32/SafeHandles/SafeZstdHandle.cs @@ -22,11 +22,8 @@ protected override bool ReleaseHandle() // release the addref we took in SetDictionary _dictionary?.DangerousRelease(); - if (_prefixHandle != null) - { - _prefixHandle.Value.Dispose(); - _prefixHandle = null; - } + _prefixHandle?.Dispose(); + _prefixHandle = null; return true; } @@ -74,11 +71,8 @@ public unsafe void Reset() ZstandardUtils.ThrowIfError(Interop.Zstd.ZSTD_CCtx_reset(this, Interop.Zstd.ZstdResetDirective.ZSTD_reset_session_only)); // prefix is not sticky and is cleared by reset - if (_prefixHandle != null) - { - _prefixHandle.Value.Dispose(); - _prefixHandle = null; - } + _prefixHandle?.Dispose(); + _prefixHandle = null; } public override bool IsInvalid => handle == IntPtr.Zero; @@ -97,11 +91,8 @@ protected override bool ReleaseHandle() // release the addref we took in SetDictionary _dictionary?.DangerousRelease(); - if (_prefixHandle != null) - { - _prefixHandle.Value.Dispose(); - _prefixHandle = null; - } + _prefixHandle?.Dispose(); + _prefixHandle = null; return true; } @@ -149,11 +140,8 @@ public unsafe void Reset() ZstandardUtils.ThrowIfError(Interop.Zstd.ZSTD_DCtx_reset(this, Interop.Zstd.ZstdResetDirective.ZSTD_reset_session_only)); // prefix is not sticky and is cleared by reset - if (_prefixHandle != null) - { - _prefixHandle.Value.Dispose(); - _prefixHandle = null; - } + _prefixHandle?.Dispose(); + _prefixHandle = null; } public override bool IsInvalid => handle == IntPtr.Zero; diff --git a/src/libraries/Common/src/System/Security/Cryptography/IncrementalHash.netfx.cs b/src/libraries/Common/src/System/Security/Cryptography/IncrementalHash.netfx.cs index 7f78979af07357..18fca25e5b7d1f 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/IncrementalHash.netfx.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/IncrementalHash.netfx.cs @@ -151,11 +151,8 @@ public void Dispose() { _disposed = true; - if (_hash != null) - { - _hash.Dispose(); - _hash = null; - } + _hash?.Dispose(); + _hash = null; } /// diff --git a/src/libraries/Common/src/System/Security/Cryptography/MLDsaCng.Windows.cs b/src/libraries/Common/src/System/Security/Cryptography/MLDsaCng.Windows.cs index dee5e6b7c7db3a..cdb5849f9700b7 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/MLDsaCng.Windows.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/MLDsaCng.Windows.cs @@ -449,10 +449,12 @@ private void ExportKey( keyBytes.Length != expectedKeySize || !parameterSet.SequenceEqual(expectedParameterSet)) { +#pragma warning disable IDE0071 Debug.Fail( $"{nameof(blobType)}: {blobType}, " + $"{nameof(parameterSet)}: {parameterSet.ToString()}, " + $"{nameof(keyBytes)}.Length: {keyBytes.Length} / {expectedKeySize}"); +#pragma warning restore IDE0071 throw new CryptographicException(); } diff --git a/src/libraries/Common/src/System/Security/Cryptography/MLDsaImplementation.Windows.cs b/src/libraries/Common/src/System/Security/Cryptography/MLDsaImplementation.Windows.cs index dcbd34ed8a2015..f3abbff0614333 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/MLDsaImplementation.Windows.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/MLDsaImplementation.Windows.cs @@ -236,10 +236,12 @@ private void ExportKey(string keyBlobType, int expectedKeySize, Span desti keyBytes.Length != expectedKeySize || !parameterSet.SequenceEqual(expectedParameterSet)) { +#pragma warning disable IDE0071 Debug.Fail( $"{nameof(blobType)}: {blobType}, " + $"{nameof(parameterSet)}: {parameterSet.ToString()}, " + $"{nameof(keyBytes)}.Length: {keyBytes.Length} / {expectedKeySize}"); +#pragma warning restore IDE0071 throw new CryptographicException(); } diff --git a/src/libraries/Common/src/System/Security/Cryptography/RSAAppleCrypto.cs b/src/libraries/Common/src/System/Security/Cryptography/RSAAppleCrypto.cs index 4842ab98bcce17..bead3ea9949ef4 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/RSAAppleCrypto.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/RSAAppleCrypto.cs @@ -62,11 +62,8 @@ public override int KeySize ThrowIfDisposed(); - if (_keys != null) - { - _keys.Dispose(); - _keys = null; - } + _keys?.Dispose(); + _keys = null; } } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.cs index 5e2afdabcd49c6..70326a8f29589a 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.cs @@ -248,17 +248,11 @@ protected virtual void Dispose(bool disposing) } finally { - if (catalogToUnsubscribeFrom != null) - { - catalogToUnsubscribeFrom.Changing -= OnCatalogChanging; - } + catalogToUnsubscribeFrom?.Changing -= OnCatalogChanging; aggregateExportProvider?.Dispose(); - if (sourceProvider != null) - { - sourceProvider.ExportsChanging -= OnExportsChangingInternal; - } + sourceProvider?.ExportsChanging -= OnExportsChangingInternal; importEngine?.Dispose(); diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionService.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionService.cs index 13d9b311b21d51..0e72dc44972ec7 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionService.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionService.cs @@ -24,10 +24,7 @@ internal CompositionService(ComposablePartCatalog composablePartCatalog) _notifyCatalog = composablePartCatalog as INotifyComposablePartCatalogChanged; try { - if (_notifyCatalog != null) - { - _notifyCatalog.Changing += OnCatalogChanging; - } + _notifyCatalog?.Changing += OnCatalogChanging; var compositionOptions = CompositionOptions.DisableSilentRejection | CompositionOptions.IsThreadSafe | CompositionOptions.ExportCompositionService; var compositionContainer = new CompositionContainer(composablePartCatalog, compositionOptions); @@ -36,10 +33,7 @@ internal CompositionService(ComposablePartCatalog composablePartCatalog) } catch { - if (_notifyCatalog != null) - { - _notifyCatalog.Changing -= OnCatalogChanging; - } + _notifyCatalog?.Changing -= OnCatalogChanging; throw; } } @@ -62,10 +56,7 @@ public void Dispose() } // Delegates are cool there is no concern if you try to remove an item from them and they don't exist - if (_notifyCatalog != null) - { - _notifyCatalog.Changing -= OnCatalogChanging; - } + _notifyCatalog?.Changing -= OnCatalogChanging; _compositionContainer.Dispose(); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.cs index 98e3d4bcc414cd..9eec00679d4231 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.cs @@ -274,10 +274,7 @@ protected virtual void Dispose(bool disposing) } } - if (sourceProviderToUnsubscribeFrom != null) - { - sourceProviderToUnsubscribeFrom.ExportsChanging -= OnExportsChanging; - } + sourceProviderToUnsubscribeFrom?.ExportsChanging -= OnExportsChanging; if (disposeLock) { diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicenseManager.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicenseManager.cs index b672334a38375e..2ff47b2eb4f56f 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicenseManager.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicenseManager.cs @@ -323,11 +323,8 @@ private static bool ValidateInternalRecursive(LicenseContext context, Type type, #pragma warning restore IDE0059 } isValid = ValidateInternalRecursive(context, baseType, null, allowExceptions, out license, out _); - if (license != null) - { - license.Dispose(); - license = null; - } + license?.Dispose(); + license = null; } } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/Timers/Timer.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/Timers/Timer.cs index 54063f811431e7..eea76c92a2df98 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/Timers/Timer.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/Timers/Timer.cs @@ -250,11 +250,8 @@ public void Close() _delayedEnable = false; _enabled = false; - if (_timer != null) - { - _timer.Dispose(); - _timer = null; - } + _timer?.Dispose(); + _timer = null; } protected override void Dispose(bool disposing) diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigXmlDocument.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigXmlDocument.cs index d90c3bb252585f..cb2cc619a5a94e 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigXmlDocument.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigXmlDocument.cs @@ -61,11 +61,8 @@ public override void Load(string filename) } finally { - if (_reader != null) - { - _reader.Close(); - _reader = null; - } + _reader?.Close(); + _reader = null; } } @@ -82,11 +79,8 @@ public void LoadSingleElement(string filename, XmlTextReader sourceReader) } finally { - if (_reader != null) - { - _reader.Close(); - _reader = null; - } + _reader?.Close(); + _reader = null; } } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ErrorInfoXmlDocument.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ErrorInfoXmlDocument.cs index 5e18a49a8a4ea8..43c327459a17ff 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ErrorInfoXmlDocument.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ErrorInfoXmlDocument.cs @@ -45,11 +45,8 @@ public override void Load(string filename) } finally { - if (_reader != null) - { - _reader.Close(); - _reader = null; - } + _reader?.Close(); + _reader = null; } } @@ -66,11 +63,8 @@ private void LoadFromConfigXmlReader(ConfigXmlReader reader) } finally { - if (_reader != null) - { - _reader.Close(); - _reader = null; - } + _reader?.Close(); + _reader = null; } } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/XmlUtil.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/XmlUtil.cs index 7c13f0c9f2398c..bfaa63c1427d48 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/XmlUtil.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/XmlUtil.cs @@ -142,11 +142,8 @@ private void ReleaseResources() _stream = null; - if (_cachedStringWriter != null) - { - _cachedStringWriter.Close(); - _cachedStringWriter = null; - } + _cachedStringWriter?.Close(); + _cachedStringWriter = null; } // Read until the Next Element element, or we hit 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 52bc8c57c2c34a..da4fe58b642279 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataTable.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataTable.cs @@ -1701,21 +1701,12 @@ public DataColumn[] PrimaryKey oldKey.ConstraintIndex.RemoveRef(); // if PrimaryKey is removed, reset LoadDataRow indexes - if (null != _loadIndex) - { - _loadIndex.RemoveRef(); - _loadIndex = null; - } - if (null != _loadIndexwithOriginalAdded) - { - _loadIndexwithOriginalAdded.RemoveRef(); - _loadIndexwithOriginalAdded = null; - } - if (null != _loadIndexwithCurrentDeleted) - { - _loadIndexwithCurrentDeleted.RemoveRef(); - _loadIndexwithCurrentDeleted = null; - } + _loadIndex?.RemoveRef(); + _loadIndex = null; + _loadIndexwithOriginalAdded?.RemoveRef(); + _loadIndexwithOriginalAdded = null; + _loadIndexwithCurrentDeleted?.RemoveRef(); + _loadIndexwithCurrentDeleted = null; Constraints.Remove(oldKey); } diff --git a/src/libraries/System.Data.Common/src/System/Data/UniqueConstraint.cs b/src/libraries/System.Data.Common/src/System/Data/UniqueConstraint.cs index 705a0f5a5509d7..885a93edd2f16b 100644 --- a/src/libraries/System.Data.Common/src/System/Data/UniqueConstraint.cs +++ b/src/libraries/System.Data.Common/src/System/Data/UniqueConstraint.cs @@ -150,11 +150,8 @@ private void AssertConstraintAndKeyIndexes() internal void ConstraintIndexClear() { - if (null != _constraintIndex) - { - _constraintIndex.RemoveRef(); - _constraintIndex = null; - } + _constraintIndex?.RemoveRef(); + _constraintIndex = null; } internal void ConstraintIndexInitialize() 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 7d796da66d542d..42082892670535 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 @@ -114,11 +114,8 @@ internal void DisconnectFromDataReaderAndConnection() _transaction = null; - if (null != _connection) - { - _connection.RemoveWeakReference(this); - _connection = null; - } + _connection?.RemoveWeakReference(this); + _connection = null; // if the reader is dead we have to dismiss the statement if (liveReader == null) @@ -1035,11 +1032,8 @@ internal void CreateStatementHandle() internal void Dispose() { - if (null != _dataReaderBuf) - { - _dataReaderBuf.Dispose(); - _dataReaderBuf = null; - } + _dataReaderBuf?.Dispose(); + _dataReaderBuf = null; DisposeStatementHandle(); CNativeBuffer? buffer = _nativeParameterBuffer; diff --git a/src/libraries/System.Data.OleDb/src/OleDbConnectionInternal.cs b/src/libraries/System.Data.OleDb/src/OleDbConnectionInternal.cs index a816de5b7e39ab..461b96c3d2e5d4 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbConnectionInternal.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbConnectionInternal.cs @@ -112,16 +112,10 @@ internal OleDbConnectionInternal(OleDbConnectionString constr, OleDbConnection? } catch { - if (null != _sessionwrp) - { - _sessionwrp.Dispose(); - _sessionwrp = null; - } - if (null != _datasrcwrp) - { - _datasrcwrp.Dispose(); - _datasrcwrp = null; - } + _sessionwrp?.Dispose(); + _sessionwrp = null; + _datasrcwrp?.Dispose(); + _datasrcwrp = null; throw; } } diff --git a/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs b/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs index 59662e12c00ec8..d65c0c3dcbed66 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs @@ -654,11 +654,8 @@ public override void Close() { DisposeNativeMultipleResults(); - if (null != bindings) - { - bindings.CloseFromConnection(); - bindings = null; - } + bindings?.CloseFromConnection(); + bindings = null; } else { diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DsesFilterAndTransform.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DsesFilterAndTransform.cs index be75ba9db2d82d..80b94e080331e2 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DsesFilterAndTransform.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DsesFilterAndTransform.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; @@ -410,11 +410,8 @@ private DsesFilterAndTransform( public void Dispose() { - if (_diagnosticsListenersSubscription != null) - { - _diagnosticsListenersSubscription.Dispose(); - _diagnosticsListenersSubscription = null; - } + _diagnosticsListenersSubscription?.Dispose(); + _diagnosticsListenersSubscription = null; if (_liveSubscriptions != null) { diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogInternal.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogInternal.cs index f32c41f3041a99..1c2ca0d102d350 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogInternal.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogInternal.cs @@ -612,17 +612,11 @@ internal void Dispose(bool disposing) Close(); } // This is probably unnecessary - if (readHandle != null) - { - readHandle.Close(); - readHandle = null; - } + readHandle?.Close(); + readHandle = null; - if (writeHandle != null) - { - writeHandle.Close(); - writeHandle = null; - } + writeHandle?.Close(); + writeHandle = null; } } finally diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogWatcher.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogWatcher.cs index f3de1b2d0a7e19..a8fb0827b26c5a 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogWatcher.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogWatcher.cs @@ -113,17 +113,11 @@ internal void StopSubscribing() _registeredWaitHandle = null; } - if (_unregisterDoneHandle != null) - { - _unregisterDoneHandle.Close(); - _unregisterDoneHandle = null; - } + _unregisterDoneHandle?.Close(); + _unregisterDoneHandle = null; - if (_subscriptionWaitHandle != null) - { - _subscriptionWaitHandle.Close(); - _subscriptionWaitHandle = null; - } + _subscriptionWaitHandle?.Close(); + _subscriptionWaitHandle = null; for (int i = 0; i < _numEventsInBuffer; i++) { diff --git a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterLib.cs b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterLib.cs index b4989c06adb218..1c94a12d74aa3c 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterLib.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterLib.cs @@ -346,11 +346,8 @@ internal void CloseTables() internal void Close() { - if (_performanceMonitor != null) - { - _performanceMonitor.Close(); - _performanceMonitor = null; - } + _performanceMonitor?.Close(); + _performanceMonitor = null; CloseTables(); } diff --git a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceData/CounterSetInstance.cs b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceData/CounterSetInstance.cs index a1f12783eb611f..2a16b19ae8b81e 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceData/CounterSetInstance.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceData/CounterSetInstance.cs @@ -87,11 +87,8 @@ private void Dispose(bool disposing) { if (disposing) { - if (Counters != null) - { - Counters.Dispose(); - Counters = null; - } + Counters?.Dispose(); + Counters = null; } unsafe { diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Unix.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Unix.cs index 2dde9eb778cdc9..3363a58192acc9 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Unix.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Unix.cs @@ -147,11 +147,8 @@ private void KillTree(ref List? exceptions) /// Additional logic invoked when the Process is closed. private void CloseCore() { - if (_waitStateHolder != null) - { - _waitStateHolder.Dispose(); - _waitStateHolder = null; - } + _waitStateHolder?.Dispose(); + _waitStateHolder = null; } /// Additional configuration when a process ID is set. diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessWaitState.Unix.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessWaitState.Unix.cs index 042a95b1950c64..fe9adc965c3c3c 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessWaitState.Unix.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessWaitState.Unix.cs @@ -239,11 +239,8 @@ public void Dispose() lock (_gate) { - if (_exitedEvent != null) - { - _exitedEvent.Dispose(); - _exitedEvent = null; - } + _exitedEvent?.Dispose(); + _exitedEvent = null; } } diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADDNLinkedAttrSet.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADDNLinkedAttrSet.cs index 01b09669eb547a..a74b5a7e2fa5de 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADDNLinkedAttrSet.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADDNLinkedAttrSet.cs @@ -960,24 +960,15 @@ internal override void Reset() _foreignGroups.Clear(); _queryMembersResultEnumerator = null; - if (_queryMembersResults != null) - { - _queryMembersResults.Dispose(); - _queryMembersResults = null; - } + _queryMembersResults?.Dispose(); + _queryMembersResults = null; - if (null != _currentMembersSearcher) - { - _currentMembersSearcher.Dispose(); - _currentMembersSearcher = null; - } + _currentMembersSearcher?.Dispose(); + _currentMembersSearcher = null; _memberSearchResultsEnumerator = null; - if (_memberSearchResults != null) - { - _memberSearchResults.Dispose(); - _memberSearchResults = null; - } + _memberSearchResults?.Dispose(); + _memberSearchResults = null; if (null != _memberSearchersQueue) { @@ -1058,11 +1049,8 @@ internal override ResultSetBookmark BookmarkAndReset() _expansionMode = _originalExpansionMode; - if (null != _currentMembersSearcher) - { - _currentMembersSearcher.Dispose(); - _currentMembersSearcher = null; - } + _currentMembersSearcher?.Dispose(); + _currentMembersSearcher = null; _storeCtx = _originalStoreCtx; diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMMembersSet.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMMembersSet.cs index 7c22e86110b5d1..7acb8cc4344bd6 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMMembersSet.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMMembersSet.cs @@ -461,11 +461,8 @@ internal override void Reset() _foreignMembers.Clear(); _foreignGroups.Clear(); - if (_foreignResultSet != null) - { - _foreignResultSet.Dispose(); - _foreignResultSet = null; - } + _foreignResultSet?.Dispose(); + _foreignResultSet = null; _atBeginning = true; } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchema.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchema.cs index 5e8ffe4989613d..aecde0c0665d8a 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchema.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchema.cs @@ -61,17 +61,12 @@ protected override void Dispose(bool disposing) if (disposing) { // dispose schema entry - if (_schemaEntry != null) - { - _schemaEntry.Dispose(); - _schemaEntry = null!; - } + _schemaEntry?.Dispose(); + _schemaEntry = null!; + // dispose the abstract schema entry - if (_abstractSchemaEntry != null) - { - _abstractSchemaEntry.Dispose(); - _abstractSchemaEntry = null; - } + _abstractSchemaEntry?.Dispose(); + _abstractSchemaEntry = null; } _disposed = true; } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClass.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClass.cs index e4fc2ba312cf9f..7f0bc4dbaf538f 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClass.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClass.cs @@ -189,23 +189,14 @@ protected virtual void Dispose(bool disposing) if (disposing) { // dispose schema entry - if (_schemaEntry != null) - { - _schemaEntry.Dispose(); - _schemaEntry = null; - } + _schemaEntry?.Dispose(); + _schemaEntry = null; // dispose class entry - if (_classEntry != null) - { - _classEntry.Dispose(); - _classEntry = null; - } + _classEntry?.Dispose(); + _classEntry = null; // dispose abstract class entry - if (_abstractClassEntry != null) - { - _abstractClassEntry.Dispose(); - _abstractClassEntry = null; - } + _abstractClassEntry?.Dispose(); + _abstractClassEntry = null; // dispose the schema object _schema?.Dispose(); } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaProperty.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaProperty.cs index 5f13df1d473cfc..dcca11b9383a47 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaProperty.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaProperty.cs @@ -242,23 +242,14 @@ protected virtual void Dispose(bool disposing) if (disposing) { // dispose schema entry - if (_schemaEntry != null) - { - _schemaEntry.Dispose(); - _schemaEntry = null; - } + _schemaEntry?.Dispose(); + _schemaEntry = null; // dispose property entry - if (_propertyEntry != null) - { - _propertyEntry.Dispose(); - _propertyEntry = null; - } + _propertyEntry?.Dispose(); + _propertyEntry = null; // dispose abstract class entry - if (_abstractPropertyEntry != null) - { - _abstractPropertyEntry.Dispose(); - _abstractPropertyEntry = null; - } + _abstractPropertyEntry?.Dispose(); + _abstractPropertyEntry = null; // dispose the schema object _schema?.Dispose(); } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ApplicationPartition.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ApplicationPartition.cs index 1a2b8a49177efe..f69774d80db1eb 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ApplicationPartition.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ApplicationPartition.cs @@ -81,16 +81,10 @@ protected override void Dispose(bool disposing) // resources to be freed, those should be done here // if disposing = true, only unmanaged resources should // be freed, else both managed and unmanaged. - if (_crossRefEntry != null) - { - _crossRefEntry.Dispose(); - _crossRefEntry = null; - } - if (_domainDNSEntry != null) - { - _domainDNSEntry.Dispose(); - _domainDNSEntry = null; - } + _crossRefEntry?.Dispose(); + _crossRefEntry = null; + _domainDNSEntry?.Dispose(); + _domainDNSEntry = null; _disposed = true; } diff --git a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarEntry.cs b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarEntry.cs index 6e8382552e4d4b..433c55643c6760 100644 --- a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarEntry.cs +++ b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarEntry.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; @@ -265,15 +265,12 @@ public Stream? DataStream throw new ArgumentException(SR.IO_NotSupported_UnreadableStream, nameof(value)); } - if (_readerOfOrigin != null) - { - // This entry came from a reader, so if the underlying stream is unseekable, we need to - // manually advance the stream pointer to the next header before doing the substitution - // The original stream will get disposed when the reader gets disposed. - _readerOfOrigin.AdvanceDataStreamIfNeeded(); - // We only do this once - _readerOfOrigin = null; - } + // This entry came from a reader, so if the underlying stream is unseekable, we need to + // manually advance the stream pointer to the next header before doing the substitution + // The original stream will get disposed when the reader gets disposed. + _readerOfOrigin?.AdvanceDataStreamIfNeeded(); + // We only do this once + _readerOfOrigin = null; _header._dataStream?.Dispose(); diff --git a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/Package.cs b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/Package.cs index 2a6adbac5a4ab4..b3d87077624976 100644 --- a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/Package.cs +++ b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/Package.cs @@ -770,11 +770,8 @@ protected virtual void Dispose(bool disposing) { _partList?.Clear(); - if (_packageProperties != null) - { - _packageProperties.Dispose(); - _packageProperties = null; - } + _packageProperties?.Dispose(); + _packageProperties = null; //release objects _partList = null!; diff --git a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialPort.cs b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialPort.cs index db12734b0b2192..0b0fc9283c8100 100644 --- a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialPort.cs +++ b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialPort.cs @@ -81,10 +81,7 @@ public event SerialDataReceivedEventHandler DataReceived if (wasNull) { - if (_internalSerialStream != null) - { - _internalSerialStream.DataReceived += _dataReceivedHandler; - } + _internalSerialStream?.DataReceived += _dataReceivedHandler; } } remove @@ -93,10 +90,7 @@ public event SerialDataReceivedEventHandler DataReceived if (_dataReceived == null) { - if (_internalSerialStream != null) - { - _internalSerialStream.DataReceived -= _dataReceivedHandler; - } + _internalSerialStream?.DataReceived -= _dataReceivedHandler; } } } @@ -110,10 +104,7 @@ public event SerialPinChangedEventHandler PinChanged if (wasNull) { - if (_internalSerialStream != null) - { - _internalSerialStream.PinChanged += _pinChangedHandler; - } + _internalSerialStream?.PinChanged += _pinChangedHandler; } } remove @@ -122,10 +113,7 @@ public event SerialPinChangedEventHandler PinChanged if (_pinChanged == null) { - if (_internalSerialStream != null) - { - _internalSerialStream.PinChanged -= _pinChangedHandler; - } + _internalSerialStream?.PinChanged -= _pinChangedHandler; } } } diff --git a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Unix.cs b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Unix.cs index d220cf95a832c1..7182832e3b8ea7 100644 --- a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Unix.cs +++ b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Unix.cs @@ -724,11 +724,8 @@ protected override void Dispose(bool disposing) FinishPendingIORequests(); - if (_handle != null) - { - _handle.Dispose(); - _handle = null; - } + _handle?.Dispose(); + _handle = null; } base.Dispose(disposing); diff --git a/src/libraries/System.Linq/src/System/Linq/AppendPrepend.cs b/src/libraries/System.Linq/src/System/Linq/AppendPrepend.cs index 3e2df29dcae51b..8aefca6e16e41a 100644 --- a/src/libraries/System.Linq/src/System/Linq/AppendPrepend.cs +++ b/src/libraries/System.Linq/src/System/Linq/AppendPrepend.cs @@ -72,11 +72,8 @@ protected bool LoadFromEnumerator() public override void Dispose() { - if (_enumerator is not null) - { - _enumerator.Dispose(); - _enumerator = null; - } + _enumerator?.Dispose(); + _enumerator = null; base.Dispose(); } diff --git a/src/libraries/System.Linq/src/System/Linq/Concat.cs b/src/libraries/System.Linq/src/System/Linq/Concat.cs index 7b6dcc009d5efb..ceb02bc1e009b5 100644 --- a/src/libraries/System.Linq/src/System/Linq/Concat.cs +++ b/src/libraries/System.Linq/src/System/Linq/Concat.cs @@ -206,11 +206,8 @@ private abstract partial class ConcatIterator : Iterator public override void Dispose() { - if (_enumerator is not null) - { - _enumerator.Dispose(); - _enumerator = null; - } + _enumerator?.Dispose(); + _enumerator = null; base.Dispose(); } diff --git a/src/libraries/System.Linq/src/System/Linq/DefaultIfEmpty.cs b/src/libraries/System.Linq/src/System/Linq/DefaultIfEmpty.cs index 1ee5b5fd304db2..b8ab1f9c70beb5 100644 --- a/src/libraries/System.Linq/src/System/Linq/DefaultIfEmpty.cs +++ b/src/libraries/System.Linq/src/System/Linq/DefaultIfEmpty.cs @@ -76,11 +76,8 @@ public override bool MoveNext() public override void Dispose() { - if (_enumerator is not null) - { - _enumerator.Dispose(); - _enumerator = null; - } + _enumerator?.Dispose(); + _enumerator = null; base.Dispose(); } diff --git a/src/libraries/System.Linq/src/System/Linq/Select.SpeedOpt.cs b/src/libraries/System.Linq/src/System/Linq/Select.SpeedOpt.cs index 969487927eac33..b8e158b0f86b6c 100644 --- a/src/libraries/System.Linq/src/System/Linq/Select.SpeedOpt.cs +++ b/src/libraries/System.Linq/src/System/Linq/Select.SpeedOpt.cs @@ -673,11 +673,8 @@ public override bool MoveNext() public override void Dispose() { - if (_enumerator is not null) - { - _enumerator.Dispose(); - _enumerator = null; - } + _enumerator?.Dispose(); + _enumerator = null; base.Dispose(); } diff --git a/src/libraries/System.Linq/src/System/Linq/Select.cs b/src/libraries/System.Linq/src/System/Linq/Select.cs index d5fcb864384440..61bcd88c9def72 100644 --- a/src/libraries/System.Linq/src/System/Linq/Select.cs +++ b/src/libraries/System.Linq/src/System/Linq/Select.cs @@ -128,11 +128,8 @@ private protected override Iterator Clone() => public override void Dispose() { - if (_enumerator is not null) - { - _enumerator.Dispose(); - _enumerator = null; - } + _enumerator?.Dispose(); + _enumerator = null; base.Dispose(); } @@ -306,11 +303,8 @@ public override bool MoveNext() public override void Dispose() { - if (_enumerator is not null) - { - _enumerator.Dispose(); - _enumerator = null; - } + _enumerator?.Dispose(); + _enumerator = null; base.Dispose(); } diff --git a/src/libraries/System.Linq/src/System/Linq/SelectMany.cs b/src/libraries/System.Linq/src/System/Linq/SelectMany.cs index d8845e8334db3e..7c3b48e410d316 100644 --- a/src/libraries/System.Linq/src/System/Linq/SelectMany.cs +++ b/src/libraries/System.Linq/src/System/Linq/SelectMany.cs @@ -166,17 +166,11 @@ private protected override Iterator Clone() public override void Dispose() { - if (_subEnumerator is not null) - { - _subEnumerator.Dispose(); - _subEnumerator = null; - } + _subEnumerator?.Dispose(); + _subEnumerator = null; - if (_sourceEnumerator is not null) - { - _sourceEnumerator.Dispose(); - _sourceEnumerator = null; - } + _sourceEnumerator?.Dispose(); + _sourceEnumerator = null; base.Dispose(); } diff --git a/src/libraries/System.Linq/src/System/Linq/SkipTake.SpeedOpt.cs b/src/libraries/System.Linq/src/System/Linq/SkipTake.SpeedOpt.cs index a6d03bfa40918f..6a3bcfe067ece9 100644 --- a/src/libraries/System.Linq/src/System/Linq/SkipTake.SpeedOpt.cs +++ b/src/libraries/System.Linq/src/System/Linq/SkipTake.SpeedOpt.cs @@ -254,11 +254,8 @@ private protected override Iterator Clone() => public override void Dispose() { - if (_enumerator is not null) - { - _enumerator.Dispose(); - _enumerator = null; - } + _enumerator?.Dispose(); + _enumerator = null; base.Dispose(); } diff --git a/src/libraries/System.Linq/src/System/Linq/Where.cs b/src/libraries/System.Linq/src/System/Linq/Where.cs index c0028a1c004a22..17bd7b8dc1de07 100644 --- a/src/libraries/System.Linq/src/System/Linq/Where.cs +++ b/src/libraries/System.Linq/src/System/Linq/Where.cs @@ -109,11 +109,8 @@ public IEnumerableWhereIterator(IEnumerable source, Func public override void Dispose() { - if (_enumerator is not null) - { - _enumerator.Dispose(); - _enumerator = null; - } + _enumerator?.Dispose(); + _enumerator = null; base.Dispose(); } @@ -383,11 +380,8 @@ private protected override Iterator Clone() => public override void Dispose() { - if (_enumerator is not null) - { - _enumerator.Dispose(); - _enumerator = null; - } + _enumerator?.Dispose(); + _enumerator = null; base.Dispose(); } diff --git a/src/libraries/System.Management/src/System/Management/ManagementBaseObject.cs b/src/libraries/System.Management/src/System/Management/ManagementBaseObject.cs index 76a77643843a8f..4b072ce0946b69 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementBaseObject.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementBaseObject.cs @@ -234,11 +234,8 @@ protected ManagementBaseObject(SerializationInfo info, StreamingContext context) public new void Dispose() { - if (_wbemObject != null) - { - _wbemObject.Dispose(); - _wbemObject = null; - } + _wbemObject?.Dispose(); + _wbemObject = null; base.Dispose(); GC.SuppressFinalize(this); } diff --git a/src/libraries/System.Management/src/System/Management/ManagementEventWatcher.cs b/src/libraries/System.Management/src/System/Management/ManagementEventWatcher.cs index 846b73c89f5e79..cc90c7bb2777e6 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementEventWatcher.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementEventWatcher.cs @@ -246,14 +246,11 @@ public ManagementEventWatcher( // Ensure any outstanding calls are cleared Stop(); - if (null != scope) - scope.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); + scope?.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); - if (null != options) - options.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); + options?.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); - if (null != query) - query.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); + query?.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); } // @@ -294,8 +291,7 @@ public ManagementScope Scope scope = (ManagementScope)value.Clone(); // Unregister ourselves from the previous scope object - if (null != oldScope) - oldScope.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); + oldScope?.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); //register for change events in this object scope.IdentifierChanged += new IdentifierChangedEventHandler(HandleIdentifierChange); @@ -327,8 +323,7 @@ public EventQuery Query query = (EventQuery)value.Clone(); // Unregister ourselves from the previous query object - if (null != oldQuery) - oldQuery.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); + oldQuery?.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); //register for change events in this object query.IdentifierChanged += new IdentifierChangedEventHandler(HandleIdentifierChange); @@ -360,8 +355,7 @@ public EventWatcherOptions Options options = (EventWatcherOptions)value.Clone(); // Unregister ourselves from the previous scope object - if (null != oldOptions) - oldOptions.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); + oldOptions?.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); cachedObjects = new IWbemClassObjectFreeThreaded[options.BlockSize]; //register for change events in this object @@ -504,11 +498,8 @@ public void Start() if (status < 0) { - if (sink != null) - { - sink.ReleaseStub(); - sink = null; - } + sink?.ReleaseStub(); + sink = null; if ((status & 0xfffff000) == 0x80041000) @@ -541,11 +532,8 @@ public void Stop() // In async mode cancel the call to the sink - this will // unwind the operation and cause a Stopped message - if (null != sink) - { - sink.Cancel(); - sink = null; - } + sink?.Cancel(); + sink = null; } private void Initialize() diff --git a/src/libraries/System.Management/src/System/Management/ManagementObject.cs b/src/libraries/System.Management/src/System/Management/ManagementObject.cs index 6686227dd59890..7971041774b100 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementObject.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementObject.cs @@ -102,11 +102,8 @@ protected override void GetObjectData(SerializationInfo info, StreamingContext c public new void Dispose() { - if (wmiClass != null) - { - wmiClass.Dispose(); - wmiClass = null; - } + wmiClass?.Dispose(); + wmiClass = null; base.Dispose(); GC.SuppressFinalize(this); } @@ -513,8 +510,7 @@ public ManagementScope Scope { if (null != value) { - if (null != scope) - scope.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); + scope?.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); scope = ManagementScope._Clone((ManagementScope)value, new IdentifierChangedEventHandler(HandleIdentifierChange)); @@ -576,8 +572,7 @@ public virtual ManagementPath Path (GetType() == typeof(ManagementClass) && newPath.IsClass) || newPath.IsEmpty) { - if (null != path) - path.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); + path?.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); path = ManagementPath._Clone((ManagementPath)value, new IdentifierChangedEventHandler(HandleIdentifierChange)); @@ -629,8 +624,7 @@ public ObjectGetOptions Options { if (null != value) { - if (null != options) - options.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); + options?.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); options = ObjectGetOptions._Clone((ObjectGetOptions)value, new IdentifierChangedEventHandler(HandleIdentifierChange)); diff --git a/src/libraries/System.Management/src/System/Management/ManagementOptions.cs b/src/libraries/System.Management/src/System/Management/ManagementOptions.cs index 94c108df19ccd6..8b1bb5e33d637d 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementOptions.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementOptions.cs @@ -177,8 +177,7 @@ public ManagementNamedValueCollection Context else context = new ManagementNamedValueCollection(); - if (null != oldContext) - oldContext.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); + oldContext?.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); //register for change events in this object context.IdentifierChanged += new IdentifierChangedEventHandler(HandleIdentifierChange); diff --git a/src/libraries/System.Management/src/System/Management/ManagementScope.cs b/src/libraries/System.Management/src/System/Management/ManagementScope.cs index b0944fac8a9c53..7faecc65466f30 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementScope.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementScope.cs @@ -813,8 +813,7 @@ public ConnectionOptions Options { if (null != value) { - if (null != options) - options.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); + options?.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); options = ConnectionOptions._Clone((ConnectionOptions)value, new IdentifierChangedEventHandler(HandleIdentifierChange)); @@ -851,8 +850,7 @@ public ManagementPath Path { if (null != value) { - if (null != prvpath) - prvpath.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); + prvpath?.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); IsDefaulted = false; //someone is specifically setting the scope path so it's not defaulted any more diff --git a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestState.cs b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestState.cs index c2141c6578b2e7..c05e8648fddd16 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestState.cs +++ b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestState.cs @@ -86,11 +86,8 @@ public void ClearSendRequestState() ServerCredentials = null; DefaultProxyCredentials = null; - if (RequestHandle != null) - { - RequestHandle.Dispose(); - RequestHandle = null; - } + RequestHandle?.Dispose(); + RequestHandle = null; } public TaskCompletionSource? Tcs { get; set; } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ConnectionPool/HttpConnectionPool.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ConnectionPool/HttpConnectionPool.cs index d78cae1d9e2040..094288c28fb177 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ConnectionPool/HttpConnectionPool.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ConnectionPool/HttpConnectionPool.cs @@ -916,11 +916,8 @@ public void Dispose() _availableHttp3Connections.Clear(); } - if (_authorityExpireTimer != null) - { - _authorityExpireTimer.Dispose(); - _authorityExpireTimer = null; - } + _authorityExpireTimer?.Dispose(); + _authorityExpireTimer = null; if (_altSvcBlocklistTimerCancellation != null) { diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionResponseContent.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionResponseContent.cs index 3bc32fd2e19e36..b8a73bf53498c3 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionResponseContent.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionResponseContent.cs @@ -84,11 +84,8 @@ protected sealed override void Dispose(bool disposing) { if (disposing) { - if (_stream != null) - { - _stream.Dispose(); - _stream = null; - } + _stream?.Dispose(); + _stream = null; } base.Dispose(disposing); diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpContentStream.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpContentStream.cs index 0c40bdb17a3179..d2f66377a141c5 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpContentStream.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpContentStream.cs @@ -22,11 +22,8 @@ protected override void Dispose(bool disposing) { if (disposing) { - if (_connection != null) - { - _connection.Dispose(); - _connection = null; - } + _connection?.Dispose(); + _connection = null; } base.Dispose(disposing); diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/MailMessage.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/MailMessage.cs index 02eefbe1ed9315..4dc1174bf68580 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/MailMessage.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/MailMessage.cs @@ -315,11 +315,8 @@ protected virtual void Dispose(bool disposing) private void SetContent(bool allowUnicode) { //the attachments may have changed, so we need to reset the message - if (_bodyView != null) - { - _bodyView.Dispose(); - _bodyView = null; - } + _bodyView?.Dispose(); + _bodyView = null; if (AlternateViews.Count == 0 && Attachments.Count == 0) { diff --git a/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.Windows.cs b/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.Windows.cs index 0b04636ac4f71c..b2f5c92c3d9145 100644 --- a/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.Windows.cs +++ b/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.Windows.cs @@ -117,13 +117,10 @@ private void UnregisterWaitHandle() { lock (_lockObject) { - if (_registeredWait != null) - { - // If Unregister returns false, it is sufficient to nullify registeredWait - // and let its own finalizer clean up later. - _registeredWait.Unregister(null); - _registeredWait = null; - } + // If Unregister returns false, it is sufficient to nullify registeredWait + // and let its own finalizer clean up later. + _registeredWait?.Unregister(null); + _registeredWait = null; } } @@ -230,31 +227,19 @@ private void Cleanup(bool isAsync) partial void InternalDisposeCore() { - if (_handlePingV4 != null) - { - _handlePingV4.Dispose(); - _handlePingV4 = null; - } + _handlePingV4?.Dispose(); + _handlePingV4 = null; - if (_handlePingV6 != null) - { - _handlePingV6.Dispose(); - _handlePingV6 = null; - } + _handlePingV6?.Dispose(); + _handlePingV6 = null; UnregisterWaitHandle(); - if (_pingEvent != null) - { - _pingEvent.Dispose(); - _pingEvent = null; - } + _pingEvent?.Dispose(); + _pingEvent = null; - if (_replyBuffer != null) - { - _replyBuffer.Dispose(); - _replyBuffer = null; - } + _replyBuffer?.Dispose(); + _replyBuffer = null; } // Private callback invoked when icmpsendecho APIs succeed. @@ -317,11 +302,8 @@ private unsafe void SetUnmanagedStructures(byte[] buffer) // Releases the unmanaged memory after ping completion. private void FreeUnmanagedStructures() { - if (_requestBuffer != null) - { - _requestBuffer.Dispose(); - _requestBuffer = null; - } + _requestBuffer?.Dispose(); + _requestBuffer = null; } private static IPStatus GetStatusFromCode(int statusCode) diff --git a/src/libraries/System.Private.CoreLib/src/System/Buffers/MemoryHandle.cs b/src/libraries/System.Private.CoreLib/src/System/Buffers/MemoryHandle.cs index 2ac65aa35a1264..4f8db6608fbcf9 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Buffers/MemoryHandle.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Buffers/MemoryHandle.cs @@ -44,11 +44,8 @@ public void Dispose() _handle.Free(); } - if (_pinnable != null) - { - _pinnable.Unpin(); - _pinnable = null; - } + _pinnable?.Unpin(); + _pinnable = null; _pointer = null; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/DiagnosticCounter.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/DiagnosticCounter.cs index 0095e93ba4ae4c..2070f432738c5c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/DiagnosticCounter.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/DiagnosticCounter.cs @@ -55,11 +55,8 @@ private protected void Publish() /// public void Dispose() { - if (_group != null) - { - _group.Remove(this); - _group = null; - } + _group?.Remove(this); + _group = null; } /// diff --git a/src/libraries/System.Private.CoreLib/src/System/Security/SecureString.cs b/src/libraries/System.Private.CoreLib/src/System/Security/SecureString.cs index 65ff3788b06d6d..c646751a32a67f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Security/SecureString.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Security/SecureString.cs @@ -160,11 +160,8 @@ public void Dispose() { lock (_methodLock) { - if (_buffer != null) - { - _buffer.Dispose(); - _buffer = null; - } + _buffer?.Dispose(); + _buffer = null; } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/ReaderWriterLockSlim.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/ReaderWriterLockSlim.cs index 828222db0082b3..0f864ca7fa5357 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/ReaderWriterLockSlim.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/ReaderWriterLockSlim.cs @@ -1257,29 +1257,17 @@ private void Dispose(bool disposing) if (IsReadLockHeld || IsUpgradeableReadLockHeld || IsWriteLockHeld) throw new SynchronizationLockException(SR.SynchronizationLockException_IncorrectDispose); - if (_writeEvent != null) - { - _writeEvent.Dispose(); - _writeEvent = null; - } + _writeEvent?.Dispose(); + _writeEvent = null; - if (_readEvent != null) - { - _readEvent.Dispose(); - _readEvent = null; - } + _readEvent?.Dispose(); + _readEvent = null; - if (_upgradeEvent != null) - { - _upgradeEvent.Dispose(); - _upgradeEvent = null; - } + _upgradeEvent?.Dispose(); + _upgradeEvent = null; - if (_waitUpgradeEvent != null) - { - _waitUpgradeEvent.Dispose(); - _waitUpgradeEvent = null; - } + _waitUpgradeEvent?.Dispose(); + _waitUpgradeEvent = null; _fDisposed = true; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/RegisteredWaitHandle.WindowsThreadPool.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/RegisteredWaitHandle.WindowsThreadPool.cs index f220fb4dbdaf7f..5c288082c6717f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/RegisteredWaitHandle.WindowsThreadPool.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/RegisteredWaitHandle.WindowsThreadPool.cs @@ -206,11 +206,8 @@ private void FinishUnregisteringAsync(object? waitObject) _tpWait = IntPtr.Zero; } - if (_waitHandle != null) - { - _waitHandle.DangerousRelease(); - _waitHandle = null; - } + _waitHandle?.DangerousRelease(); + _waitHandle = null; } } finally diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/WaitHandle.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/WaitHandle.cs index 07d11d18adb0d3..6eb5b3a086ea2d 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/WaitHandle.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/WaitHandle.cs @@ -56,11 +56,8 @@ public virtual IntPtr Handle // ideally do these things: // *) Expose a settable SafeHandle property on WaitHandle. // *) Expose a settable OwnsHandle property on SafeHandle. - if (_waitHandle != null) - { - _waitHandle.SetHandleAsInvalid(); - _waitHandle = null; - } + _waitHandle?.SetHandleAsInvalid(); + _waitHandle = null; } else { diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/WaitSubsystem.Unix.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/WaitSubsystem.Unix.cs index cad35f0dc4d378..20335f072139d7 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/WaitSubsystem.Unix.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/WaitSubsystem.Unix.cs @@ -134,11 +134,8 @@ public LockHolder(LowLevelLock l) public void Dispose() { - if (_lock != null) - { - _lock.Release(); - _lock = null; - } + _lock?.Release(); + _lock = null; } } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBufferReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBufferReader.cs index d063d729297e95..1d6b06f8c48c06 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBufferReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBufferReader.cs @@ -101,11 +101,8 @@ public void Close() { _streamBuffer = null; } - if (_stream != null) - { - _stream.Dispose(); - _stream = null; - } + _stream?.Dispose(); + _stream = null; _buffer = Array.Empty(); _offset = 0; _offsetMax = 0; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/BinaryXml/XmlBinaryReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/BinaryXml/XmlBinaryReader.cs index f803aa7419cf2c..7e710249c218da 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/BinaryXml/XmlBinaryReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/BinaryXml/XmlBinaryReader.cs @@ -877,11 +877,8 @@ public override void Close() _nodetype = XmlNodeType.None; _token = BinXmlToken.Error; _stringValue = null; - if (null != _textXmlReader) - { - _textXmlReader.Close(); - _textXmlReader = null; - } + _textXmlReader?.Close(); + _textXmlReader = null; if (null != _inStrm && _closeInput) _inStrm.Dispose(); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNode.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNode.cs index 79bbbc75d0e7a2..656a645c221e56 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNode.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNode.cs @@ -765,9 +765,9 @@ public virtual void Normalize() } default: { - if (firstChildTextLikeNode != null) + if (firstChildTextLikeNode is XmlNode node) { - firstChildTextLikeNode.Value = sb.ToString(); + node.Value = sb.ToString(); firstChildTextLikeNode = null; } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeNameParser.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeNameParser.cs index 448cc85ff1003e..ee89603972b7d3 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeNameParser.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeNameParser.cs @@ -61,7 +61,9 @@ private TypeNameParser(ReadOnlySpan name, bool throwOnError, TypeNameParse return null; } +#pragma warning disable IDE0071 Debug.Assert(parsedName.GetNodeCount() == recursiveDepth, $"Node count mismatch for '{typeName.ToString()}'"); +#pragma warning restore IDE0071 return parsedName; } diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/EnvelopedCms.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/EnvelopedCms.cs index 25f2278c331631..8af43c281929a8 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/EnvelopedCms.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/EnvelopedCms.cs @@ -97,11 +97,8 @@ public void Encrypt(CmsRecipientCollection recipients) if (recipients.Count == 0) throw new PlatformNotSupportedException(SR.Cryptography_Cms_NoRecipients); - if (_decryptorPal != null) - { - _decryptorPal.Dispose(); - _decryptorPal = null; - } + _decryptorPal?.Dispose(); + _decryptorPal = null; _encodedMessage = PkcsPal.Instance.Encrypt(recipients, ContentInfo, ContentEncryptionAlgorithm, Certificates, UnprotectedAttributes); _lastCall = LastCall.Encrypt; } @@ -143,11 +140,8 @@ public void Decode(byte[] encodedMessage) #endif void Decode(ReadOnlySpan encodedMessage) { - if (_decryptorPal != null) - { - _decryptorPal.Dispose(); - _decryptorPal = null; - } + _decryptorPal?.Dispose(); + _decryptorPal = null; int version; ContentInfo contentInfo; diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngAlgorithmCore.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngAlgorithmCore.cs index af11684e1b730f..8e87980f63aa2c 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngAlgorithmCore.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngAlgorithmCore.cs @@ -37,11 +37,8 @@ public bool IsKeyGeneratedNamedCurve() public void DisposeKey() { - if (_lazyKey != null) - { - _lazyKey.Dispose(); - _lazyKey = null; - } + _lazyKey?.Dispose(); + _lazyKey = null; } public CngKey GetOrGenerateKey(int keySize, CngAlgorithm algorithm) diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/IncrementalHash.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/IncrementalHash.cs index 05f5d7092c575a..26564f452774b0 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/IncrementalHash.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/IncrementalHash.cs @@ -356,17 +356,11 @@ public void Dispose() { _disposed = true; - if (_hash != null) - { - _hash.Dispose(); - _hash = null; - } + _hash?.Dispose(); + _hash = null; - if (_hmac != null) - { - _hmac.Dispose(true); - _hmac = null; - } + _hmac?.Dispose(true); + _hmac = null; } /// diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/AndroidCertificatePal.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/AndroidCertificatePal.cs index f0192bcb3c9dfc..5fcaec635d3796 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/AndroidCertificatePal.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/AndroidCertificatePal.cs @@ -575,11 +575,8 @@ public void AppendPrivateKeyInfo(StringBuilder sb) public void Dispose() { - if (_privateKey != null) - { - _privateKey.Dispose(); - _privateKey = null; - } + _privateKey?.Dispose(); + _privateKey = null; if (_cert != null) { diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/OpenSslX509CertificateReader.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/OpenSslX509CertificateReader.cs index 0fa48589caa989..61f4568a7db988 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/OpenSslX509CertificateReader.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/OpenSslX509CertificateReader.cs @@ -831,11 +831,8 @@ public void AppendPrivateKeyInfo(StringBuilder sb) public void Dispose() { - if (_privateKey != null) - { - _privateKey.Dispose(); - _privateKey = null; - } + _privateKey?.Dispose(); + _privateKey = null; if (_cert != null) { diff --git a/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceController.cs b/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceController.cs index d8b98fc2003828..51efe1e8f62bd9 100644 --- a/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceController.cs +++ b/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceController.cs @@ -468,11 +468,8 @@ private static bool CheckMachineName(string value) /// public void Close() { - if (_serviceManagerHandle != null) - { - _serviceManagerHandle.Dispose(); - _serviceManagerHandle = null; - } + _serviceManagerHandle?.Dispose(); + _serviceManagerHandle = null; _statusGenerated = false; _startTypeInitialized = false; diff --git a/src/libraries/System.Speech/src/Internal/ObjectToken/ObjectToken.cs b/src/libraries/System.Speech/src/Internal/ObjectToken/ObjectToken.cs index fea500a3041301..37ae8a9f43a9ae 100644 --- a/src/libraries/System.Speech/src/Internal/ObjectToken/ObjectToken.cs +++ b/src/libraries/System.Speech/src/Internal/ObjectToken/ObjectToken.cs @@ -68,11 +68,8 @@ protected override void Dispose(bool disposing) Marshal.ReleaseComObject(_sapiObjectToken); _sapiObjectToken = null; } - if (_attributes != null) - { - _attributes.Dispose(); - _attributes = null; - } + _attributes?.Dispose(); + _attributes = null; } } finally diff --git a/src/libraries/System.Speech/src/Recognition/RecognizerBase.cs b/src/libraries/System.Speech/src/Recognition/RecognizerBase.cs index 2c98f3b83a2951..4a2a9d58c2d757 100644 --- a/src/libraries/System.Speech/src/Recognition/RecognizerBase.cs +++ b/src/libraries/System.Speech/src/Recognition/RecognizerBase.cs @@ -1346,22 +1346,13 @@ protected virtual void Dispose(bool disposing) // Release SAPI recognizer/recoContext interfaces. // We do not need to release additional references copy onto the same RCW. - if (_sapiContext != null) - { - _sapiContext.Dispose(); - _sapiContext = null; - } - if (_sapiRecognizer != null) - { - _sapiRecognizer.Dispose(); - _sapiRecognizer = null; - } + _sapiContext?.Dispose(); + _sapiContext = null; + _sapiRecognizer?.Dispose(); + _sapiRecognizer = null; - if (_recognizerInfo != null) - { - _recognizerInfo.Dispose(); - _recognizerInfo = null; - } + _recognizerInfo?.Dispose(); + _recognizerInfo = null; _disposed = true; } @@ -2767,11 +2758,8 @@ private object GetBookmarkItemAndRemove(uint bookmarkId) private void CloseCachedInputStream() { - if (_inputStream != null) - { - _inputStream.Close(); - _inputStream = null; - } + _inputStream?.Close(); + _inputStream = null; } /// diff --git a/src/libraries/System.Speech/src/Recognition/SpeechRecognitionEngine.cs b/src/libraries/System.Speech/src/Recognition/SpeechRecognitionEngine.cs index 36a7d13f08871a..f403e9a27c4607 100644 --- a/src/libraries/System.Speech/src/Recognition/SpeechRecognitionEngine.cs +++ b/src/libraries/System.Speech/src/Recognition/SpeechRecognitionEngine.cs @@ -83,16 +83,10 @@ protected virtual void Dispose(bool disposing) { if (disposing && !_disposed) { - if (_recognizerBase != null) - { - _recognizerBase.Dispose(); - _recognizerBase = null; - } - if (_sapiRecognizer != null) - { - _sapiRecognizer.Dispose(); - _sapiRecognizer = null; - } + _recognizerBase?.Dispose(); + _recognizerBase = null; + _sapiRecognizer?.Dispose(); + _sapiRecognizer = null; _disposed = true; // Don't set RecognizerBase to null as every method will then need to throw ObjectDisposedException. } } diff --git a/src/libraries/System.Speech/src/Recognition/SpeechRecognizer.cs b/src/libraries/System.Speech/src/Recognition/SpeechRecognizer.cs index 342b470aff468b..7673f1bc0cbe78 100644 --- a/src/libraries/System.Speech/src/Recognition/SpeechRecognizer.cs +++ b/src/libraries/System.Speech/src/Recognition/SpeechRecognizer.cs @@ -27,16 +27,10 @@ protected virtual void Dispose(bool disposing) { if (disposing && !_disposed) { - if (_recognizerBase != null) - { - _recognizerBase.Dispose(); - _recognizerBase = null; - } - if (_sapiRecognizer != null) - { - _sapiRecognizer.Dispose(); - _sapiRecognizer = null; - } + _recognizerBase?.Dispose(); + _recognizerBase = null; + _sapiRecognizer?.Dispose(); + _sapiRecognizer = null; _disposed = true; // Don't set RecognizerBase to null as every method will then need to throw ObjectDisposedException. } } diff --git a/src/libraries/System.Speech/src/Synthesis/SpeechSynthesizer.cs b/src/libraries/System.Speech/src/Synthesis/SpeechSynthesizer.cs index 9ce5166bb57914..7c4a1c33eee8b2 100644 --- a/src/libraries/System.Speech/src/Synthesis/SpeechSynthesizer.cs +++ b/src/libraries/System.Speech/src/Synthesis/SpeechSynthesizer.cs @@ -486,12 +486,9 @@ private void Dispose(bool disposing) } } - if (_voiceSynthesis != null) - { - // Terminate the background synthesis object the thread. - _voiceSynthesis.Dispose(); - _voiceSynthesis = null; - } + // Terminate the background synthesis object the thread. + _voiceSynthesis?.Dispose(); + _voiceSynthesis = null; _isDisposed = true; } diff --git a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BatchBlock.cs b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BatchBlock.cs index db265298ffbbb4..cd51d9ada75b53 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BatchBlock.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BatchBlock.cs @@ -384,7 +384,7 @@ internal DataflowMessageStatus OfferMessage(DataflowMessageHeader messageHeader, // Once consumed, enqueue it. _messages.Enqueue(messageValue!); - if (_boundingState != null) _boundingState.CurrentCount += 1; // track this new item against our bound + if (_boundingState != null) _boundingState.CurrentCount++; // track this new item against our bound // Now start declining if the number of batches we've already made plus // the number we can make from data already enqueued meets our quota. @@ -1010,7 +1010,7 @@ private void ConsumeReservedMessagesNonGreedy() lock (IncomingLock) { // Increment the bounding count with the number of consumed messages - if (_boundingState != null) _boundingState.CurrentCount += reserved.Count; + if (_boundingState is BoundingState boundingState) boundingState.CurrentCount += reserved.Count; // Enqueue the consumed messages foreach (KeyValuePair, KeyValuePair> sourceAndMessage in reserved) @@ -1059,7 +1059,7 @@ private void ConsumeReservedMessagesGreedyBounded() lock (IncomingLock) { // Increment the bounding count with the number of consumed messages - if (_boundingState != null) _boundingState.CurrentCount += consumedCount; + if (_boundingState is BoundingState boundingState) boundingState.CurrentCount += consumedCount; // Enqueue the consumed messages foreach (KeyValuePair, KeyValuePair> sourceAndMessage in reserved) diff --git a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BroadcastBlock.cs b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BroadcastBlock.cs index a900995c99cfba..4c4a6fa0ed293b 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BroadcastBlock.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BroadcastBlock.cs @@ -194,7 +194,7 @@ DataflowMessageStatus ITargetBlock.OfferMessage(DataflowMessageHeader message // Once consumed, pass it to the delegate _source.AddMessage(messageValue!); - if (_boundingState != null) _boundingState.CurrentCount += 1; // track this new item against our bound + if (_boundingState != null) _boundingState.CurrentCount++; // track this new item against our bound return DataflowMessageStatus.Accepted; } // Otherwise, we try to postpone if a source was provided diff --git a/src/libraries/System.Threading.Tasks.Dataflow/src/Internal/TargetCore.cs b/src/libraries/System.Threading.Tasks.Dataflow/src/Internal/TargetCore.cs index cff6ecf4b4b43c..9d1b250f07aa55 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Internal/TargetCore.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Internal/TargetCore.cs @@ -216,7 +216,7 @@ internal DataflowMessageStatus OfferMessage(DataflowMessageHeader messageHeader, // Once consumed, enqueue the message with its ID and kick off asynchronous processing. long messageId = _nextAvailableInputMessageId.Value++; Debug.Assert(messageId != Common.INVALID_REORDERING_ID, "The assigned message ID is invalid."); - if (_boundingState != null) _boundingState.CurrentCount += 1; // track this new item against our bound + if (_boundingState != null) _boundingState.CurrentCount++; // track this new item against our bound _messages.Enqueue(new KeyValuePair(messageValue!, messageId)); ProcessAsyncIfNecessary(); return DataflowMessageStatus.Accepted; diff --git a/src/libraries/System.Threading.Tasks.Dataflow/src/Internal/TargetRegistry.cs b/src/libraries/System.Threading.Tasks.Dataflow/src/Internal/TargetRegistry.cs index 994e4493889668..6e91c00c8fb126 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Internal/TargetRegistry.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Internal/TargetRegistry.cs @@ -254,17 +254,11 @@ internal void RemoveFromList(LinkedTargetInfo node) LinkedTargetInfo? next = node.Next; // Remove the node by linking the adjacent nodes - if (node.Previous != null) - { - node.Previous.Next = next; - node.Previous = null; - } + previous?.Next = next; + node.Previous = null; - if (node.Next != null) - { - node.Next.Previous = previous; - node.Next = null; - } + next?.Previous = previous; + node.Next = null; // Adjust the list ends if (_firstTarget == node) _firstTarget = next; diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/Oletx/OletxTransaction.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/Oletx/OletxTransaction.cs index d99c9ca5596c3f..c47f9fe59eca62 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/Oletx/OletxTransaction.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/Oletx/OletxTransaction.cs @@ -662,11 +662,8 @@ internal RealOletxTransaction( { if (!successful) { - if (_outcomeEnlistment != null) - { - _outcomeEnlistment.UnregisterOutcomeCallback(); - _outcomeEnlistment = null; - } + _outcomeEnlistment?.UnregisterOutcomeCallback(); + _outcomeEnlistment = null; } } }