diff --git a/src/coreclr/System.Private.CoreLib/src/Internal/Runtime/InteropServices/ComActivator.cs b/src/coreclr/System.Private.CoreLib/src/Internal/Runtime/InteropServices/ComActivator.cs index a78bb670a2d79..da6ccb945e751 100644 --- a/src/coreclr/System.Private.CoreLib/src/Internal/Runtime/InteropServices/ComActivator.cs +++ b/src/coreclr/System.Private.CoreLib/src/Internal/Runtime/InteropServices/ComActivator.cs @@ -716,11 +716,7 @@ public string RequestLicKey(Type type) throw new COMException(); // E_FAIL } - var license = (IDisposable?)parameters[2]; - if (license != null) - { - license.Dispose(); - } + ((IDisposable?)parameters[2])?.Dispose(); var licenseKey = (string?)parameters[3]; if (licenseKey == null) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/DynamicMethod.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/DynamicMethod.cs index bd939a56daa6b..4fdd536b36e4c 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/DynamicMethod.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/DynamicMethod.cs @@ -821,11 +821,13 @@ internal RuntimeParameterInfo[] LoadParameters() Type[] parameterTypes = m_owner.m_parameterTypes; RuntimeParameterInfo[] parameters = new RuntimeParameterInfo[parameterTypes.Length]; for (int i = 0; i < parameterTypes.Length; i++) + { parameters[i] = new RuntimeParameterInfo(this, null, parameterTypes[i], i); - if (m_parameters == null) - // should we interlockexchange? - m_parameters = parameters; + } + + m_parameters ??= parameters; // should we Interlocked.CompareExchange? } + return m_parameters; } } diff --git a/src/coreclr/System.Private.CoreLib/src/System/StubHelpers.cs b/src/coreclr/System.Private.CoreLib/src/System/StubHelpers.cs index dbcc1ce868f8c..4063f0b22836e 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/StubHelpers.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/StubHelpers.cs @@ -1180,9 +1180,11 @@ internal static Exception GetCOMHRExceptionObject(int hr, IntPtr pCPCMD, object { Exception? ex = s_pendingExceptionObject; if (ex != null) + { ex.InternalPreserveStackTrace(); + s_pendingExceptionObject = null; + } - s_pendingExceptionObject = null; return ex; } diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/Internal/Reflection/Extensions/NonPortable/CustomAttributeSearcher.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/Internal/Reflection/Extensions/NonPortable/CustomAttributeSearcher.cs index b8a3ed263731e..c01d470b258a6 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/Internal/Reflection/Extensions/NonPortable/CustomAttributeSearcher.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/Internal/Reflection/Extensions/NonPortable/CustomAttributeSearcher.cs @@ -191,8 +191,7 @@ private IEnumerable GetMatchingCustomAttributesIterator(E e } else { - if (usage == null) - usage = GetAttributeUsage(attributeType); + usage ??= GetAttributeUsage(attributeType); encounteredTypes[attributeTypeKey] = usage; // Type was encountered at a lower level. Only include it if its inheritable AND allowMultiple. if (usage.Inherited && usage.AllowMultiple) diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/ActivatorImplementation.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/ActivatorImplementation.cs index ecd8889a0c33d..36218921dfb2b 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/ActivatorImplementation.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/ActivatorImplementation.cs @@ -60,8 +60,7 @@ public static object CreateInstance( type = type.UnderlyingSystemType; CreateInstanceCheckType(type); - if (args == null) - args = Array.Empty(); + args ??= Array.Empty(); int numArgs = args.Length; Type?[] argTypes = new Type[numArgs]; @@ -85,8 +84,7 @@ public static object CreateInstance( throw new MissingMethodException(SR.Format(SR.Arg_NoDefCTor, type)); } - if (binder == null) - binder = Type.DefaultBinder; + binder ??= Type.DefaultBinder; MethodBase invokeMethod = binder.BindToMethod(bindingAttr, matches.ToArray(), ref args, null, culture, null, out object? state); if (invokeMethod.GetParametersNoCopy().Length == 0) diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/InvokeUtils.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/InvokeUtils.cs index cfa20e99d7a5b..5e7c3b2de618f 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/InvokeUtils.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/InvokeUtils.cs @@ -525,10 +525,7 @@ internal static object DynamicInvokeBoxedValuetypeReturn(out DynamicInvokeParamL { if (paramType == DynamicInvokeParamType.Ref) { - if (nullableCopyBackObjects == null) - { - nullableCopyBackObjects = new object[parameters.Length]; - } + nullableCopyBackObjects ??= new object[parameters.Length]; nullableCopyBackObjects[index] = finalObjectToReturn; parameters[index] = null; @@ -667,10 +664,7 @@ public static object DynamicInvokeParamHelperCore(ref ArgSetupState argSetupStat { // Since this not a by-ref parameter, we don't want to bash the original user-owned argument array but the rules of DynamicInvokeParamHelperCore() require // that we return non-value types as the "index"th element in an array. Thus, create an on-demand throwaway array just for this purpose. - if (argSetupState.customBinderProvidedParameters == null) - { - argSetupState.customBinderProvidedParameters = new object[argSetupState.parameters.Length]; - } + argSetupState.customBinderProvidedParameters ??= new object[argSetupState.parameters.Length]; argSetupState.customBinderProvidedParameters[index] = incomingParam; return argSetupState.customBinderProvidedParameters; } diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/Assemblies/NativeFormat/NativeFormatRuntimeAssembly.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/Assemblies/NativeFormat/NativeFormatRuntimeAssembly.cs index 93fd3bfca537b..d832e7894ef45 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/Assemblies/NativeFormat/NativeFormatRuntimeAssembly.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/Assemblies/NativeFormat/NativeFormatRuntimeAssembly.cs @@ -123,10 +123,7 @@ protected sealed override IEnumerable TypeForwardInfos string? namespaceName = null; foreach (TypeForwarderHandle typeForwarderHandle in namespaceHandle.GetNamespaceDefinition(reader).TypeForwarders) { - if (namespaceName == null) - { - namespaceName = namespaceHandle.ToNamespaceName(reader); - } + namespaceName ??= namespaceHandle.ToNamespaceName(reader); TypeForwarder typeForwarder = typeForwarderHandle.GetTypeForwarder(reader); string typeName = typeForwarder.Name.GetString(reader); diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/Assemblies/RuntimeAssemblyInfo.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/Assemblies/RuntimeAssemblyInfo.cs index 491acf920ec10..1908e1be92b40 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/Assemblies/RuntimeAssemblyInfo.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/Assemblies/RuntimeAssemblyInfo.cs @@ -146,10 +146,7 @@ public sealed override Type[] GetForwardedTypes() } else { - if (exceptions == null) - { - exceptions = new List(); - } + exceptions ??= new List(); exceptions.Add(exception); } } diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/CustomAttributes/RuntimePseudoCustomAttributeData.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/CustomAttributes/RuntimePseudoCustomAttributeData.cs index 0e81484c5dcdc..84e8358f42ab8 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/CustomAttributes/RuntimePseudoCustomAttributeData.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/CustomAttributes/RuntimePseudoCustomAttributeData.cs @@ -22,8 +22,7 @@ public RuntimePseudoCustomAttributeData( Type attributeType, IList constructorArguments) { _attributeType = attributeType; - if (constructorArguments == null) - constructorArguments = Array.Empty(); + constructorArguments ??= Array.Empty(); _constructorArguments = new ReadOnlyCollection(constructorArguments); } diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/MethodInfos/RuntimeConstructorInfo.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/MethodInfos/RuntimeConstructorInfo.cs index 3550d71105014..22eb2a6276729 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/MethodInfos/RuntimeConstructorInfo.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/MethodInfos/RuntimeConstructorInfo.cs @@ -71,8 +71,7 @@ public sealed override ParameterInfo[] GetParametersNoCopy() [DebuggerGuidedStepThrough] public sealed override object Invoke(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture) { - if (parameters == null) - parameters = Array.Empty(); + parameters ??= Array.Empty(); MethodInvoker methodInvoker; try { @@ -167,11 +166,7 @@ protected MethodInvoker MethodInvoker { get { - if (_lazyMethodInvoker == null) - { - _lazyMethodInvoker = UncachedMethodInvoker; - } - return _lazyMethodInvoker; + return _lazyMethodInvoker ??= UncachedMethodInvoker; } } diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/MethodInfos/RuntimeMethodHelpers.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/MethodInfos/RuntimeMethodHelpers.cs index 4892116492429..f3377c9c32ec2 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/MethodInfos/RuntimeMethodHelpers.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/MethodInfos/RuntimeMethodHelpers.cs @@ -105,9 +105,9 @@ internal static string ComputeToString(MethodBase contextMethod, RuntimeTypeInfo { sb.Append(sep); sep = ","; - string? name = methodTypeArgument.InternalNameIfAvailable; - if (name == null) - name = Type.DefaultTypeNameWhenMissingMetadata; + string name = + methodTypeArgument.InternalNameIfAvailable ?? + Type.DefaultTypeNameWhenMissingMetadata; sb.Append(methodTypeArgument.Name); } sb.Append(']'); diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/MethodInfos/RuntimeMethodInfo.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/MethodInfos/RuntimeMethodInfo.cs index e9907db30eb9c..58b8427e7af3d 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/MethodInfos/RuntimeMethodInfo.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/MethodInfos/RuntimeMethodInfo.cs @@ -163,8 +163,7 @@ public sealed override ParameterInfo[] GetParametersNoCopy() [DebuggerGuidedStepThroughAttribute] public sealed override object? Invoke(object? obj, BindingFlags invokeAttr, Binder binder, object?[]? parameters, CultureInfo culture) { - if (parameters == null) - parameters = Array.Empty(); + parameters ??= Array.Empty(); MethodInvoker methodInvoker = this.MethodInvoker; object? result = methodInvoker.Invoke(obj, parameters, binder, invokeAttr, culture); System.Diagnostics.DebugAnnotations.PreviousCallContainsDebuggerStepInCode(); diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/MethodInfos/RuntimePlainConstructorInfo.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/MethodInfos/RuntimePlainConstructorInfo.cs index acd2980e29194..655b4fbfd51c2 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/MethodInfos/RuntimePlainConstructorInfo.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/MethodInfos/RuntimePlainConstructorInfo.cs @@ -78,8 +78,7 @@ public sealed override Type DeclaringType [DebuggerGuidedStepThrough] public sealed override object Invoke(BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture) { - if (parameters == null) - parameters = Array.Empty(); + parameters ??= Array.Empty(); // Most objects are allocated by NewObject and their constructors return "void". But in many frameworks, // there are "weird" cases (e.g. String) where the constructor must do both the allocation and initialization. diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/MethodInfos/RuntimeSyntheticConstructorInfo.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/MethodInfos/RuntimeSyntheticConstructorInfo.cs index 939535180b69e..187cbfcf06318 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/MethodInfos/RuntimeSyntheticConstructorInfo.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/MethodInfos/RuntimeSyntheticConstructorInfo.cs @@ -79,8 +79,7 @@ public sealed override int MetadataToken [DebuggerGuidedStepThrough] public sealed override object Invoke(BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture) { - if (parameters == null) - parameters = Array.Empty(); + parameters ??= Array.Empty(); object ctorAllocatedObject = this.MethodInvoker.Invoke(null, parameters, binder, invokeAttr, culture)!; System.Diagnostics.DebugAnnotations.PreviousCallContainsDebuggerStepInCode(); diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/PropertyInfos/RuntimePropertyInfo.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/PropertyInfos/RuntimePropertyInfo.cs index 440eb9487952d..0c0a91beb36bb 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/PropertyInfos/RuntimePropertyInfo.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/PropertyInfos/RuntimePropertyInfo.cs @@ -132,8 +132,7 @@ public sealed override MethodInfo GetMethod _lazyGetterInvoker = Getter.GetUncachedMethodInvoker(Array.Empty(), this); } - if (index == null) - index = Array.Empty(); + index ??= Array.Empty(); return _lazyGetterInvoker.Invoke(obj, index, binder, invokeAttr, culture); } diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/NativeFormat/NativeFormatRuntimeNamedTypeInfo.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/NativeFormat/NativeFormatRuntimeNamedTypeInfo.cs index 18c175185421f..3e351f102360e 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/NativeFormat/NativeFormatRuntimeNamedTypeInfo.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/NativeFormat/NativeFormatRuntimeNamedTypeInfo.cs @@ -294,9 +294,7 @@ private NamespaceChain NamespaceChain { get { - if (_lazyNamespaceChain == null) - _lazyNamespaceChain = new NamespaceChain(_reader, _typeDefinition.NamespaceDefinition); - return _lazyNamespaceChain; + return _lazyNamespaceChain ??= new NamespaceChain(_reader, _typeDefinition.NamespaceDefinition); } } diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeConstructedGenericTypeInfo.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeConstructedGenericTypeInfo.cs index a2a010de909ce..69779ae9b3ad8 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeConstructedGenericTypeInfo.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeConstructedGenericTypeInfo.cs @@ -185,8 +185,7 @@ public sealed override string ToString() } } // If all else fails, use the ToString() - it won't match the legacy CLR but with no metadata, we can't match it anyway. - if (genericTypeDefinitionString == null) - genericTypeDefinitionString = genericTypeDefinition.ToString(); + genericTypeDefinitionString ??= genericTypeDefinition.ToString(); // Now, append the generic type arguments. StringBuilder sb = new StringBuilder(); diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.BindingFlags.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.BindingFlags.cs index b796b6d2a1dee..b1631bb32d6dd 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.BindingFlags.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.BindingFlags.cs @@ -41,8 +41,7 @@ protected sealed override ConstructorInfo GetConstructorImpl(BindingFlags bindin if ((bindingAttr & BindingFlags.ExactBinding) != 0) return System.DefaultBinder.ExactBinding(candidates.ToArray(), types) as ConstructorInfo; - if (binder == null) - binder = DefaultBinder; + binder ??= DefaultBinder; return binder.SelectMethod(bindingAttr, candidates.ToArray(), types, modifiers) as ConstructorInfo; } @@ -108,8 +107,7 @@ private MethodInfo GetMethodImplCommon(string name, int genericParameterCount, B if (types.Length == 0 && candidates.Count == 1) return candidates[0]; - if (binder == null) - binder = DefaultBinder; + binder ??= DefaultBinder; return binder.SelectMethod(bindingAttr, candidates.ToArray(), types, modifiers) as MethodInfo; } @@ -175,8 +173,7 @@ protected sealed override PropertyInfo GetPropertyImpl(string name, BindingFlags if ((bindingAttr & BindingFlags.ExactBinding) != 0) return System.DefaultBinder.ExactPropertyBinding(candidates.ToArray(), returnType, types); - if (binder == null) - binder = DefaultBinder; + binder ??= DefaultBinder; return binder.SelectProperty(bindingAttr, candidates.ToArray(), returnType, types, modifiers); } diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.InvokeMember.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.InvokeMember.cs index aa845932759a3..e160ab54fca6f 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.InvokeMember.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.InvokeMember.cs @@ -72,8 +72,7 @@ internal abstract partial class RuntimeTypeInfo int argCnt = (providedArgs != null) ? providedArgs.Length : 0; #region Get a Binder - if (binder == null) - binder = DefaultBinder; + binder ??= DefaultBinder; #endregion @@ -375,11 +374,9 @@ internal abstract partial class RuntimeTypeInfo return finalist.Invoke(target, bindingFlags, binder, providedArgs, culture); } - if (finalists == null) - finalists = new MethodInfo[] { finalist }; + finalists ??= new MethodInfo[] { finalist }; - if (providedArgs == null) - providedArgs = Array.Empty(); + providedArgs ??= Array.Empty(); object? state = null; diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.cs index c52da3fb06481..618cfaab23179 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.cs @@ -741,11 +741,7 @@ internal void EstablishDebugName() if (_debugName == null) { _debugName = "Constructing..."; // Protect against any inadvertent reentrancy. - string debugName; - debugName = this.ToString(); - if (debugName == null) - debugName = ""; - _debugName = debugName; + _debugName = ToString() ?? ""; } return; } diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/CompilerServices/ClassConstructorRunner.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/CompilerServices/ClassConstructorRunner.cs index 6db9cb646f91a..21a52801cadc0 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/CompilerServices/ClassConstructorRunner.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/CompilerServices/ClassConstructorRunner.cs @@ -421,8 +421,7 @@ public static int MarkThreadAsBlocked(int managedThreadId, CctorHandle blockedOn #endif using (LockHolder.Hold(s_cctorGlobalLock)) { - if (s_blockingRecords == null) - s_blockingRecords = new BlockingRecord[Grow]; + s_blockingRecords ??= new BlockingRecord[Grow]; int found; for (found = 0; found < s_nextBlockingRecordIndex; found++) { diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/TypeLoaderExports.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/TypeLoaderExports.cs index b83792fd593ba..2d89aeb6fbfa2 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/TypeLoaderExports.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/TypeLoaderExports.cs @@ -30,9 +30,7 @@ public static unsafe void ActivatorCreateInstanceAny(ref object ptrToData, IntPt ptrToData = RuntimeImports.RhNewObject(pEEType); Entry entry = LookupInCache(s_cache, pEETypePtr, pEETypePtr); - if (entry == null) - { - entry = CacheMiss(pEETypePtr, pEETypePtr, + entry ??= CacheMiss(pEETypePtr, pEETypePtr, (IntPtr context, IntPtr signature, object contextObject, ref IntPtr auxResult) => { IntPtr result = RuntimeAugments.TypeLoaderCallbacks.TryGetDefaultConstructorForType(new RuntimeTypeHandle(new EETypePtr(context))); @@ -40,7 +38,6 @@ public static unsafe void ActivatorCreateInstanceAny(ref object ptrToData, IntPt result = RuntimeAugments.GetFallbackDefaultConstructor(); return result; }); - } RawCalliHelper.Call(entry.Result, ptrToData); } @@ -73,60 +70,42 @@ internal static void Initialize() public static IntPtr GenericLookup(IntPtr context, IntPtr signature) { Entry entry = LookupInCache(s_cache, context, signature); - if (entry == null) - { - entry = CacheMiss(context, signature); - } + entry ??= CacheMiss(context, signature); return entry.Result; } public static void GenericLookupAndCallCtor(object arg, IntPtr context, IntPtr signature) { Entry entry = LookupInCache(s_cache, context, signature); - if (entry == null) - { - entry = CacheMiss(context, signature); - } + entry ??= CacheMiss(context, signature); RawCalliHelper.Call(entry.Result, arg); } public static object GenericLookupAndAllocObject(IntPtr context, IntPtr signature) { Entry entry = LookupInCache(s_cache, context, signature); - if (entry == null) - { - entry = CacheMiss(context, signature); - } + entry ??= CacheMiss(context, signature); return RawCalliHelper.Call(entry.Result, entry.AuxResult); } public static object GenericLookupAndAllocArray(IntPtr context, IntPtr arg, IntPtr signature) { Entry entry = LookupInCache(s_cache, context, signature); - if (entry == null) - { - entry = CacheMiss(context, signature); - } + entry ??= CacheMiss(context, signature); return RawCalliHelper.Call(entry.Result, entry.AuxResult, arg); } public static void GenericLookupAndCheckArrayElemType(IntPtr context, object arg, IntPtr signature) { Entry entry = LookupInCache(s_cache, context, signature); - if (entry == null) - { - entry = CacheMiss(context, signature); - } + entry ??= CacheMiss(context, signature); RawCalliHelper.Call(entry.Result, entry.AuxResult, arg); } public static object GenericLookupAndCast(object arg, IntPtr context, IntPtr signature) { Entry entry = LookupInCache(s_cache, context, signature); - if (entry == null) - { - entry = CacheMiss(context, signature); - } + entry ??= CacheMiss(context, signature); return RawCalliHelper.Call(entry.Result, arg, entry.AuxResult); } @@ -160,12 +139,9 @@ public static unsafe IntPtr GetDelegateThunk(object delegateObj, int whichThunk) public static unsafe IntPtr GVMLookupForSlot(object obj, RuntimeMethodHandle slot) { Entry entry = LookupInCache(s_cache, (IntPtr)obj.GetMethodTable(), *(IntPtr*)&slot); - if (entry == null) - { - entry = CacheMiss((IntPtr)obj.GetMethodTable(), *(IntPtr*)&slot, + entry ??= CacheMiss((IntPtr)obj.GetMethodTable(), *(IntPtr*)&slot, (IntPtr context, IntPtr signature, object contextObject, ref IntPtr auxResult) => Internal.Runtime.CompilerServices.GenericVirtualMethodSupport.GVMLookupForSlot(new RuntimeTypeHandle(new EETypePtr(context)), *(RuntimeMethodHandle*)&signature)); - } return entry.Result; } @@ -173,13 +149,10 @@ public static unsafe IntPtr GVMLookupForSlot(object obj, RuntimeMethodHandle slo internal static unsafe IntPtr OpenInstanceMethodLookup(IntPtr openResolver, object obj) { Entry entry = LookupInCache(s_cache, (IntPtr)obj.GetMethodTable(), openResolver); - if (entry == null) - { - entry = CacheMiss((IntPtr)obj.GetMethodTable(), openResolver, + entry ??= CacheMiss((IntPtr)obj.GetMethodTable(), openResolver, (IntPtr context, IntPtr signature, object contextObject, ref IntPtr auxResult) => Internal.Runtime.CompilerServices.OpenMethodResolver.ResolveMethodWorker(signature, contextObject), obj); - } return entry.Result; } @@ -201,10 +174,7 @@ private static Entry LookupInCache(Entry[] cache, IntPtr context, IntPtr signatu internal static IntPtr RuntimeCacheLookupInCache(IntPtr context, IntPtr signature, RuntimeObjectFactory factory, object contextObject, out IntPtr auxResult) { Entry entry = LookupInCache(s_cache, context, signature); - if (entry == null) - { - entry = CacheMiss(context, signature, factory, contextObject); - } + entry ??= CacheMiss(context, signature, factory, contextObject); auxResult = entry.AuxResult; return entry.Result; } 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 b4eddbbffd996..3cf038c4b63e3 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 @@ -24,9 +24,7 @@ internal class Waiter private static Waiter GetWaiterForCurrentThread() { - Waiter waiter = t_waiterForCurrentThread; - if (waiter == null) - waiter = t_waiterForCurrentThread = new Waiter(); + Waiter waiter = t_waiterForCurrentThread ??= new Waiter(); waiter.signalled = false; return waiter; } @@ -68,8 +66,7 @@ private unsafe void AddWaiter(Waiter waiter) _waitersTail = waiter; - if (_waitersHead == null) - _waitersHead = waiter; + _waitersHead ??= waiter; } private unsafe void RemoveWaiter(Waiter waiter) diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/Win32ThreadPoolNativeOverlapped.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/Win32ThreadPoolNativeOverlapped.cs index 9f139af0ad1de..26f453b499f2f 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/Win32ThreadPoolNativeOverlapped.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/Win32ThreadPoolNativeOverlapped.cs @@ -145,8 +145,7 @@ private void SetData(IOCompletionCallback callback, object state, object pinData } else { - if (data._pinnedData == null) - data._pinnedData = new GCHandle[1]; + data._pinnedData ??= new GCHandle[1]; if (!data._pinnedData[0].IsAllocated) data._pinnedData[0] = GCHandle.Alloc(pinData, GCHandleType.Pinned); @@ -203,8 +202,7 @@ internal static unsafe void CompleteWithCallback(uint errorCode, uint bytesWritt // Get an args object from the per-thread cache. ExecutionContextCallbackArgs args = t_executionContextCallbackArgs; - if (args == null) - args = new ExecutionContextCallbackArgs(); + args ??= new ExecutionContextCallbackArgs(); t_executionContextCallbackArgs = null; diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/TypeLoadException.NativeAot.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/TypeLoadException.NativeAot.cs index 9ca654774c813..538f41116fd1f 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/TypeLoadException.NativeAot.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/TypeLoadException.NativeAot.cs @@ -14,8 +14,7 @@ internal TypeLoadException(string message, string typeName) private void SetMessageField() { - if (_message == null) - _message = SR.Arg_TypeLoadException; + _message ??= SR.Arg_TypeLoadException; } } } diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/WeakReference.NativeAot.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/WeakReference.NativeAot.cs index 090dac14df2c4..8833dc4bdcf45 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/WeakReference.NativeAot.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/WeakReference.NativeAot.cs @@ -80,12 +80,7 @@ public virtual object? Target if (default(IntPtr) == h) return null; - object? o = RuntimeImports.RhHandleGet(h); - - if (o == null) - { - o = TryGetComTarget(); - } + object? o = RuntimeImports.RhHandleGet(h) ?? TryGetComTarget(); // We want to ensure that if the target is live, then we will // return it to the user. We need to keep this WeakReference object diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/WeakReference.T.NativeAot.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/WeakReference.T.NativeAot.cs index ab5a5bdfa842a..70ed8886a5546 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/WeakReference.T.NativeAot.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/WeakReference.T.NativeAot.cs @@ -54,12 +54,7 @@ private T? Target if (default(IntPtr) == h) return default; - T? target = Unsafe.As(RuntimeImports.RhHandleGet(h)); - - if (target == null) - { - target = TryGetComTarget() as T; - } + T? target = Unsafe.As(RuntimeImports.RhHandleGet(h)) ?? TryGetComTarget() as T; // We want to ensure that the handle was still alive when we fetched the target, // so we double check m_handle here. Note that the reading of the handle diff --git a/src/coreclr/nativeaot/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/ExecutionEnvironmentImplementation.MappingTables.cs b/src/coreclr/nativeaot/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/ExecutionEnvironmentImplementation.MappingTables.cs index 7bbc2de4e88f1..ab242bd2af8fb 100644 --- a/src/coreclr/nativeaot/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/ExecutionEnvironmentImplementation.MappingTables.cs +++ b/src/coreclr/nativeaot/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/ExecutionEnvironmentImplementation.MappingTables.cs @@ -387,8 +387,7 @@ public sealed override MethodInvoker TryGetMethodInvoker(RuntimeTypeHandle decla // If we failed to get a MethodInvokeInfo for an exact method, or a canonically equivalent method, check if there is a universal canonically // equivalent entry that could be used (it will be much slower, and require a calling convention converter) - if (methodInvokeInfo == null) - methodInvokeInfo = TryGetMethodInvokeInfo(declaringTypeHandle, methodHandle, genericMethodTypeArgumentHandles, + methodInvokeInfo ??= TryGetMethodInvokeInfo(declaringTypeHandle, methodHandle, genericMethodTypeArgumentHandles, methodInfo, ref methodSignatureComparer, CanonicalFormKind.Universal); #endif diff --git a/src/coreclr/nativeaot/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/PayForPlayExperience/DiagnosticMappingTables.cs b/src/coreclr/nativeaot/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/PayForPlayExperience/DiagnosticMappingTables.cs index d09662aad9514..eca67f2164b23 100644 --- a/src/coreclr/nativeaot/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/PayForPlayExperience/DiagnosticMappingTables.cs +++ b/src/coreclr/nativeaot/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/PayForPlayExperience/DiagnosticMappingTables.cs @@ -111,17 +111,11 @@ public static string ConvertBackTickNameToNameWithReducerInputFormat(string type StringBuilder genericTypeName = new StringBuilder(); genericTypeName.Append(typeNameSansBackTick); genericTypeName.Append('<'); - if (genericParameterOffsets != null) - { - genericParameterOffsets.Add(genericTypeName.Length); - } + genericParameterOffsets?.Add(genericTypeName.Length); for (int i = 1; i < genericParameterCount; i++) { genericTypeName.Append(','); - if (genericParameterOffsets != null) - { - genericParameterOffsets.Add(genericTypeName.Length); - } + genericParameterOffsets?.Add(genericTypeName.Length); } genericTypeName.Append('>'); return genericTypeName.ToString(); diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TemplateLocator.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TemplateLocator.cs index e36e67a158bd8..ae07966087976 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TemplateLocator.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TemplateLocator.cs @@ -31,8 +31,7 @@ public static TypeDesc TryGetTypeTemplate(TypeDesc concreteType, ref NativeLayou TypeDesc result = TryGetTypeTemplate_Internal(concreteType, CanonicalFormKind.Specific, out nativeLayoutInfo.Module, out nativeLayoutInfo.Offset); // If not found, see if there's a universal canonical template - if (result == null) - result = TryGetUniversalTypeTemplate(concreteType, ref nativeLayoutInfo); + result ??= TryGetUniversalTypeTemplate(concreteType, ref nativeLayoutInfo); return result; #endif @@ -218,8 +217,7 @@ public static InstantiatedMethod TryGetGenericMethodTemplate(InstantiatedMethod InstantiatedMethod result = TryGetGenericMethodTemplate_Internal(concreteMethod, CanonicalFormKind.Specific, out nativeLayoutInfoModule, out nativeLayoutInfoToken); // If not found, see if there's a universal canonical template - if (result == null) - result = TryGetGenericMethodTemplate_Internal(concreteMethod, CanonicalFormKind.Universal, out nativeLayoutInfoModule, out nativeLayoutInfoToken); + result ??= TryGetGenericMethodTemplate_Internal(concreteMethod, CanonicalFormKind.Universal, out nativeLayoutInfoModule, out nativeLayoutInfoToken); return result; } diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilder.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilder.cs index 272fb6c4ad971..34c43edb3d4a7 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilder.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilder.cs @@ -183,8 +183,7 @@ public void RegisterForPreparation(TypeDesc type) if (type.IsCanonicalSubtype(CanonicalFormKind.Any)) return; - if (_typesThatNeedPreparation == null) - _typesThatNeedPreparation = new LowLevelList(); + _typesThatNeedPreparation ??= new LowLevelList(); _typesThatNeedPreparation.Add(type); } @@ -247,8 +246,7 @@ internal void PrepareType(TypeDesc type) if (hasTypeHandle) return; - if (state == null) - state = type.GetOrCreateTypeBuilderState(); + state ??= type.GetOrCreateTypeBuilderState(); // If this type was already prepared, do nothing unless we are re-preparing it for the purpose of loading the field layout if (state.HasBeenPrepared) @@ -1548,8 +1546,7 @@ private void FinishTypeAndMethodBuilding() newByRefTypesCount++; else if (typeAsParameterizedType.IsMdArray) { - if (mdArrayNewTypesCount == null) - mdArrayNewTypesCount = new int[MDArray.MaxRank + 1]; + mdArrayNewTypesCount ??= new int[MDArray.MaxRank + 1]; mdArrayNewTypesCount[((ArrayType)typeAsParameterizedType).Rank]++; } } diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilderState.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilderState.cs index 38b5971517fee..1e5bbecb5d75d 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilderState.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilderState.cs @@ -292,10 +292,7 @@ public bool HasDictionarySlotInVTable { get { - if (_hasDictionarySlotInVTable == null) - { - _hasDictionarySlotInVTable = ComputeHasDictionarySlotInVTable(); - } + _hasDictionarySlotInVTable ??= ComputeHasDictionarySlotInVTable(); return _hasDictionarySlotInVTable.Value; } } @@ -354,8 +351,7 @@ public bool HasDictionaryInVTable { get { - if (_hasDictionaryInVTable == null) - _hasDictionaryInVTable = ComputeHasDictionaryInVTable(); + _hasDictionaryInVTable ??= ComputeHasDictionaryInVTable(); return _hasDictionaryInVTable.Value; } } @@ -452,8 +448,7 @@ public ushort NumVTableSlots { get { - if (_numVTableSlots == null) - _numVTableSlots = ComputeNumVTableSlots(); + _numVTableSlots ??= ComputeNumVTableSlots(); return _numVTableSlots.Value; } @@ -614,8 +609,7 @@ public LowLevelList InstanceGCLayout TypeBuilder.GCLayout fieldGcLayout = GetFieldGCLayout(field.FieldType); if (!fieldGcLayout.IsNone) { - if (instanceGCLayout == null) - instanceGCLayout = new LowLevelList(); + instanceGCLayout ??= new LowLevelList(); fieldGcLayout.WriteToBitfield(instanceGCLayout, field.Offset.AsInt); } @@ -720,14 +714,12 @@ public void PrepareStaticGCLayout() LowLevelList gcLayoutInfo = null; if (field.IsThreadStatic) { - if (threadStaticLayout == null) - threadStaticLayout = new LowLevelList(); + threadStaticLayout ??= new LowLevelList(); gcLayoutInfo = threadStaticLayout; } else if (field.HasGCStaticBase) { - if (gcStaticLayout == null) - gcStaticLayout = new LowLevelList(); + gcStaticLayout ??= new LowLevelList(); gcLayoutInfo = gcStaticLayout; } else diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.cs index fb0b2d5105002..cc8da0cd995a5 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.cs @@ -356,8 +356,7 @@ internal static unsafe NativeReader GetNativeLayoutInfoReader(TypeManagerHandle { Debug.Assert(!moduleHandle.IsNull); - if (t_moduleNativeReaders == null) - t_moduleNativeReaders = new LowLevelDictionary(); + t_moduleNativeReaders ??= new LowLevelDictionary(); NativeReader result; if (t_moduleNativeReaders.TryGetValue(moduleHandle, out result)) diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/TypeSystem/RuntimeNoMetadataType.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/TypeSystem/RuntimeNoMetadataType.cs index a78e0a316aa05..3dad145f03c92 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/TypeSystem/RuntimeNoMetadataType.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/TypeSystem/RuntimeNoMetadataType.cs @@ -40,8 +40,7 @@ public NoMetadataType(TypeSystemContext context, RuntimeTypeHandle genericTypeDe _context = context; _genericTypeDefinition = genericTypeDefinition; _genericTypeDefinitionAsDefType = genericTypeDefinitionAsDefType; - if (_genericTypeDefinitionAsDefType == null) - _genericTypeDefinitionAsDefType = this; + _genericTypeDefinitionAsDefType ??= this; _instantiation = instantiation; // Instantiation must either be: diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/TypeSystem/TypeSystemContext.Runtime.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/TypeSystem/TypeSystemContext.Runtime.cs index 1f2b9cd01f000..08b444d0280fc 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/TypeSystem/TypeSystemContext.Runtime.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/TypeSystem/TypeSystemContext.Runtime.cs @@ -220,11 +220,9 @@ public TypeDesc ResolveRuntimeTypeHandle(RuntimeTypeHandle rtth) } else { - returnedType = TryGetMetadataBasedTypeFromRuntimeTypeHandle_Uncached(rtth); - if (returnedType == null) - { - returnedType = new NoMetadataType(this, rtth, null, Instantiation.Empty, rtth.GetHashCode()); - } + returnedType = + TryGetMetadataBasedTypeFromRuntimeTypeHandle_Uncached(rtth) ?? + new NoMetadataType(this, rtth, null, Instantiation.Empty, rtth.GetHashCode()); } // We either retrieved an existing DefType that is already registered with the runtime @@ -414,8 +412,7 @@ protected override MethodDesc CreateValueFromKey(RuntimeMethodKey key) internal MethodDesc ResolveRuntimeMethod(bool unboxingStub, DefType owningType, MethodNameAndSignature nameAndSignature, IntPtr functionPointer, bool usgFunctionPointer) { - if (_runtimeMethods == null) - _runtimeMethods = new RuntimeMethodKey.RuntimeMethodKeyHashtable(); + _runtimeMethods ??= new RuntimeMethodKey.RuntimeMethodKeyHashtable(); MethodDesc retVal = _runtimeMethods.GetOrCreateValue(new RuntimeMethodKey(unboxingStub, owningType, nameAndSignature)); @@ -443,8 +440,7 @@ public DefType ResolveGenericInstantiation(DefType typeDef, Instantiation argume if (typeAsMetadataType != null) return GetInstantiatedType(typeAsMetadataType, arguments); - if (_genericTypeInstances == null) - _genericTypeInstances = new LowLevelDictionary(); + _genericTypeInstances ??= new LowLevelDictionary(); GenericTypeInstanceKey key = new GenericTypeInstanceKey(typeDef, arguments); @@ -569,8 +565,7 @@ public virtual int LoadFactor /// internal void RegisterTypeForTypeSystemStateFlushing(TypeDesc type) { - if (_typesToFlushTypeSystemStateFrom == null) - _typesToFlushTypeSystemStateFrom = new LowLevelList(); + _typesToFlushTypeSystemStateFrom ??= new LowLevelList(); _typesToFlushTypeSystemStateFrom.Add(type); } @@ -646,7 +641,7 @@ internal static partial class TypeNameHelper public static T WithDebugName(this T type) where T : TypeDesc { #if DEBUG - if (type.DebugName == null) type.DebugName = type.ToString(); + type.DebugName ??= type.ToString(); #endif return type; } diff --git a/src/coreclr/tools/Common/TypeSystem/Common/MetadataType.MethodImpls.cs b/src/coreclr/tools/Common/TypeSystem/Common/MetadataType.MethodImpls.cs index b92ba0aa54588..faea42eea60ea 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/MetadataType.MethodImpls.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/MetadataType.MethodImpls.cs @@ -35,10 +35,7 @@ public MethodImplRecord[] VirtualMethodImplsForType { get { - if (_allVirtualMethodImplsForType == null) - { - _allVirtualMethodImplsForType = ComputeVirtualMethodImplsForType(); - } + _allVirtualMethodImplsForType ??= ComputeVirtualMethodImplsForType(); return _allVirtualMethodImplsForType; } diff --git a/src/libraries/Common/src/Interop/Android/System.Security.Cryptography.Native.Android/Interop.EcDsa.ImportExport.cs b/src/libraries/Common/src/Interop/Android/System.Security.Cryptography.Native.Android/Interop.EcDsa.ImportExport.cs index 369bdae0b6ce5..e731a47c39aa4 100644 --- a/src/libraries/Common/src/Interop/Android/System.Security.Cryptography.Native.Android/Interop.EcDsa.ImportExport.cs +++ b/src/libraries/Common/src/Interop/Android/System.Security.Cryptography.Native.Android/Interop.EcDsa.ImportExport.cs @@ -82,8 +82,7 @@ internal static SafeEcKeyHandle EcKeyCreateByExplicitCurve(ECCurve curve) if (key == null || key.IsInvalid) { - if (key != null) - key.Dispose(); + key?.Dispose(); throw new CryptographicException(); } diff --git a/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EcDsa.ImportExport.cs b/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EcDsa.ImportExport.cs index b70935b75cb42..0810e71a14d3c 100644 --- a/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EcDsa.ImportExport.cs +++ b/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EcDsa.ImportExport.cs @@ -84,8 +84,7 @@ internal static SafeEcKeyHandle EcKeyCreateByExplicitCurve(ECCurve curve) if (key == null || key.IsInvalid) { - if (key != null) - key.Dispose(); + key?.Dispose(); throw Interop.Crypto.CreateOpenSslCryptographicException(); } diff --git a/src/libraries/Common/src/Microsoft/Win32/SafeHandles/SafeInteriorHandle.cs b/src/libraries/Common/src/Microsoft/Win32/SafeHandles/SafeInteriorHandle.cs index f4ab32baba814..2c27022ec4bee 100644 --- a/src/libraries/Common/src/Microsoft/Win32/SafeHandles/SafeInteriorHandle.cs +++ b/src/libraries/Common/src/Microsoft/Win32/SafeHandles/SafeInteriorHandle.cs @@ -19,13 +19,12 @@ protected SafeInteriorHandle(IntPtr invalidHandleValue, bool ownsHandle) protected override bool ReleaseHandle() { SafeHandle? parent = _parent; - if (parent != null) { parent.DangerousRelease(); + _parent = null; } - _parent = null; SetHandle(IntPtr.Zero); return true; } diff --git a/src/libraries/Common/src/System/Data/ProviderBase/DbConnectionFactory.cs b/src/libraries/Common/src/System/Data/ProviderBase/DbConnectionFactory.cs index 6b5746444f8d9..9d4ae11d35337 100644 --- a/src/libraries/Common/src/System/Data/ProviderBase/DbConnectionFactory.cs +++ b/src/libraries/Common/src/System/Data/ProviderBase/DbConnectionFactory.cs @@ -47,10 +47,7 @@ public void ClearAllPools() foreach (KeyValuePair entry in connectionPoolGroups) { DbConnectionPoolGroup poolGroup = entry.Value; - if (null != poolGroup) - { - poolGroup.Clear(); - } + poolGroup?.Clear(); } } @@ -59,10 +56,7 @@ public void ClearPool(DbConnection connection) ADP.CheckArgumentNull(connection, nameof(connection)); DbConnectionPoolGroup? poolGroup = GetConnectionPoolGroup(connection); - if (null != poolGroup) - { - poolGroup.Clear(); - } + poolGroup?.Clear(); } public void ClearPool(DbConnectionPoolKey key) @@ -94,10 +88,7 @@ public void ClearPool(DbConnectionPoolKey key) DbConnectionPoolKey poolKey = poolGroup.PoolKey; DbConnectionInternal? newConnection = CreateConnection(connectionOptions, poolKey, poolGroupProviderInfo, null, owningConnection, userOptions); - if (null != newConnection) - { - newConnection.MakeNonPooledObject(owningConnection); - } + newConnection?.MakeNonPooledObject(owningConnection); return newConnection; } @@ -107,10 +98,7 @@ public void ClearPool(DbConnectionPoolKey key) DbConnectionPoolGroupProviderInfo poolGroupProviderInfo = pool.PoolGroup.ProviderInfo!; DbConnectionInternal? newConnection = CreateConnection(options, poolKey, poolGroupProviderInfo, pool, owningObject, userOptions); - if (null != newConnection) - { - newConnection.MakePooledConnection(pool); - } + newConnection?.MakePooledConnection(pool); return newConnection; } diff --git a/src/libraries/Common/src/System/Data/ProviderBase/DbConnectionInternal.cs b/src/libraries/Common/src/System/Data/ProviderBase/DbConnectionInternal.cs index 1103b6488733b..69a742094e738 100644 --- a/src/libraries/Common/src/System/Data/ProviderBase/DbConnectionInternal.cs +++ b/src/libraries/Common/src/System/Data/ProviderBase/DbConnectionInternal.cs @@ -284,11 +284,7 @@ internal void MakePooledConnection(DbConnectionPool connectionPool) internal void NotifyWeakReference(int message) { - DbReferenceCollection? referenceCollection = ReferenceCollection; - if (null != referenceCollection) - { - referenceCollection.Notify(message); - } + ReferenceCollection?.Notify(message); } internal virtual void OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) @@ -414,11 +410,7 @@ internal void PostPop(object newOwner) internal void RemoveWeakReference(object value) { - DbReferenceCollection? referenceCollection = ReferenceCollection; - if (null != referenceCollection) - { - referenceCollection.Remove(value); - } + ReferenceCollection?.Remove(value); } /// diff --git a/src/libraries/Common/src/System/Data/ProviderBase/DbMetaDataFactory.cs b/src/libraries/Common/src/System/Data/ProviderBase/DbMetaDataFactory.cs index 339387acffc0f..bbd6eefe88fdd 100644 --- a/src/libraries/Common/src/System/Data/ProviderBase/DbMetaDataFactory.cs +++ b/src/libraries/Common/src/System/Data/ProviderBase/DbMetaDataFactory.cs @@ -182,10 +182,7 @@ private DataTable ExecuteCommand(DataRow requestedCollectionRow, string?[]? rest } finally { - if (reader != null) - { - reader.Dispose(); - } + reader?.Dispose(); } return resultTable; } diff --git a/src/libraries/Common/src/System/Net/Security/Unix/SafeFreeSslCredentials.cs b/src/libraries/Common/src/System/Net/Security/Unix/SafeFreeSslCredentials.cs index de76466004b5d..c509a7c4c5b5e 100644 --- a/src/libraries/Common/src/System/Net/Security/Unix/SafeFreeSslCredentials.cs +++ b/src/libraries/Common/src/System/Net/Security/Unix/SafeFreeSslCredentials.cs @@ -97,15 +97,8 @@ public override bool IsInvalid protected override bool ReleaseHandle() { - if (_certHandle != null) - { - _certHandle.Dispose(); - } - - if (_certKeyHandle != null) - { - _certKeyHandle.Dispose(); - } + _certHandle?.Dispose(); + _certKeyHandle?.Dispose(); _isInvalid = true; return true; diff --git a/src/libraries/Common/src/System/Net/TlsStream.cs b/src/libraries/Common/src/System/Net/TlsStream.cs index 0d2319916c4f1..047253159127e 100644 --- a/src/libraries/Common/src/System/Net/TlsStream.cs +++ b/src/libraries/Common/src/System/Net/TlsStream.cs @@ -80,10 +80,7 @@ public override void Close() { base.Close(); - if (_sslStream != null) - { - _sslStream.Close(); - } + _sslStream?.Close(); } } } diff --git a/src/libraries/Common/src/System/Resources/ResourceWriter.cs b/src/libraries/Common/src/System/Resources/ResourceWriter.cs index c64aff3334c64..11804d9e317c6 100644 --- a/src/libraries/Common/src/System/Resources/ResourceWriter.cs +++ b/src/libraries/Common/src/System/Resources/ResourceWriter.cs @@ -241,10 +241,7 @@ private void Dispose(bool disposing) { Generate(); } - if (_output != null) - { - _output.Dispose(); - } + _output?.Dispose(); } _output = null!; diff --git a/src/libraries/Common/src/System/Security/Cryptography/DSAAndroid.cs b/src/libraries/Common/src/System/Security/Cryptography/DSAAndroid.cs index cca1119007a4b..7e2984cfad211 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/DSAAndroid.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/DSAAndroid.cs @@ -161,12 +161,7 @@ private void FreeKey() { if (_key != null && _key.IsValueCreated) { - SafeDsaHandle handle = _key.Value; - - if (handle != null) - { - handle.Dispose(); - } + _key.Value?.Dispose(); } } diff --git a/src/libraries/Common/src/System/Security/Cryptography/DSAOpenSsl.cs b/src/libraries/Common/src/System/Security/Cryptography/DSAOpenSsl.cs index 780291d85299e..4ecb5554b2284 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/DSAOpenSsl.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/DSAOpenSsl.cs @@ -165,12 +165,7 @@ private void FreeKey() { if (_key != null && _key.IsValueCreated) { - SafeDsaHandle handle = _key.Value; - - if (handle != null) - { - handle.Dispose(); - } + _key.Value?.Dispose(); } } diff --git a/src/libraries/Common/src/System/Security/Cryptography/RSASecurityTransforms.cs b/src/libraries/Common/src/System/Security/Cryptography/RSASecurityTransforms.cs index 9acbf03158c2a..15cc55a62bb74 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/RSASecurityTransforms.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/RSASecurityTransforms.cs @@ -556,11 +556,8 @@ protected override void Dispose(bool disposing) { if (disposing) { - if (_keys != null) - { - // Do not set _keys to null, in order to prevent rehydration. - _keys.Dispose(); - } + // Do not set _keys to null, in order to prevent rehydration. + _keys?.Dispose(); } base.Dispose(disposing); diff --git a/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationSection.cs b/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationSection.cs index c9c4c8baaf5be..2950f16bab5f7 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationSection.cs +++ b/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationSection.cs @@ -38,18 +38,9 @@ public ConfigurationSection(IConfigurationRoot root, string path) /// /// Gets the key this section occupies in its parent. /// - public string Key - { - get - { - if (_key == null) - { - // Key is calculated lazily as last portion of Path - _key = ConfigurationPath.GetSectionKey(_path); - } - return _key; - } - } + public string Key => + // Key is calculated lazily as last portion of Path + _key ??= ConfigurationPath.GetSectionKey(_path); /// /// Gets or sets the section value. diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/FileWrapper.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/FileWrapper.cs index f9a0f4bb9da15..346e52d4efe8d 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/FileWrapper.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/FileWrapper.cs @@ -39,11 +39,7 @@ public void CreateEmptyFile(string path) { try { - FileStream emptyFile = File.Create(path); - if (emptyFile != null) - { - emptyFile.Dispose(); - } + File.Create(path).Dispose(); } catch { } } diff --git a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/Patterns/PatternBuilder.cs b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/Patterns/PatternBuilder.cs index 12601f23829ea..18ea195ceef35 100644 --- a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/Patterns/PatternBuilder.cs +++ b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/Patterns/PatternBuilder.cs @@ -182,9 +182,9 @@ public IPattern Build(string pattern) segmentsPatternEndsWith = new List(); } } - else if (segmentsPatternEndsWith != null) + else { - segmentsPatternEndsWith.Add(segment); + segmentsPatternEndsWith?.Add(segment); } allSegments.Add(segment); diff --git a/src/libraries/Microsoft.Extensions.Options/src/OptionsMonitor.cs b/src/libraries/Microsoft.Extensions.Options/src/OptionsMonitor.cs index a736240557289..3c81c66ba49de 100644 --- a/src/libraries/Microsoft.Extensions.Options/src/OptionsMonitor.cs +++ b/src/libraries/Microsoft.Extensions.Options/src/OptionsMonitor.cs @@ -66,10 +66,7 @@ private void InvokeChanged(string? name) name ??= Options.DefaultName; _cache.TryRemove(name); TOptions options = Get(name); - if (_onChange != null) - { - _onChange.Invoke(options, name); - } + _onChange?.Invoke(options, name); } /// diff --git a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/BlockingCollection.cs b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/BlockingCollection.cs index 9834d8594a596..7a7737f71232a 100644 --- a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/BlockingCollection.cs +++ b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/BlockingCollection.cs @@ -438,10 +438,7 @@ private bool TryAddWithNoTimeValidation(T item, int millisecondsTimeout, Cancell } finally { - if (linkedTokenSource != null) - { - linkedTokenSource.Dispose(); - } + linkedTokenSource?.Dispose(); } } if (waitForSemaphoreWasSuccessful) @@ -495,10 +492,7 @@ private bool TryAddWithNoTimeValidation(T item, int millisecondsTimeout, Cancell { //TryAdd did not result in increasing the size of the underlying store and hence we need //to increment back the count of the _freeNodes semaphore. - if (_freeNodes != null) - { - _freeNodes.Release(); - } + _freeNodes?.Release(); throw; } if (addingSucceeded) @@ -1529,11 +1523,7 @@ protected virtual void Dispose(bool disposing) { if (!_isDisposed) { - if (_freeNodes != null) - { - _freeNodes.Dispose(); - } - + _freeNodes?.Dispose(); _occupiedNodes.Dispose(); _isDisposed = true; @@ -1643,24 +1633,12 @@ public IEnumerable GetConsumingEnumerable() /// If the is canceled. public IEnumerable GetConsumingEnumerable(CancellationToken cancellationToken) { - CancellationTokenSource? linkedTokenSource = null; - try + using CancellationTokenSource linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _consumersCancellationTokenSource.Token); + while (!IsCompleted) { - linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _consumersCancellationTokenSource.Token); - while (!IsCompleted) + if (TryTakeWithNoTimeValidation(out T? item, Timeout.Infinite, cancellationToken, linkedTokenSource)) { - T? item; - if (TryTakeWithNoTimeValidation(out item, Timeout.Infinite, cancellationToken, linkedTokenSource)) - { - yield return item; - } - } - } - finally - { - if (linkedTokenSource != null) - { - linkedTokenSource.Dispose(); + yield return item; } } } diff --git a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/OrderablePartitioner.cs b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/OrderablePartitioner.cs index 77a3356188173..964cf4a9f3746 100644 --- a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/OrderablePartitioner.cs +++ b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/OrderablePartitioner.cs @@ -229,11 +229,7 @@ IEnumerator IEnumerable.GetEnumerator() } public void Dispose() { - IDisposable? d = _source as IDisposable; - if (d != null) - { - d.Dispose(); - } + (_source as IDisposable)?.Dispose(); } } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary_2.HashBucket.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary_2.HashBucket.cs index 2562372c666b4..6a8031ce56733 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary_2.HashBucket.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary_2.HashBucket.cs @@ -327,10 +327,7 @@ internal bool TryGetKey(TKey equalKey, Comparers comparers, out TKey actualKey) /// internal void Freeze() { - if (_additionalElements != null) - { - _additionalElements.Freeze(); - } + _additionalElements?.Freeze(); } /// diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableHashSet_1.HashBucket.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableHashSet_1.HashBucket.cs index 04ca794da7808..c7e8c36ddd5c1 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableHashSet_1.HashBucket.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableHashSet_1.HashBucket.cs @@ -242,10 +242,7 @@ internal HashBucket Remove(T value, IEqualityComparer equalityComparer, out O /// internal void Freeze() { - if (_additionalElements != null) - { - _additionalElements.Freeze(); - } + _additionalElements?.Freeze(); } /// diff --git a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/HybridDictionary.cs b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/HybridDictionary.cs index 86e27dc0be802..04ca1c6aa4ce9 100644 --- a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/HybridDictionary.cs +++ b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/HybridDictionary.cs @@ -302,10 +302,8 @@ public IDictionaryEnumerator GetEnumerator() { return hashtable.GetEnumerator(); } - if (list == null) - { - list = new ListDictionary(caseInsensitive ? StringComparer.OrdinalIgnoreCase : null); - } + + list ??= new ListDictionary(caseInsensitive ? StringComparer.OrdinalIgnoreCase : null); return list.GetEnumerator(); } diff --git a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/OrderedDictionary.cs b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/OrderedDictionary.cs index 853c45a1a919b..b116fef6df53e 100644 --- a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/OrderedDictionary.cs +++ b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/OrderedDictionary.cs @@ -239,14 +239,8 @@ public void Clear() { throw new NotSupportedException(SR.OrderedDictionary_ReadOnly); } - if (_objectsTable != null) - { - _objectsTable.Clear(); - } - if (_objectsArray != null) - { - _objectsArray.Clear(); - } + _objectsTable?.Clear(); + _objectsArray?.Clear(); } /// diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportLifetimeContextOfT.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportLifetimeContextOfT.cs index fd0fce5ac6a5f..9712904a431ee 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportLifetimeContextOfT.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportLifetimeContextOfT.cs @@ -24,10 +24,7 @@ public T Value public void Dispose() { - if (_disposeAction != null) - { - _disposeAction.Invoke(); - } + _disposeAction?.Invoke(); } } } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ApplicationCatalog.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ApplicationCatalog.cs index bb70de3f475b2..c012630d055ef 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ApplicationCatalog.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ApplicationCatalog.cs @@ -117,10 +117,7 @@ protected override void Dispose(bool disposing) _innerCatalog = null; _isDisposed = true; } - if (innerCatalog != null) - { - innerCatalog.Dispose(); - } + innerCatalog?.Dispose(); } } finally diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AssemblyCatalog.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AssemblyCatalog.cs index 3eeb586b5f910..70fbe53ea3a51 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AssemblyCatalog.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AssemblyCatalog.cs @@ -514,10 +514,7 @@ protected override void Dispose(bool disposing) { if (disposing) { - if (_innerCatalog != null) - { - _innerCatalog.Dispose(); - } + _innerCatalog?.Dispose(); } } } 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 b7473205291fc..2884ae6c92c69 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 @@ -166,13 +166,10 @@ protected virtual void Dispose(bool disposing) } catch (Exception e) { - if (exceptions == null) - { - //If any exceptions leak through the actions we will swallow them for now - // complete processing the list - // and we will throw InvalidOperationException with an AggregateException as it's innerException - exceptions = new List(); - } + //If any exceptions leak through the actions we will swallow them for now + // complete processing the list + // and we will throw InvalidOperationException with an AggregateException as it's innerException + exceptions ??= new List(); exceptions.Add(e); } } @@ -205,12 +202,9 @@ private void FinalComplete() } catch (Exception e) { - if (exceptions == null) - { - //If any exceptions leak through the actions we will swallow them for now complete processing the list - // and we will throw InvalidOperationException with an AggregateException as it's innerException - exceptions = new List(); - } + //If any exceptions leak through the actions we will swallow them for now complete processing the list + // and we will throw InvalidOperationException with an AggregateException as it's innerException + exceptions ??= new List(); exceptions.Add(e); } } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.ScopeFactoryExport.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.ScopeFactoryExport.cs index 8c81e19816946..20aed9c4e4acd 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.ScopeFactoryExport.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.ScopeFactoryExport.cs @@ -66,10 +66,7 @@ public override ExportDefinition Definition export = null; } } - if (childContainer != null) - { - childContainer.Dispose(); - } + childContainer?.Dispose(); } return _export.Value; @@ -93,10 +90,7 @@ public void Dispose() } } - if (childContainer != null) - { - childContainer.Dispose(); - } + childContainer?.Dispose(); } } } 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 5bbf40e766c9f..7a0b7a7831065 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 @@ -190,10 +190,7 @@ public ExportProvider? SourceProvider { sourceProvider.ExportsChanging -= OnExportsChangingInternal; newImportEngine!.Dispose(); - if (aggregateExportProvider != null) - { - aggregateExportProvider.Dispose(); - } + aggregateExportProvider?.Dispose(); } } } @@ -256,20 +253,14 @@ protected virtual void Dispose(bool disposing) catalogToUnsubscribeFrom.Changing -= OnCatalogChanging; } - if (aggregateExportProvider != null) - { - aggregateExportProvider.Dispose(); - } + aggregateExportProvider?.Dispose(); if (sourceProvider != null) { sourceProvider.ExportsChanging -= OnExportsChangingInternal; } - if (importEngine != null) - { - importEngine.Dispose(); - } + importEngine?.Dispose(); if (partsToDispose != null) { @@ -509,10 +500,7 @@ private CatalogPart GetSharedPart(ComposablePartDefinition partDefinition) // if disposableNewPart != null, this means we have created a new instance of something disposable and not used it // Dispose of it now - if (disposableNewPart != null) - { - disposableNewPart.Dispose(); - } + disposableNewPart?.Dispose(); return catalogPart; } @@ -579,10 +567,7 @@ private void DisposePart(object? exportedValue, CatalogPart catalogPart, AtomicC importEngine = _importEngine; } - if (importEngine != null) - { - importEngine.ReleaseImports(catalogPart.Part, atomicComposition); - } + importEngine?.ReleaseImports(catalogPart.Part, atomicComposition); if (exportedValue != null) { atomicComposition.AddCompleteActionAllowNull(() => diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartExportProvider.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartExportProvider.cs index d16314d72b493..6c470aa2af93c 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartExportProvider.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartExportProvider.cs @@ -85,10 +85,7 @@ protected virtual void Dispose(bool disposing) } finally { - if (importEngine != null) - { - importEngine.Dispose(); - } + importEngine?.Dispose(); if (disposeLock) { @@ -170,10 +167,7 @@ private ImportEngine ImportEngine } // if we have created an engine and didn't set it because of a race condition, we need to dispose of it - if (importEngine != null) - { - importEngine.Dispose(); - } + importEngine?.Dispose(); } return _importEngine; diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionContainer.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionContainer.cs index f1b1b48eee402..7f3b1b21e33ee 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionContainer.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionContainer.cs @@ -354,35 +354,12 @@ protected virtual void Dispose(bool disposing) rootProvider.ExportsChanging -= OnExportsChangingInternal; } - if (disposableRootProvider != null) - { - disposableRootProvider.Dispose(); - } - - if (disposableAncestorExportProvider != null) - { - disposableAncestorExportProvider.Dispose(); - } - - if (disposableLocalExportProvider != null) - { - disposableLocalExportProvider.Dispose(); - } - - if (catalogExportProvider != null) - { - catalogExportProvider.Dispose(); - } - - if (partExportProvider != null) - { - partExportProvider.Dispose(); - } - - if (importEngine != null) - { - importEngine.Dispose(); - } + disposableRootProvider?.Dispose(); + disposableAncestorExportProvider?.Dispose(); + disposableLocalExportProvider?.Dispose(); + catalogExportProvider?.Dispose(); + partExportProvider?.Dispose(); + importEngine?.Dispose(); } } @@ -551,10 +528,7 @@ public void SatisfyImportsOnce(ComposablePart part) importEngine = null; } } - if (importEngine != null) - { - importEngine.Dispose(); - } + importEngine?.Dispose(); } _importEngine.SatisfyImportsOnce(part); } @@ -617,10 +591,7 @@ internal void OnExportsChangingInternal(object? sender, ExportsChangeEventArgs e _localExportProvider.TryGetExports(definition.RemoveImportSource(), atomicComposition, out exports); break; case ImportSource.NonLocal: - if (_ancestorExportProvider != null) - { - _ancestorExportProvider.TryGetExports(definition.RemoveImportSource(), atomicComposition, out exports); - } + _ancestorExportProvider?.TryGetExports(definition.RemoveImportSource(), atomicComposition, out exports); break; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionScopeDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionScopeDefinition.cs index 9a7cc2c700264..89ad9ff5a7479 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionScopeDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionScopeDefinition.cs @@ -223,11 +223,7 @@ internal IEnumerable> GetExpor /// The instance containing the event data. protected virtual void OnChanged(ComposablePartCatalogChangeEventArgs e) { - EventHandler? changedEvent = Changed; - if (changedEvent != null) - { - changedEvent.Invoke(this, e); - } + Changed?.Invoke(this, e); } /// @@ -236,11 +232,7 @@ protected virtual void OnChanged(ComposablePartCatalogChangeEventArgs e) /// The instance containing the event data. protected virtual void OnChanging(ComposablePartCatalogChangeEventArgs e) { - EventHandler? changingEvent = Changing; - if (changingEvent != null) - { - changingEvent.Invoke(this, e); - } + Changing?.Invoke(this, e); } private void OnChangedInternal(object? sender, ComposablePartCatalogChangeEventArgs e) diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/DirectoryCatalog.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/DirectoryCatalog.cs index ff8ea6d86b14d..54dc5b17d5c05 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/DirectoryCatalog.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/DirectoryCatalog.cs @@ -479,10 +479,7 @@ protected override void Dispose(bool disposing) } finally { - if (catalogs != null) - { - catalogs.Dispose(); - } + catalogs?.Dispose(); if (disposeLock) { diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.cs index 279fe06e3693c..f0de648f19812 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.cs @@ -115,10 +115,7 @@ public FilteredCatalog Complement } } - if (complement != null) - { - complement.Dispose(); - } + complement?.Dispose(); } return _complement; @@ -182,11 +179,7 @@ public override IEnumerable> G /// The instance containing the event data. protected virtual void OnChanged(ComposablePartCatalogChangeEventArgs e) { - EventHandler? changedEvent = Changed; - if (changedEvent != null) - { - changedEvent.Invoke(this, e); - } + Changed?.Invoke(this, e); } /// @@ -195,11 +188,7 @@ protected virtual void OnChanged(ComposablePartCatalogChangeEventArgs e) /// The instance containing the event data. protected virtual void OnChanging(ComposablePartCatalogChangeEventArgs e) { - EventHandler? changingEvent = Changing; - if (changingEvent != null) - { - changingEvent.Invoke(this, e); - } + Changing?.Invoke(this, e); } private void OnChangedInternal(object? sender, ComposablePartCatalogChangeEventArgs e) diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.PartManager.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.PartManager.cs index 64ba13fefb658..b04d37919e9d2 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.PartManager.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.PartManager.cs @@ -109,12 +109,9 @@ public void SetSavedImport(ImportDefinition import, Export[]? exports, AtomicCom public Export[]? GetSavedImport(ImportDefinition import) { Export[]? exports = null; - if (_importCache != null) - { - // We don't care about the return value we just want the exports - // and if it isn't present we just return the initialized null value - _importCache.TryGetValue(import, out exports); - } + // We don't care about the return value we just want the exports + // and if it isn't present we just return the initialized null value + _importCache?.TryGetValue(import, out exports); return exports; } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesigntimeLicenseContext.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesigntimeLicenseContext.cs index e5e4b48abbe7e..6db94b11f3946 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesigntimeLicenseContext.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesigntimeLicenseContext.cs @@ -78,12 +78,10 @@ private static string GetLocalPath(string fileName) string fileName = new FileInfo(location).Name; Stream? s = asm.GetManifestResourceStream(fileName + ".licenses"); - if (s == null) - { - // Since the casing may be different depending on how the assembly was loaded, - // we'll do a case insensitive lookup for this manifest resource stream... - s = CaseInsensitiveManifestResourceStreamLookup(asm, fileName + ".licenses"); - } + + // Since the casing may be different depending on how the assembly was loaded, + // we'll do a case insensitive lookup for this manifest resource stream... + s ??= CaseInsensitiveManifestResourceStreamLookup(asm, fileName + ".licenses"); if (s != null) { diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/PropertyDescriptor.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/PropertyDescriptor.cs index c6a6111408924..aab9b3f496c98 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/PropertyDescriptor.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/PropertyDescriptor.cs @@ -279,10 +279,7 @@ public virtual PropertyDescriptorCollection GetChildProperties(object? instance, // Now, if we failed to find it in our own attributes, go to the // component descriptor. - if (editor == null) - { - editor = TypeDescriptor.GetEditor(PropertyType, editorBaseType); - } + editor ??= TypeDescriptor.GetEditor(PropertyType, editorBaseType); // Now, another slot in our editor cache for next time if (_editorTypes == null) diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ApplicationSettingsBase.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ApplicationSettingsBase.cs index 9840347f66526..b27a4d2dc5d06 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ApplicationSettingsBase.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ApplicationSettingsBase.cs @@ -341,10 +341,7 @@ protected virtual void OnSettingsSaving(object sender, CancelEventArgs e) /// public void Reload() { - if (PropertyValues != null) - { - PropertyValues.Clear(); - } + PropertyValues?.Clear(); foreach (SettingsProperty sp in Properties) { @@ -363,11 +360,7 @@ public void Reset() { foreach (SettingsProvider provider in Providers) { - IApplicationSettingsProvider clientProv = provider as IApplicationSettingsProvider; - if (clientProv != null) - { - clientProv.Reset(Context); - } + (provider as IApplicationSettingsProvider)?.Reset(Context); } } @@ -434,11 +427,7 @@ public virtual void Upgrade() { foreach (SettingsProvider provider in Providers) { - IApplicationSettingsProvider clientProv = provider as IApplicationSettingsProvider; - if (clientProv != null) - { - clientProv.Upgrade(Context, GetPropertiesForProvider(provider)); - } + (provider as IApplicationSettingsProvider)?.Upgrade(Context, GetPropertiesForProvider(provider)); } } @@ -618,10 +607,7 @@ private SettingsProperty Initializer } else if (attr is SettingsGroupNameAttribute) { - if (_context == null) - { - _context = new SettingsContext(); - } + _context ??= new SettingsContext(); _context["GroupName"] = ((SettingsGroupNameAttribute)attr).GroupName; } else if (attr is SettingsProviderAttribute) diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/BaseConfigurationRecord.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/BaseConfigurationRecord.cs index 2874181ed71ff..cfecdaf110d58 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/BaseConfigurationRecord.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/BaseConfigurationRecord.cs @@ -716,12 +716,9 @@ private void RefreshFactoryRecord(string configKey) } // Add implicit sections to the factory list - if (factoryList == null) - { - // But if factoryList isn't found in this config, we still try to - // add implicit sections to an empty factoryList. - factoryList = new Hashtable(); - } + // But if factoryList isn't found in this config, we still try to + // add implicit sections to an empty factoryList. + factoryList ??= new Hashtable(); AddImplicitSections(factoryList); factoryRecord = (FactoryRecord)factoryList[configKey]; diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/LocalFileSettingsProvider.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/LocalFileSettingsProvider.cs index 828a35954bb9c..feb8b052e88ff 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/LocalFileSettingsProvider.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/LocalFileSettingsProvider.cs @@ -41,18 +41,7 @@ public override string ApplicationName /// /// We maintain a single instance of the ClientSettingsStore per instance of provider. /// - private ClientSettingsStore Store - { - get - { - if (_store == null) - { - _store = new ClientSettingsStore(); - } - - return _store; - } - } + private ClientSettingsStore Store => _store ??= new ClientSettingsStore(); /// /// Abstract ProviderBase method. diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DBCommandBuilder.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DBCommandBuilder.cs index fb642d1c21022..24b799981c4ee 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DBCommandBuilder.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DBCommandBuilder.cs @@ -1622,10 +1622,7 @@ private void RowUpdatingHandlerBuilder(RowUpdatingEventArgs rowUpdatingEvent) } if (null == command) { - if (null != datarow) - { - datarow.AcceptChanges(); - } + datarow?.AcceptChanges(); rowUpdatingEvent.Status = UpdateStatus.SkipCurrentRow; } rowUpdatingEvent.Command = command; diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbDataAdapter.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbDataAdapter.cs index 72163f26113a6..dee47399fcfe6 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbDataAdapter.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbDataAdapter.cs @@ -647,10 +647,7 @@ private int FillInternal(DataSet? dataset, DataTable[]? datatables, int startRec } finally { - if (null != dataReader) - { - dataReader.Dispose(); - } + dataReader?.Dispose(); } } finally diff --git a/src/libraries/System.Data.Common/src/System/Data/DBConcurrencyException.cs b/src/libraries/System.Data.Common/src/System/Data/DBConcurrencyException.cs index 1fd430e5ca10c..871fc6cd1b9de 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DBConcurrencyException.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DBConcurrencyException.cs @@ -70,11 +70,7 @@ public void CopyToRows(DataRow[] array) public void CopyToRows(DataRow[] array, int arrayIndex) { - DataRow[]? dataRows = _dataRows; - if (null != dataRows) - { - dataRows.CopyTo(array, arrayIndex); - } + _dataRows?.CopyTo(array, arrayIndex); } } } 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 1e2021a0bbaee..c3434d8ea7bae 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataColumn.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataColumn.cs @@ -379,20 +379,14 @@ public string ColumnName RaisePropertyChanging(nameof(ColumnName)); _columnName = value; _encodedColumnName = null; - if (_table != null) - { - _table.Columns.OnColumnPropertyChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, this)); - } + _table?.Columns.OnColumnPropertyChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, this)); } else if (_columnName != value) { RaisePropertyChanging(nameof(ColumnName)); _columnName = value; _encodedColumnName = null; - if (_table != null) - { - _table.Columns.OnColumnPropertyChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, this)); - } + _table?.Columns.OnColumnPropertyChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, this)); } } finally @@ -1806,10 +1800,7 @@ internal void SetStorage(object store, BitArray nullbits) internal void AddDependentColumn(DataColumn expressionColumn) { - if (_dependentColumns == null) - { - _dependentColumns = new List(); - } + _dependentColumns ??= new List(); Debug.Assert(!_dependentColumns.Contains(expressionColumn), "duplicate column - expected to be unique"); _dependentColumns.Add(expressionColumn); 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 15707b9c2ce27..5d9b8c4380094 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataColumnCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataColumnCollection.cs @@ -751,10 +751,7 @@ internal void FinishInitCollection() foreach (DataColumn? column in _delayedAddRangeColumns) { - if (column != null) - { - column.FinishInitInProgress(); - } + column?.FinishInitInProgress(); } _delayedAddRangeColumns = null; diff --git a/src/libraries/System.Data.Common/src/System/Data/DataRelation.cs b/src/libraries/System.Data.Common/src/System/Data/DataRelation.cs index d903c18763628..1a44717e6e5dc 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataRelation.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataRelation.cs @@ -484,10 +484,7 @@ public virtual bool Nested } Debug.Assert(ChildTable != null, "On a DataSet, but not on Table. Bad state"); ForeignKeyConstraint? constraint = ChildTable.Constraints.FindForeignKeyConstraint(ChildKey.ColumnsReference, ParentKey.ColumnsReference); - if (constraint != null) - { - constraint.CheckConstraint(); - } + constraint?.CheckConstraint(); ValidateMultipleNestedRelations(); } } 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 b38833e4a4f5c..d65d72bc111cd 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataSet.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataSet.cs @@ -3135,11 +3135,7 @@ protected internal virtual void OnRemoveTable(DataTable table) { } internal void OnRemovedTable(DataTable table) { - DataViewManager? viewManager = _defaultViewManager; - if (null != viewManager) - { - viewManager.DataViewSettings.Remove(table); - } + _defaultViewManager?.DataViewSettings.Remove(table); } /// 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 a5cc7cb15c06e..eba3f6acd109b 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataTable.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataTable.cs @@ -2833,8 +2833,7 @@ internal void Clear(bool clearAll) Debug.Assert(null == _rowDiffId, "wasn't previously cleared"); _rowDiffId = null; - if (_dataSet != null) - _dataSet.OnClearFunctionCalled(this); + _dataSet?.OnClearFunctionCalled(this); bool shouldFireClearEvents = (Rows.Count != 0); // if Rows is already empty, this is noop DataTableClearEventArgs? e = null; @@ -4610,10 +4609,7 @@ public void BeginLoadData() { _loadIndex = _primaryKey.Key.GetSortIndex(DataViewRowState.OriginalRows); } - if (_loadIndex != null) - { - _loadIndex.AddRef(); - } + _loadIndex?.AddRef(); } if (DataSet != null) @@ -4642,18 +4638,9 @@ public void EndLoadData() return; } - if (_loadIndex != null) - { - _loadIndex.RemoveRef(); - } - if (_loadIndexwithOriginalAdded != null) - { - _loadIndexwithOriginalAdded.RemoveRef(); - } - if (_loadIndexwithCurrentDeleted != null) - { - _loadIndexwithCurrentDeleted.RemoveRef(); - } + _loadIndex?.RemoveRef(); + _loadIndexwithOriginalAdded?.RemoveRef(); + _loadIndexwithCurrentDeleted?.RemoveRef(); _loadIndex = null; _loadIndexwithOriginalAdded = null; @@ -4758,10 +4745,7 @@ public DataRow LoadDataRow(object?[] values, LoadOption loadOption) { _loadIndexwithCurrentDeleted = _primaryKey.Key.GetSortIndex(DataViewRowState.CurrentRows | DataViewRowState.Deleted); Debug.Assert(_loadIndexwithCurrentDeleted != null, "loadIndexwithCurrentDeleted should not be null"); - if (_loadIndexwithCurrentDeleted != null) - { - _loadIndexwithCurrentDeleted.AddRef(); - } + _loadIndexwithCurrentDeleted?.AddRef(); } indextoUse = _loadIndexwithCurrentDeleted; } @@ -4772,10 +4756,7 @@ public DataRow LoadDataRow(object?[] values, LoadOption loadOption) { _loadIndexwithOriginalAdded = _primaryKey.Key.GetSortIndex(DataViewRowState.OriginalRows | DataViewRowState.Added); Debug.Assert(_loadIndexwithOriginalAdded != null, "loadIndexwithOriginalAdded should not be null"); - if (_loadIndexwithOriginalAdded != null) - { - _loadIndexwithOriginalAdded.AddRef(); - } + _loadIndexwithOriginalAdded?.AddRef(); } indextoUse = _loadIndexwithOriginalAdded; } @@ -6872,8 +6853,7 @@ internal void Cleanup() #if DEBUG // cannot assert that table exists in the usedTables - new tables might be // created during diffgram processing in DataSet.ReadXml. - if (RowDiffIdUsageSection.t_usedTables != null) - RowDiffIdUsageSection.t_usedTables.Remove(table); + RowDiffIdUsageSection.t_usedTables?.Remove(table); #endif table._rowDiffId = null; } diff --git a/src/libraries/System.Data.Common/src/System/Data/DataTableReader.cs b/src/libraries/System.Data.Common/src/System/Data/DataTableReader.cs index b37c297550354..0a43cab1ea419 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataTableReader.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataTableReader.cs @@ -91,10 +91,7 @@ private bool IsSchemaChanged } _schemaIsChanged = value; - if (_listener != null) - { - _listener.CleanUp(); - } + _listener?.CleanUp(); } } @@ -121,10 +118,7 @@ public override void Close() } // no need to listen to events after close - if (_listener != null) - { - _listener.CleanUp(); - } + _listener?.CleanUp(); _listener = null!; _schemaTable = null; @@ -187,10 +181,7 @@ public override bool Read() if (_rowCounter >= _currentDataTable.Rows.Count - 1) { _reachEORows = true; - if (_listener != null) - { - _listener.CleanUp(); - } + _listener?.CleanUp(); return false; } @@ -204,10 +195,7 @@ public override bool Read() if (_rowCounter == _currentDataTable.Rows.Count) { _reachEORows = true; - if (_listener != null) - { - _listener.CleanUp(); - } + _listener?.CleanUp(); return false; } ValidateRow(_rowCounter); diff --git a/src/libraries/System.Data.Common/src/System/Data/DataView.cs b/src/libraries/System.Data.Common/src/System/Data/DataView.cs index 6f165eb57522a..cb9f787d3caaa 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataView.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataView.cs @@ -311,10 +311,7 @@ public virtual string? RowFilter [RequiresUnreferencedCode(Select.RequiresUnreferencedCodeMessage)] set { - if (value == null) - { - value = string.Empty; - } + value ??= string.Empty; DataCommonEventSource.Log.Trace(" {0}, '{1}'", ObjectID, value); if (_fInitInProgress) @@ -427,10 +424,7 @@ public string Sort } set { - if (value == null) - { - value = string.Empty; - } + value ??= string.Empty; DataCommonEventSource.Log.Trace(" {0}, '{1}'", ObjectID, value); if (_fInitInProgress) @@ -914,10 +908,7 @@ void IList.Remove(object? value) internal Index? GetFindIndex(string column, bool keepIndex) { - if (_findIndexes == null) - { - _findIndexes = new Dictionary(); - } + _findIndexes ??= new Dictionary(); Index? findIndex; if (_findIndexes.TryGetValue(column, out findIndex)) 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 36d3e682774c7..500029b89e698 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Merger.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Merger.cs @@ -163,10 +163,7 @@ internal void MergeTable(DataTable src) _dataSet.Tables[src.TableName, src.Namespace]; } - if (dt != null) - { - dt.EvaluateExpressions(); - } + dt?.EvaluateExpressions(); if (!_isStandAlonetable) { @@ -282,10 +279,7 @@ internal void MergeRows(DataRow[] rows) // Getting our own copy instead. ndxSearch = dst.primaryKey.Key.GetSortIndex(); // IMO, Better would be to reuse index // ndxSearch = dst.primaryKey.Key.GetSortIndex(DataViewRowState.OriginalRows | DataViewRowState.Added ); - if (null != ndxSearch) - { - ndxSearch.RemoveRef(); - } + ndxSearch?.RemoveRef(); ndxSearch = new Index(dst, dst._primaryKey!.Key.GetIndexDesc(), DataViewRowState.OriginalRows | DataViewRowState.Added, null); ndxSearch.AddRef(); // need to addref twice, otherwise it will be collected ndxSearch.AddRef(); // in past first adref was done in const @@ -310,10 +304,7 @@ internal void MergeRows(DataRow[] rows) targetRow.Table.EvaluateExpressions(targetRow, DataRowAction.Change, null); } } - if (null != ndxSearch) - { - ndxSearch.RemoveRef(); - } + ndxSearch?.RemoveRef(); _dataSet.EnforceConstraints = fEnforce; } diff --git a/src/libraries/System.Data.Common/src/System/Data/ProviderBase/SchemaMapping.cs b/src/libraries/System.Data.Common/src/System/Data/ProviderBase/SchemaMapping.cs index 9d2b2dfb615f5..6faaf9b30ffbf 100644 --- a/src/libraries/System.Data.Common/src/System/Data/ProviderBase/SchemaMapping.cs +++ b/src/libraries/System.Data.Common/src/System/Data/ProviderBase/SchemaMapping.cs @@ -548,21 +548,12 @@ private static void RollbackAddedItems(List? items) DataColumn? column = (items[i] as DataColumn); if (null != column) { - if (null != column.Table) - { - column.Table.Columns.Remove(column); - } + column.Table?.Columns.Remove(column); } else { DataTable? table = (items[i] as DataTable); - if (null != table) - { - if (null != table.DataSet) - { - table.DataSet.Tables.Remove(table); - } - } + table?.DataSet?.Tables.Remove(table); } } } diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SqlXml.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SqlXml.cs index fb4d7293e974e..6f295f0cd04dc 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SqlXml.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SqlXml.cs @@ -486,8 +486,7 @@ public override void SetLength(long value) public override void Flush() { - if (_stream != null) - _stream.Flush(); + _stream?.Flush(); } protected override void Dispose(bool disposing) diff --git a/src/libraries/System.Data.Common/src/System/Data/XmlToDatasetMap.cs b/src/libraries/System.Data.Common/src/System/Data/XmlToDatasetMap.cs index c66e8f522a540..d14461c2d67e9 100644 --- a/src/libraries/System.Data.Common/src/System/Data/XmlToDatasetMap.cs +++ b/src/libraries/System.Data.Common/src/System/Data/XmlToDatasetMap.cs @@ -396,19 +396,14 @@ private void BuildIdentityMap(XmlNameTable nameTable, DataTable dataTable) // Handle namespaces and names as usuall string _tableLocalName = XmlConvert.EncodeLocalName(r.ChildTable.TableName); - string? tableLocalName = nameTable.Get(_tableLocalName); - if (tableLocalName == null) - { - tableLocalName = nameTable.Add(_tableLocalName); - } - - string? tableNamespace = nameTable.Get(r.ChildTable.Namespace); + string? tableLocalName = + nameTable.Get(_tableLocalName) ?? + nameTable.Add(_tableLocalName); - if (tableNamespace == null) - { - tableNamespace = nameTable.Add(r.ChildTable.Namespace); - } + string? tableNamespace = + nameTable.Get(r.ChildTable.Namespace) ?? + nameTable.Add(r.ChildTable.Namespace); XmlNodeIdentety idTable = new XmlNodeIdentety(tableLocalName, tableNamespace); tableSchemaInfo.ColumnsSchemaMap[idTable] = r.ChildTable; diff --git a/src/libraries/System.Data.Common/src/System/Xml/XmlBoundElement.cs b/src/libraries/System.Data.Common/src/System/Xml/XmlBoundElement.cs index 92a6a510a9f36..a0410ff912a97 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/XmlBoundElement.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/XmlBoundElement.cs @@ -225,10 +225,7 @@ internal ElementState ElementState internal void Foliate(ElementState newState) { XmlDataDocument doc = (XmlDataDocument)OwnerDocument; - if (doc != null) - { - doc.Foliate(this, newState); - } + doc?.Foliate(this, newState); } // Foliate the node as a side effect of user calling functions on this node (like NextSibling) OR as a side effect of DataDocNav using nodes to do editing @@ -236,10 +233,7 @@ internal void Foliate(ElementState newState) private void AutoFoliate() { XmlDataDocument doc = (XmlDataDocument)OwnerDocument; - if (doc != null) - { - doc.Foliate(this, doc.AutoFoliationState); - } + doc?.Foliate(this, doc.AutoFoliationState); } public override XmlNode CloneNode(bool deep) @@ -416,10 +410,7 @@ private static void WriteTo(DataPointer dp, XmlWriter w) default: Debug.Assert(((IXmlDataVirtualNode)dp).IsOnColumn(null)); - if (dp.GetNode() != null) - { - dp.GetNode().WriteTo(w); - } + dp.GetNode()?.WriteTo(w); break; } } 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 5bd3410dbc372..6d498e08fe107 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/XmlDataDocument.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/XmlDataDocument.cs @@ -2261,8 +2261,7 @@ private void OnUndeleteRow(DataRow row, XmlElement rowElement) XmlElement parent; // make certain we weren't place somewhere else. - if (rowElement.ParentNode != null) - rowElement.ParentNode.RemoveChild(rowElement); + rowElement.ParentNode?.RemoveChild(rowElement); // Find the parent of RowNode to be inserted DataRow? parentRowInRelation = GetNestedParent(row); @@ -2293,8 +2292,7 @@ private void PromoteChild(XmlNode child, XmlNode prevSibling) // Should not insert after docElem node Debug.Assert(prevSibling != DocumentElement); - if (child.ParentNode != null) - child.ParentNode.RemoveChild(child); + child.ParentNode?.RemoveChild(child); Debug.Assert(child.ParentNode == null); prevSibling.ParentNode.InsertAfter(child, prevSibling); @@ -2531,8 +2529,7 @@ private void SynchronizeRowFromRowElementEx(XmlBoundElement rowElement, ArrayLis XmlBoundElement? be = e as XmlBoundElement; if (be != null && be.Row != null) { - if (rowElemList != null) - rowElemList.Add(e); + rowElemList?.Add(e); // Skip over sub-regions fMore = iter.NextRight(); continue; diff --git a/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionPool.cs b/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionPool.cs index c251760b9ff7c..70354e2947d53 100644 --- a/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionPool.cs +++ b/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionPool.cs @@ -354,12 +354,7 @@ internal void Clear() for (int i = 0; i < count; ++i) { - obj = _objectList[i]; - - if (null != obj) - { - obj.DoNotPoolThisConnection(); - } + _objectList[i]?.DoNotPoolThisConnection(); } } @@ -574,10 +569,7 @@ private void ErrorCallback(object? state) // the error state is cleaned, destroy the timer to avoid periodic invocation Timer? t = _errorTimer; _errorTimer = null; - if (t != null) - { - t.Dispose(); // Cancel timer request. - } + t?.Dispose(); // Cancel timer request. } @@ -1141,10 +1133,7 @@ internal void Shutdown() // deactivate timer callbacks Timer? t = _cleanupTimer; _cleanupTimer = null; - if (null != t) - { - t.Dispose(); - } + t?.Dispose(); } 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 0b62490f385da..9ac612ac2292a 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 @@ -499,10 +499,7 @@ private void CloseCommandWrapper() { wrapper.Dispose(); - if (null != _connection) - { - _connection.RemoveWeakReference(this); - } + _connection?.RemoveWeakReference(this); } finally { @@ -690,10 +687,7 @@ private OdbcDataReader ExecuteReaderObject(CommandBehavior behavior, if (null == parameterBuffer || parameterBuffer.Length < parameterBufferSize) { - if (null != parameterBuffer) - { - parameterBuffer.Dispose(); - } + parameterBuffer?.Dispose(); parameterBuffer = new CNativeBuffer(parameterBufferSize); _cmdWrapper._nativeParameterBuffer = parameterBuffer; } @@ -835,10 +829,7 @@ private OdbcDataReader ExecuteReaderObject(CommandBehavior behavior, if (null != localReader) { // clear bindings so we don't grab output parameters on a failed execute - if (null != _parameterCollection) - { - _parameterCollection.ClearBindings(); - } + _parameterCollection?.ClearBindings(); ((IDisposable)localReader).Dispose(); } if (ConnectionState.Closed != _cmdState) @@ -1059,10 +1050,7 @@ internal void Dispose() CNativeBuffer? buffer = _nativeParameterBuffer; _nativeParameterBuffer = null; - if (null != buffer) - { - buffer.Dispose(); - } + buffer?.Dispose(); _ssKeyInfoModeOn = false; _ssKeyInfoModeOff = false; } diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnection.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnection.cs index cf23b502df4d8..3e3ae94e9cd1f 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnection.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnection.cs @@ -527,10 +527,7 @@ private int GetInfoInt32Unhandled(ODBC32.SQL_INFO infotype) } default: OdbcException e = OdbcException.CreateException(ODBC32.GetDiagErrors(null, hrHandle, retcode), retcode); - if (e != null) - { - e.Errors.SetSource(this.Driver); - } + e?.Errors.SetSource(this.Driver); ConnectionIsAlive(e); // this will close and throw if the connection is dead return e; } 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 8a978df0eb052..4b6b3076bb05f 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 @@ -97,11 +97,7 @@ protected override DbMetaDataFactory CreateMetaDataFactory(DbConnectionInternal internal override void PermissionDemand(DbConnection outerConnection) { - OdbcConnection? c = (outerConnection as OdbcConnection); - if (null != c) - { - c.PermissionDemand(); - } + (outerConnection as OdbcConnection)?.PermissionDemand(); } internal override void SetConnectionPoolGroup(DbConnection outerConnection, DbConnectionPoolGroup poolGroup) @@ -115,11 +111,7 @@ internal override void SetConnectionPoolGroup(DbConnection outerConnection, DbCo internal override void SetInnerConnectionEvent(DbConnection owningObject, DbConnectionInternal to) { - OdbcConnection? c = (owningObject as OdbcConnection); - if (null != c) - { - c.SetInnerConnectionEvent(to); - } + (owningObject as OdbcConnection)?.SetInnerConnectionEvent(to); } internal override bool SetInnerConnectionFrom(DbConnection owningObject, DbConnectionInternal to, DbConnectionInternal from) @@ -134,11 +126,7 @@ internal override bool SetInnerConnectionFrom(DbConnection owningObject, DbConne internal override void SetInnerConnectionTo(DbConnection owningObject, DbConnectionInternal to) { - OdbcConnection? c = (owningObject as OdbcConnection); - if (null != c) - { - c.SetInnerConnectionTo(to); - } + (owningObject as OdbcConnection)?.SetInnerConnectionTo(to); } } } diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataReader.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataReader.cs index ef5bc0b4856f7..3165e2001d304 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataReader.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataReader.cs @@ -361,9 +361,9 @@ private void Close(bool disposing) Connection.Close(); } } - else if (null != wrapper) + else { - wrapper.Dispose(); + wrapper?.Dispose(); } _command = null; diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcHandle.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcHandle.cs index cdf45ca1dc517..38b8125a6119a 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcHandle.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcHandle.cs @@ -165,9 +165,9 @@ protected override bool ReleaseHandle() // If we ended up getting released, then we have to release // our reference on our parent. OdbcHandle? parentHandle = _parentHandle; - _parentHandle = null; - if (null != parentHandle) + if (parentHandle != null) { + _parentHandle = null; parentHandle.DangerousRelease(); } return true; diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcMetaDataFactory.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcMetaDataFactory.cs index ec4652c496bae..324cd75c619ad 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcMetaDataFactory.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcMetaDataFactory.cs @@ -549,14 +549,8 @@ private static DataTable GetColumnsCollection(string?[]? restrictions, OdbcConne finally { - if (dataReader != null) - { - dataReader.Dispose(); - }; - if (command != null) - { - command.Dispose(); - }; + dataReader?.Dispose();; + command?.Dispose();; } return resultTable; } @@ -817,14 +811,8 @@ private DataTable GetDataTypesCollection(string?[]? restrictions, OdbcConnection finally { - if (dataReader != null) - { - dataReader.Dispose(); - }; - if (command != null) - { - command.Dispose(); - }; + dataReader?.Dispose();; + command?.Dispose();; } dataTypesTable.AcceptChanges(); return dataTypesTable; @@ -872,14 +860,8 @@ private static DataTable GetIndexCollection(string?[]? restrictions, OdbcConnect finally { - if (dataReader != null) - { - dataReader.Dispose(); - }; - if (command != null) - { - command.Dispose(); - }; + dataReader?.Dispose();; + command?.Dispose();; } return resultTable; } @@ -915,14 +897,8 @@ private static DataTable GetProcedureColumnsCollection(string?[]? restrictions, finally { - if (dataReader != null) - { - dataReader.Dispose(); - }; - if (command != null) - { - command.Dispose(); - }; + dataReader?.Dispose();; + command?.Dispose();; } return resultTable; } @@ -977,14 +953,8 @@ private static DataTable GetProceduresCollection(string?[]? restrictions, OdbcCo finally { - if (dataReader != null) - { - dataReader.Dispose(); - }; - if (command != null) - { - command.Dispose(); - }; + dataReader?.Dispose();; + command?.Dispose();; } return resultTable; } @@ -1067,14 +1037,8 @@ private static DataTable GetTablesCollection(string?[]? restrictions, OdbcConnec finally { - if (dataReader != null) - { - dataReader.Dispose(); - }; - if (command != null) - { - command.Dispose(); - }; + dataReader?.Dispose();; + command?.Dispose();; } return resultTable; } diff --git a/src/libraries/System.Data.OleDb/src/ColumnBinding.cs b/src/libraries/System.Data.OleDb/src/ColumnBinding.cs index 0e5c8083aa100..a55b6b9e065cb 100644 --- a/src/libraries/System.Data.OleDb/src/ColumnBinding.cs +++ b/src/libraries/System.Data.OleDb/src/ColumnBinding.cs @@ -206,10 +206,7 @@ internal void ResetValue() StringMemHandle? sptr = _sptr; _sptr = null; - if (null != sptr) - { - sptr.Dispose(); - } + sptr?.Dispose(); if (_pinnedBuffer.IsAllocated) { diff --git a/src/libraries/System.Data.OleDb/src/DbBindings.cs b/src/libraries/System.Data.OleDb/src/DbBindings.cs index f5d0fd868f2cf..6adc44a01e5eb 100644 --- a/src/libraries/System.Data.OleDb/src/DbBindings.cs +++ b/src/libraries/System.Data.OleDb/src/DbBindings.cs @@ -353,21 +353,14 @@ internal void CleanupBindings() ColumnBinding[] columnBindings = this.ColumnBindings(); for (int i = 0; i < columnBindings.Length; ++i) { - ColumnBinding binding = columnBindings[i]; - if (null != binding) - { - binding.ResetValue(); - } + columnBindings[i]?.ResetValue(); } } } internal void CloseFromConnection() { - if (null != _rowBinding) - { - _rowBinding.CloseFromConnection(); - } + _rowBinding?.CloseFromConnection(); Dispose(); } @@ -386,10 +379,7 @@ public void Dispose() RowBinding? rowBinding = _rowBinding; _rowBinding = null; - if (null != rowBinding) - { - rowBinding.Dispose(); - } + rowBinding?.Dispose(); } internal void GuidKindName(Guid guid, int eKind, IntPtr propid) diff --git a/src/libraries/System.Data.OleDb/src/OleDbCommand.cs b/src/libraries/System.Data.OleDb/src/OleDbCommand.cs index 91049ef703971..30e68314fb65e 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbCommand.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbCommand.cs @@ -563,10 +563,7 @@ private void CloseInternalParameters() Debug.Assert(null != _connection, "no connection, CloseInternalParameters"); Bindings? bindings = _dbBindings; _dbBindings = null; - if (null != bindings) - { - bindings.Dispose(); - } + bindings?.Dispose(); } public new OleDbParameter CreateParameter() @@ -1125,11 +1122,7 @@ private string ExpandStoredProcedureToText(string sproctext) private void ParameterCleanup() { - Bindings? bindings = ParameterBindings; - if (null != bindings) - { - bindings.CleanupBindings(); - } + ParameterBindings?.CleanupBindings(); } private bool InitializeCommand(CommandBehavior behavior, bool throwifnotsupported) diff --git a/src/libraries/System.Data.OleDb/src/OleDbConnection.cs b/src/libraries/System.Data.OleDb/src/OleDbConnection.cs index ee8c19c2e2a23..6ca1c0fab4e46 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbConnection.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbConnection.cs @@ -600,9 +600,9 @@ internal bool SupportSchemaRowset(Guid schema) ResetState(connection); } - else if (null != connection) + else { - connection.OnInfoMessage(errorInfo, hresult); + connection?.OnInfoMessage(errorInfo, hresult); } } finally @@ -637,10 +637,7 @@ public static void ReleaseObjectPool() private static void ResetState(OleDbConnection? connection) { - if (null != connection) - { - connection.ResetState(); - } + connection?.ResetState(); } } } diff --git a/src/libraries/System.Data.OleDb/src/OleDbConnectionFactory.cs b/src/libraries/System.Data.OleDb/src/OleDbConnectionFactory.cs index 2893c0173ee53..6c857b13d6a90 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbConnectionFactory.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbConnectionFactory.cs @@ -125,11 +125,7 @@ internal override DbConnectionPoolGroupProviderInfo CreateConnectionPoolGroupPro internal override void PermissionDemand(DbConnection outerConnection) { - OleDbConnection? c = (outerConnection as OleDbConnection); - if (null != c) - { - c.PermissionDemand(); - } + (outerConnection as OleDbConnection)?.PermissionDemand(); } internal override void SetConnectionPoolGroup(DbConnection outerConnection, DbConnectionPoolGroup poolGroup) @@ -143,11 +139,7 @@ internal override void SetConnectionPoolGroup(DbConnection outerConnection, DbCo internal override void SetInnerConnectionEvent(DbConnection owningObject, DbConnectionInternal to) { - OleDbConnection? c = (owningObject as OleDbConnection); - if (null != c) - { - c.SetInnerConnectionEvent(to); - } + (owningObject as OleDbConnection)?.SetInnerConnectionEvent(to); } internal override bool SetInnerConnectionFrom(DbConnection owningObject, DbConnectionInternal to, DbConnectionInternal from) @@ -162,11 +154,7 @@ internal override bool SetInnerConnectionFrom(DbConnection owningObject, DbConne internal override void SetInnerConnectionTo(DbConnection owningObject, DbConnectionInternal to) { - OleDbConnection? c = (owningObject as OleDbConnection); - if (null != c) - { - c.SetInnerConnectionTo(to); - } + (owningObject as OleDbConnection)?.SetInnerConnectionTo(to); } } diff --git a/src/libraries/System.Data.OleDb/src/OleDbConnectionInternal.cs b/src/libraries/System.Data.OleDb/src/OleDbConnectionInternal.cs index 7c0a1851c7aa3..ce21802510f61 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbConnectionInternal.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbConnectionInternal.cs @@ -306,14 +306,8 @@ protected override void Deactivate() public override void Dispose() { Debug.Assert(null == LocalTransaction, "why was Deactivate not called first"); - if (null != _sessionwrp) - { - _sessionwrp.Dispose(); - } - if (null != _datasrcwrp) - { - _datasrcwrp.Dispose(); - } + _sessionwrp?.Dispose(); + _datasrcwrp?.Dispose(); base.Dispose(); } diff --git a/src/libraries/System.Data.OleDb/src/OleDbDataAdapter.cs b/src/libraries/System.Data.OleDb/src/OleDbDataAdapter.cs index 9a358d699a6d8..6b1b5cfa2c7e8 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbDataAdapter.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbDataAdapter.cs @@ -356,10 +356,7 @@ private int FillFromRecordset(object data, UnsafeNativeMethods.ADORecordsetConst } finally { - if (null != dataReader) - { - dataReader.Close(); - } + dataReader?.Close(); } } return 0; @@ -406,10 +403,7 @@ private int FillFromRecord(object data, UnsafeNativeMethods.ADORecordConstructio } finally { - if (null != dataReader) - { - dataReader.Close(); - } + dataReader?.Close(); } } return 0; diff --git a/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs b/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs index 752fabd0f1b80..28b89d589b4a9 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs @@ -721,10 +721,7 @@ public override void Close() // release unmanaged objects RowHandleBuffer? rowHandleNativeBuffer = _rowHandleNativeBuffer; _rowHandleNativeBuffer = null; - if (null != rowHandleNativeBuffer) - { - rowHandleNativeBuffer.Dispose(); - } + rowHandleNativeBuffer?.Dispose(); } internal void CloseReaderFromConnection(bool canceling) @@ -978,12 +975,9 @@ private OleDbDataReader GetDataForReader(IntPtr ordinal, RowBinding rowbinding, reader.BuildMetaInfo(); reader.HasRowsRead(); - if (_connection != null) - { - // connection tracks all readers to prevent cmd from executing - // until all readers (including nested) are closed - _connection.AddWeakReference(reader, OleDbReferenceCollection.DataReaderTag); - } + // connection tracks all readers to prevent cmd from executing + // until all readers (including nested) are closed + _connection?.AddWeakReference(reader, OleDbReferenceCollection.DataReaderTag); } return reader!; diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionFactory.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionFactory.cs index a67b45401a2a1..d8ea0f91d5f37 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionFactory.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionFactory.cs @@ -52,11 +52,7 @@ public void ClearAllPools() Dictionary connectionPoolGroups = _connectionPoolGroups; foreach (KeyValuePair entry in connectionPoolGroups) { - DbConnectionPoolGroup poolGroup = entry.Value; - if (null != poolGroup) - { - poolGroup.Clear(); - } + entry.Value?.Clear(); } } diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionInternal.Shared.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionInternal.Shared.cs index 3419d6c350da5..0522504310814 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionInternal.Shared.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionInternal.Shared.cs @@ -338,10 +338,8 @@ internal void DeactivateConnection() Debug.Assert(0 == activateCount, "activated multiple times?"); #endif // DEBUG - if (PerformanceCounters != null) - { // Pool.Clear will DestroyObject that will clean performanceCounters before going here - PerformanceCounters.NumberOfActiveConnections.Decrement(); - } + // Pool.Clear will DestroyObject that will clean performanceCounters before going here + PerformanceCounters?.NumberOfActiveConnections.Decrement(); if (!_connectionIsDoomed && Pool!.UseLoadBalancing) { @@ -456,11 +454,7 @@ internal void MakePooledConnection(DbConnectionPool connectionPool) internal void NotifyWeakReference(int message) { - DbReferenceCollection? referenceCollection = ReferenceCollection; - if (null != referenceCollection) - { - referenceCollection.Notify(message); - } + ReferenceCollection?.Notify(message); } internal virtual void OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) @@ -581,11 +575,7 @@ internal void PostPop(object newOwner) internal void RemoveWeakReference(object value) { - DbReferenceCollection? referenceCollection = ReferenceCollection; - if (null != referenceCollection) - { - referenceCollection.Remove(value); - } + ReferenceCollection?.Remove(value); } internal void DetachCurrentTransactionIfEnded() diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionInternal.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionInternal.cs index f98d94b4ba044..574114676405f 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionInternal.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionInternal.cs @@ -143,11 +143,7 @@ public virtual void Dispose() // Dispose of the _enlistedTransaction since it is a clone // of the original reference. // _enlistedTransaction can be changed by another thread (TX end event) - SysTx.Transaction? enlistedTransaction = Interlocked.Exchange(ref _enlistedTransaction, null); - if (enlistedTransaction != null) - { - enlistedTransaction.Dispose(); - } + Interlocked.Exchange(ref _enlistedTransaction, null)?.Dispose(); } } } diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPool.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPool.cs index 836b061027169..9fa5af95d9a00 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPool.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPool.cs @@ -37,10 +37,7 @@ internal TransactedConnectionList(int initialAllocation, SysTx.Transaction tx) : internal void Dispose() { - if (null != _transaction) - { - _transaction.Dispose(); - } + _transaction?.Dispose(); } } @@ -624,12 +621,7 @@ internal void Clear() for (int i = 0; i < count; ++i) { - obj = _objectList[i]; - - if (null != obj) - { - obj.DoNotPoolThisConnection(); - } + _objectList[i]?.DoNotPoolThisConnection(); } } @@ -921,10 +913,7 @@ private void ErrorCallback(object? state) // the error state is cleaned, destroy the timer to avoid periodic invocation Timer? t = _errorTimer; _errorTimer = null; - if (t != null) - { - t.Dispose(); // Cancel timer request. - } + t?.Dispose(); // Cancel timer request. } // TODO: move this to src/Common and integrate with SqlClient @@ -991,20 +980,17 @@ private void WaitForPendingOpen() } catch (System.OutOfMemoryException) { - if (connection != null) - { connection.DoomThisConnection(); } + connection?.DoomThisConnection(); throw; } catch (System.StackOverflowException) { - if (connection != null) - { connection.DoomThisConnection(); } + connection?.DoomThisConnection(); throw; } catch (System.Threading.ThreadAbortException) { - if (connection != null) - { connection.DoomThisConnection(); } + connection?.DoomThisConnection(); throw; } catch (Exception e) @@ -1680,10 +1666,7 @@ internal void Shutdown() // deactivate timer callbacks Timer? t = _cleanupTimer; _cleanupTimer = null; - if (null != t) - { - t.Dispose(); - } + t?.Dispose(); } private DbConnectionInternal? UserCreateRequest(DbConnection owningObject, DbConnectionOptions? userOptions, DbConnectionInternal? oldConnection = null) diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPoolCounters.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPoolCounters.cs index 990461c6d4919..ee93e6202329f 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPoolCounters.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPoolCounters.cs @@ -121,32 +121,19 @@ internal Counter(string? categoryName, string? instanceName, string counterName, internal void Decrement() { PerformanceCounter? instance = _instance; - if (null != instance) - { - instance.Decrement(); - } + instance?.Decrement(); } internal void Dispose() { // TODO: race condition, Dispose at the same time as Increment/Decrement PerformanceCounter? instance = _instance; _instance = null; - if (null != instance) - { - instance.RemoveInstance(); - // should we be calling instance.Close? - // if we do will it exacerbate the Dispose vs. Decrement race condition - //instance.Close(); - } + instance?.RemoveInstance(); } internal void Increment() { - PerformanceCounter? instance = _instance; - if (null != instance) - { - instance.Increment(); - } + _instance?.Increment(); } }; @@ -298,10 +285,7 @@ public void Dispose() private static void SafeDispose(Counter counter) { - if (null != counter) - { - counter.Dispose(); - } + counter?.Dispose(); } private void ExceptionEventHandler(object sender, UnhandledExceptionEventArgs e) diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbMetaDataFactory.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbMetaDataFactory.cs index 5d94056b78ce8..2e496fd0fc888 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbMetaDataFactory.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbMetaDataFactory.cs @@ -201,10 +201,7 @@ private DataTable ExecuteCommand(DataRow requestedCollectionRow, string?[]? rest } finally { - if (reader != null) - { - reader.Dispose(); - } + reader?.Dispose(); } return resultTable; 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 686329d8ec4e8..fe59456017fe0 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogInternal.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogInternal.cs @@ -1180,10 +1180,7 @@ private static void StaticCompletionCallback(object context, bool wasSignaled) { try { - if (interestedComponents[i] != null) - { - interestedComponents[i].CompletionCallback(null); - } + interestedComponents[i]?.CompletionCallback(null); } catch (ObjectDisposedException) { 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 547e63241c2dd..f3de1b2d0a7e1 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 @@ -107,10 +107,7 @@ internal void StopSubscribing() { // Not calling Stop from within callback - wait for // Any outstanding callbacks to complete. - if (_unregisterDoneHandle != null) - { - _unregisterDoneHandle.WaitOne(); - } + _unregisterDoneHandle?.WaitOne(); } _registeredWaitHandle = null; 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 927f9d1e5417f..97ad287fb7832 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterLib.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterLib.cs @@ -627,8 +627,7 @@ private static void DeleteRegistryEntry(string categoryName) } finally { - if (serviceKey != null) - serviceKey.Close(); + serviceKey?.Close(); } } @@ -738,10 +737,8 @@ internal bool FindCustomCategory(string category, out PerformanceCounterCategory } finally { - if (key != null) - key.Close(); - if (baseKey != null) - baseKey.Close(); + key?.Close(); + baseKey?.Close(); } } @@ -974,22 +971,10 @@ private string GetCounterHelp(string category, string counter, ref bool category private static string[] GetLanguageIds() { - RegistryKey libraryParentKey = null; - string[] ids = Array.Empty(); - try - { - libraryParentKey = Registry.LocalMachine.OpenSubKey(PerflibPath); - - if (libraryParentKey != null) - ids = libraryParentKey.GetSubKeyNames(); - } - finally - { - if (libraryParentKey != null) - libraryParentKey.Close(); - } - - return ids; + using RegistryKey libraryParentKey = Registry.LocalMachine.OpenSubKey(PerflibPath); + return libraryParentKey != null ? + libraryParentKey.GetSubKeyNames() : + Array.Empty(); } internal static PerformanceCounterLib GetPerformanceCounterLib(string machineName, CultureInfo culture) @@ -1296,8 +1281,7 @@ private void Init() internal void Close() { - if (perfDataKey != null) - perfDataKey.Close(); + perfDataKey?.Close(); perfDataKey = null; } diff --git a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/SharedPerformanceCounter.cs b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/SharedPerformanceCounter.cs index 99e1f3395c14f..f60df86bd6a5e 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/SharedPerformanceCounter.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/SharedPerformanceCounter.cs @@ -711,8 +711,7 @@ private unsafe CategoryData GetCategoryData() } finally { - if (categoryKey != null) - categoryKey.Close(); + categoryKey?.Close(); } } } @@ -1761,8 +1760,7 @@ private unsafe void Initialize(string fileMappingName, int fileMappingSize, int } finally { - if (securityDescriptorPointer != null) - securityDescriptorPointer.Close(); + securityDescriptorPointer?.Close(); } Interlocked.CompareExchange(ref *(int*)_fileViewAddress.DangerousGetHandle().ToPointer(), initialOffset, 0); diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Windows.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Windows.cs index 68cda1c7f50c5..214947a72c9b8 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Windows.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Windows.cs @@ -720,10 +720,7 @@ private static unsafe void SetPrivilege(string privilegeName, int attrib) } finally { - if (hToken != null) - { - hToken.Dispose(); - } + hToken?.Dispose(); } } diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.cs index 4268e21bed4e6..18da1e4213ea5 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.cs @@ -1386,15 +1386,8 @@ private void StopWatchingForExit() } } - if (rwh != null) - { - rwh.Unregister(null); - } - - if (wh != null) - { - wh.Dispose(); - } + rwh?.Unregister(null); + wh?.Dispose(); } } diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Windows.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Windows.cs index c111927c628b7..a35913265d9cc 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Windows.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Windows.cs @@ -231,10 +231,7 @@ static unsafe ProcessManager() } finally { - if (tokenHandle != null) - { - tokenHandle.Dispose(); - } + tokenHandle?.Dispose(); } } 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 9fc96bff574cd..e0d0529b8c795 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 @@ -417,16 +417,8 @@ private bool GetNextEnum() if (!memberFound) { - IDisposable disposableMembers = _members as IDisposable; - if (disposableMembers != null) - { - disposableMembers.Dispose(); - } - IDisposable disposableMembersEnum = _membersEnum as IDisposable; - if (disposableMembersEnum != null) - { - disposableMembersEnum.Dispose(); - } + (_members as IDisposable)?.Dispose(); + (_membersEnum as IDisposable)?.Dispose(); _members = null; _membersEnum = null; } @@ -961,8 +953,7 @@ internal override void Reset() _foreignMembersCurrentGroup.Clear(); _fakePrincipalMembers.Clear(); - if (null != _foreignMembersToReturn) - _foreignMembersToReturn.Clear(); + _foreignMembersToReturn?.Clear(); _currentForeignPrincipal = null; _currentForeignDE = null; @@ -1149,8 +1140,7 @@ internal override void RestoreBookmark(ResultSetBookmark bookmark) _currentForeignPrincipal = adBookmark.currentForeignPrincipal; _currentForeignDE = adBookmark.currentForeignDE; _foreignGroups = adBookmark.foreignGroups; - if (_queryMembersResults != null) - _queryMembersResults.Dispose(); + _queryMembersResults?.Dispose(); _queryMembersResults = adBookmark.queryMembersResults; _queryMembersResultEnumerator = adBookmark.queryMembersResultEnumerator; _memberSearchResults = adBookmark.memberSearchResults; @@ -1255,11 +1245,7 @@ public override void Dispose() GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Dispose: disposing membersQueue"); foreach (IEnumerable enumerable in _membersQueue) { - IDisposable disposableEnum = enumerable as IDisposable; - if (disposableEnum != null) - { - disposableEnum.Dispose(); - } + (enumerable as IDisposable)?.Dispose(); } } if (_foreignGroups != null) diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADEntriesSet.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADEntriesSet.cs index a5ca6ecd9673e..b6318fd3dea87 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADEntriesSet.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADEntriesSet.cs @@ -88,8 +88,7 @@ internal override void Reset() _endReached = false; _current = null; - if (_enumerator != null) - _enumerator.Reset(); + _enumerator?.Reset(); } // IDisposable implementation diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx.cs index 0ed20eee09cfe..59f2177dc797f 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx.cs @@ -1248,14 +1248,8 @@ internal override ResultSet GetGroupsMemberOf(Principal p) } finally { - if (gc != null) - { - gc.Dispose(); - } - if (forest != null) - { - forest.Dispose(); - } + gc?.Dispose(); + forest?.Dispose(); } } @@ -1359,15 +1353,8 @@ internal override ResultSet GetGroupsMemberOf(Principal p) } finally { - if (null != gcPrincipalDe) - { - gcPrincipalDe.Dispose(); - } - - if (null != memberOfSearcher) - { - memberOfSearcher.Dispose(); - } + gcPrincipalDe?.Dispose(); + memberOfSearcher?.Dispose(); } } @@ -1537,12 +1524,9 @@ internal override ResultSet GetGroupsMemberOf(Principal foreignPrincipal, StoreC } finally { - if (null != fspContainer) - fspContainer.Dispose(); - if (null != ds) - ds.Dispose(); - if (null != dncContainer) - dncContainer.Dispose(); + fspContainer?.Dispose(); + ds?.Dispose(); + dncContainer?.Dispose(); } } @@ -1870,14 +1854,8 @@ internal override bool IsMemberOfInStore(GroupPrincipal g, Principal p) } finally { - if (ds != null) - { - ds.Dispose(); - } - if (defaultNCDirEntry != null) - { - defaultNCDirEntry.Dispose(); - } + ds?.Dispose(); + defaultNCDirEntry?.Dispose(); } } @@ -1952,8 +1930,7 @@ internal override bool CanGroupBeCleared(GroupPrincipal g, out string explanatio } finally { - if (ds != null) - ds.Dispose(); + ds?.Dispose(); } } diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_LoadStore.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_LoadStore.cs index 5137b5446ddba..1214019bd210d 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_LoadStore.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_LoadStore.cs @@ -669,10 +669,7 @@ private Principal FindPrincipalByIdentRefHelper( finally { ds.Dispose(); - if (src != null) - { - src.Dispose(); - } + src?.Dispose(); } } @@ -1510,8 +1507,7 @@ protected static void UpdateGroupMembership(Principal group, DirectoryEntry de, } finally { - if (copyOfDe != null) - copyOfDe.Dispose(); + copyOfDe?.Dispose(); } } @@ -1637,8 +1633,7 @@ protected static void UpdateGroupMembership(Principal group, DirectoryEntry de, } finally { - if (null != groupDe) - groupDe.Dispose(); + groupDe?.Dispose(); } } diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SDSUtils.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SDSUtils.cs index 7ac1e69f5d52d..f0e567298d685 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SDSUtils.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SDSUtils.cs @@ -425,8 +425,7 @@ internal static void WriteAttribute(string dePath, string attribute, T value, } finally { - if (copyOfDe != null) - copyOfDe.Dispose(); + copyOfDe?.Dispose(); } } @@ -477,8 +476,7 @@ internal static void WriteAttribute(string dePath, string attribute, int value, } finally { - if (copyOfDe != null) - copyOfDe.Dispose(); + copyOfDe?.Dispose(); } } diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SidList.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SidList.cs index da8670b411365..4df7b5397cc39 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SidList.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SidList.cs @@ -194,14 +194,9 @@ private void TranslateSids(string target, IntPtr[] pSids) } finally { - if (domainsHandle != null) - domainsHandle.Dispose(); - - if (namesHandle != null) - namesHandle.Dispose(); - - if (policyHandle != null) - policyHandle.Dispose(); + domainsHandle?.Dispose(); + namesHandle?.Dispose(); + policyHandle?.Dispose(); } } diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/TokenGroupsSet.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/TokenGroupsSet.cs index cc27c86811244..818b7234c69fa 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/TokenGroupsSet.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/TokenGroupsSet.cs @@ -125,8 +125,7 @@ public override void Dispose() { if (!_disposed) { - if (_current != null) - _current.Dispose(); + _current?.Dispose(); _disposed = true; } diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AuthenticablePrincipal.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AuthenticablePrincipal.cs index 3155d394c5f47..4b1d090ee70f7 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AuthenticablePrincipal.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AuthenticablePrincipal.cs @@ -524,15 +524,9 @@ internal override void ResetAllChangeStatus() RefreshOriginalThumbprintList(); - if (_accountInfo != null) - { - _accountInfo.ResetAllChangeStatus(); - } + _accountInfo?.ResetAllChangeStatus(); - if (_passwordInfo != null) - { - _passwordInfo.ResetAllChangeStatus(); - } + _passwordInfo?.ResetAllChangeStatus(); rosf.ResetAllChangeStatus(); diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Context.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Context.cs index acaf5a6afd01f..db9532712a474 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Context.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Context.cs @@ -658,8 +658,7 @@ private void DoMachineInit() " and message " + e.Message); // Cleanup the DE on failure - if (de != null) - de.Dispose(); + de?.Dispose(); throw; } @@ -765,8 +764,7 @@ private void DoLDAPDirectoryInit() finally { // Cleanup the DE on failure - if (de != null) - de.Dispose(); + de?.Dispose(); } } @@ -822,8 +820,7 @@ private void DoLDAPDirectoryInitNoContainer() finally { // Don't allow the DE to leak - if (deRootDse != null) - deRootDse.Dispose(); + deRootDse?.Dispose(); } try @@ -919,23 +916,12 @@ private void DoLDAPDirectoryInitNoContainer() // Cleanup on failure. Once a DE has been successfully handed off to a ADStoreCtx, // that ADStoreCtx will handle Dispose()'ing it - if (deUserGroupOrg != null) - deUserGroupOrg.Dispose(); - - if (deComputer != null) - deComputer.Dispose(); - - if (deBase != null) - deBase.Dispose(); - - if (storeCtxUserGroupOrg != null) - storeCtxUserGroupOrg.Dispose(); - - if (storeCtxComputer != null) - storeCtxComputer.Dispose(); - - if (storeCtxBase != null) - storeCtxBase.Dispose(); + deUserGroupOrg?.Dispose(); + deComputer?.Dispose(); + deBase?.Dispose(); + storeCtxUserGroupOrg?.Dispose(); + storeCtxComputer?.Dispose(); + storeCtxBase?.Dispose(); throw; } @@ -1004,17 +990,10 @@ public void Dispose() // This is okay, since StoreCtxs allow multiple Dispose() calls, and ignore // all but the first call. - if (_userCtx != null) - _userCtx.Dispose(); - - if (_groupCtx != null) - _groupCtx.Dispose(); - - if (_computerCtx != null) - _computerCtx.Dispose(); - - if (_queryCtx != null) - _queryCtx.Dispose(); + _userCtx?.Dispose(); + _groupCtx?.Dispose(); + _computerCtx?.Dispose(); + _queryCtx?.Dispose(); _credValidate.Dispose(); @@ -1181,10 +1160,7 @@ internal void ReadServerConfig(string serverName, ref ServerProperties propertie } finally { - if (ldapConnection != null) - { - ldapConnection.Dispose(); - } + ldapConnection?.Dispose(); } } diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Group.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Group.cs index 3fc786a1705b2..935ebf8ea4b31 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Group.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Group.cs @@ -221,8 +221,7 @@ public override void Dispose() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "Group", "Dispose: disposing"); - if (_members != null) - _members.Dispose(); + _members?.Dispose(); _disposed = true; GC.SuppressFinalize(this); @@ -333,8 +332,7 @@ internal override void ResetAllChangeStatus() _groupScopeChanged = (_groupScopeChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; _isSecurityGroupChanged = (_isSecurityGroupChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; - if (_members != null) - _members.ResetTracking(); + _members?.ResetTracking(); base.ResetAllChangeStatus(); } diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Principal.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Principal.cs index 58f294de790f0..df7f4375d3f42 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Principal.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Principal.cs @@ -766,8 +766,7 @@ protected internal PrincipalContext ContextRaw set { // Verify that the passed context is not disposed. - if (value != null) - value.CheckDisposed(); + value?.CheckDisposed(); _ctx = value; } } 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 07db2eecf3a0f..e5c354c5efdc5 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 @@ -119,8 +119,7 @@ private bool MoveNextLocal() _current = null; _currentForeign = null; - if (_foreignResultSet != null) - _foreignResultSet.Dispose(); + _foreignResultSet?.Dispose(); _foreignResultSet = null; return true; } @@ -195,8 +194,7 @@ private bool MoveNextLocal() _currentFakePrincipal = null; _currentForeign = null; - if (_foreignResultSet != null) - _foreignResultSet.Dispose(); + _foreignResultSet?.Dispose(); _foreignResultSet = null; return true; } @@ -297,8 +295,7 @@ private bool MoveNextForeign() _currentFakePrincipal = null; _currentForeign = foreignPrincipal; - if (_foreignResultSet != null) - _foreignResultSet.Dispose(); + _foreignResultSet?.Dispose(); _foreignResultSet = null; return true; } @@ -532,8 +529,7 @@ internal override void RestoreBookmark(ResultSetBookmark bookmark) _foreignMembers = samBookmark.foreignMembers; _foreignGroups = samBookmark.foreignGroups; - if (_foreignResultSet != null) - _foreignResultSet.Dispose(); + _foreignResultSet?.Dispose(); _foreignResultSet = samBookmark.foreignResultSet; _atBeginning = samBookmark.atBeginning; diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMQuerySet.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMQuerySet.cs index c00b298bc4354..6d55ffc43268a 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMQuerySet.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMQuerySet.cs @@ -164,8 +164,7 @@ internal override void Reset() _endReached = false; _current = null; - if (_enumerator != null) - _enumerator.Reset(); + _enumerator?.Reset(); _resultsReturned = 0; } diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx.cs index b02f4f6a2d489..90bff1b375e7a 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx.cs @@ -443,8 +443,7 @@ internal override void UnlockAccount(AuthenticablePrincipal p) } finally { - if (copyOfDe != null) - copyOfDe.Dispose(); + copyOfDe?.Dispose(); } } diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Utils.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Utils.cs index 1644daea12990..12cfa84157004 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Utils.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Utils.cs @@ -449,8 +449,7 @@ out tokenHandle } finally { - if (tokenHandle != null) - tokenHandle.Dispose(); + tokenHandle?.Dispose(); if (pBuffer != IntPtr.Zero) Marshal.FreeHGlobal(pBuffer); @@ -521,8 +520,7 @@ internal static IntPtr GetMachineDomainSid() } finally { - if (policyHandle != null) - policyHandle.Dispose(); + policyHandle?.Dispose(); if (pBuffer != IntPtr.Zero) Interop.Advapi32.LsaFreeMemory(pBuffer); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ADAMInstance.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ADAMInstance.cs index a584ab7d00153..84980cff39da7 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ADAMInstance.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ADAMInstance.cs @@ -299,10 +299,7 @@ public void SeizeRoleOwnership(AdamRole role) } finally { - if (roleObjectEntry != null) - { - roleObjectEntry.Dispose(); - } + roleObjectEntry?.Dispose(); } // invalidate the role collection so that it gets loaded again next time @@ -591,14 +588,8 @@ public AdamRoleCollection Roles } finally { - if (schemaEntry != null) - { - schemaEntry.Dispose(); - } - if (partitionsEntry != null) - { - partitionsEntry.Dispose(); - } + schemaEntry?.Dispose(); + partitionsEntry?.Dispose(); } return _cachedRoles; } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectoryInterSiteTransport.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectoryInterSiteTransport.cs index c7423df1c7611..1531ed1c22fe2 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectoryInterSiteTransport.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectoryInterSiteTransport.cs @@ -349,8 +349,7 @@ protected virtual void Dispose(bool disposing) if (disposing) { // free other state (managed objects) - if (_cachedEntry != null) - _cachedEntry.Dispose(); + _cachedEntry?.Dispose(); } // free your own state (unmanaged objects) 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 c6dd1c6d6fbfb..c69602a7d2e4a 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchema.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchema.cs @@ -198,10 +198,7 @@ public void RefreshSchema() } finally { - if (rootDSE != null) - { - rootDSE.Dispose(); - } + rootDSE?.Dispose(); } } @@ -456,10 +453,7 @@ internal static ReadOnlyActiveDirectorySchemaPropertyCollection GetAllProperties finally { // dispose off the result collection - if (resCol != null) - { - resCol.Dispose(); - } + resCol?.Dispose(); } return new ReadOnlyActiveDirectorySchemaPropertyCollection(propertyList); @@ -513,10 +507,7 @@ internal static ReadOnlyActiveDirectorySchemaClassCollection GetAllClasses(Direc finally { // dispose off the result collection - if (resCol != null) - { - resCol.Dispose(); - } + resCol?.Dispose(); } return new ReadOnlyActiveDirectorySchemaClassCollection(classList); 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 e46383fddbb71..c35429530d0a6 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClass.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClass.cs @@ -210,10 +210,7 @@ protected virtual void Dispose(bool disposing) _abstractClassEntry = null; } // dispose the schema object - if (_schema != null) - { - _schema.Dispose(); - } + _schema?.Dispose(); } _disposed = true; } @@ -383,10 +380,7 @@ public void Save() } finally { - if (schemaRoleOwner != null) - { - schemaRoleOwner.Dispose(); - } + schemaRoleOwner?.Dispose(); if (!alreadyUsingSchemaRoleOwnerContext) { schemaObject.Dispose(); @@ -464,11 +458,8 @@ public string? CommonName if (isBound) { - if (_commonName == null) - { - // get the property from the server - _commonName = (string)GetValueFromCache(PropertyManager.Cn, true)!; - } + // get the property from the server + _commonName ??= (string)GetValueFromCache(PropertyManager.Cn, true)!; } return _commonName; } @@ -924,11 +915,8 @@ public ActiveDirectorySchemaClass? SubClassOf if (isBound) { - if (_subClassOf == null) - { - // get the property from the server - _subClassOf = new ActiveDirectorySchemaClass(_context, (string)GetValueFromCache(PropertyManager.SubClassOf, true)!, (DirectoryEntry?)null, _schemaEntry); - } + // get the property from the server + _subClassOf ??= new ActiveDirectorySchemaClass(_context, (string)GetValueFromCache(PropertyManager.SubClassOf, true)!, (DirectoryEntry?)null, _schemaEntry); } return _subClassOf; } @@ -989,11 +977,8 @@ public Guid SchemaGuid if (isBound) { - if (_schemaGuidBinaryForm == null) - { - // get the property from the server - _schemaGuidBinaryForm = (byte[])GetValueFromCache(PropertyManager.SchemaIDGuid, true)!; - } + // get the property from the server + _schemaGuidBinaryForm ??= (byte[])GetValueFromCache(PropertyManager.SchemaIDGuid, true)!; } // we cache the byte array and create a new guid each time @@ -1345,10 +1330,7 @@ private ArrayList GetClasses(ICollection ldapDisplayNames) } finally { - if (resCol != null) - { - resCol.Dispose(); - } + resCol?.Dispose(); } return classes; @@ -1420,10 +1402,7 @@ private ArrayList GetProperties(ICollection ldapDisplayNames) } finally { - if (resCol != null) - { - resCol.Dispose(); - } + resCol?.Dispose(); } return properties; 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 07626c67218b5..acec139ed8fda 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaProperty.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaProperty.cs @@ -260,10 +260,7 @@ protected virtual void Dispose(bool disposing) _abstractPropertyEntry = null; } // dispose the schema object - if (_schema != null) - { - _schema.Dispose(); - } + _schema?.Dispose(); } _disposed = true; @@ -419,10 +416,7 @@ public void Save() } finally { - if (schemaRoleOwner != null) - { - schemaRoleOwner.Dispose(); - } + schemaRoleOwner?.Dispose(); if (!alreadyUsingSchemaRoleOwnerContext) { schemaObject.Dispose(); @@ -496,11 +490,8 @@ public string? CommonName if (isBound) { - if (_commonName == null) - { - // get the property from the server - _commonName = (string)GetValueFromCache(PropertyManager.Cn, true)!; - } + // get the property from the server + _commonName ??= (string)GetValueFromCache(PropertyManager.Cn, true)!; } return _commonName; } @@ -1068,11 +1059,8 @@ public Guid SchemaGuid if (isBound) { - if (_schemaGuidBinaryForm == null) - { - // get the property from the server - _schemaGuidBinaryForm = (byte[])GetValueFromCache(PropertyManager.SchemaIDGuid, true)!; - } + // get the property from the server + _schemaGuidBinaryForm ??= (byte[])GetValueFromCache(PropertyManager.SchemaIDGuid, true)!; } // we cache the byte array and create a new guid each time diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySite.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySite.cs index 8440e7d8c1252..6e9e52d5588a4 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySite.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySite.cs @@ -159,8 +159,7 @@ public ActiveDirectorySite(DirectoryContext context, string siteName) } finally { - if (de != null) - de.Dispose(); + de?.Dispose(); } _subnets = new ActiveDirectorySubnetCollection(context, "CN=" + siteName + "," + _siteDN); @@ -1090,11 +1089,8 @@ protected virtual void Dispose(bool disposing) if (disposing) { // free other state (managed objects) - if (cachedEntry != null) - cachedEntry.Dispose(); - - if (_ntdsEntry != null) - _ntdsEntry.Dispose(); + cachedEntry?.Dispose(); + _ntdsEntry?.Dispose(); } // free your own state (unmanaged objects) diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLink.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLink.cs index 3f4660c7820f9..388484f8ba093 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLink.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLink.cs @@ -654,8 +654,7 @@ protected virtual void Dispose(bool disposing) if (disposing) { // free other state (managed objects) - if (cachedEntry != null) - cachedEntry.Dispose(); + cachedEntry?.Dispose(); } // free your own state (unmanaged objects) diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLinkBridge.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLinkBridge.cs index 672a5aab39aa8..3e936f14be405 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLinkBridge.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLinkBridge.cs @@ -310,8 +310,7 @@ protected virtual void Dispose(bool disposing) if (disposing) { // free other state (managed objects) - if (cachedEntry != null) - cachedEntry.Dispose(); + cachedEntry?.Dispose(); } // free your own state (unmanaged objects) diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySubnet.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySubnet.cs index ec25775a7c655..95d61b0d76d81 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySubnet.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySubnet.cs @@ -102,8 +102,7 @@ public static ActiveDirectorySubnet FindByName(DirectoryContext context, string } finally { - if (de != null) - de.Dispose(); + de?.Dispose(); } } @@ -143,8 +142,7 @@ public ActiveDirectorySubnet(DirectoryContext context, string subnetName) } finally { - if (de != null) - de.Dispose(); + de?.Dispose(); } } @@ -365,8 +363,7 @@ protected virtual void Dispose(bool disposing) if (disposing) { // free other state (managed objects) - if (cachedEntry != null) - cachedEntry.Dispose(); + cachedEntry?.Dispose(); } // free your own state (unmanaged objects) 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 93dc06daf4495..27cf3d5c74d26 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ApplicationPartition.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ApplicationPartition.cs @@ -984,15 +984,8 @@ private void CreateApplicationPartition(string distinguishedName, string objectC finally { // dispose all resources - if (parent != null) - { - parent.Dispose(); - } - - if (tempEntry != null) - { - tempEntry.Dispose(); - } + parent?.Dispose(); + tempEntry?.Dispose(); } } else @@ -1031,15 +1024,8 @@ private void CreateApplicationPartition(string distinguishedName, string objectC finally { // dispose all resources - if (parent != null) - { - parent.Dispose(); - } - - if (tempEntry != null) - { - tempEntry.Dispose(); - } + parent?.Dispose(); + tempEntry?.Dispose(); } } catch (COMException e) @@ -1091,10 +1077,7 @@ private void InitializeCrossRef(string distinguishedName) } finally { - if (partitionsEntry != null) - { - partitionsEntry.Dispose(); - } + partitionsEntry?.Dispose(); } } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ConfigSet.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ConfigSet.cs index 47675bca1c04c..8a64bddee5802 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ConfigSet.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ConfigSet.cs @@ -621,10 +621,7 @@ private AdamInstance GetRoleOwner(AdamRole role) } finally { - if (entry != null) - { - entry.Dispose(); - } + entry?.Dispose(); } // create a new context object for the adam instance passing on the @@ -666,11 +663,8 @@ private ArrayList GetSites() } finally { - if (resCol != null) - { - // call dispose on search result collection - resCol.Dispose(); - } + // call dispose on search result collection + resCol?.Dispose(); } return sites; } @@ -739,11 +733,8 @@ private ArrayList GetApplicationPartitions() } finally { - if (resCol != null) - { - // call dispose on search result collection - resCol.Dispose(); - } + // call dispose on search result collection + resCol?.Dispose(); } return appNCs; } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServer.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServer.cs index 1e9b45c4b1044..85cdd51a2b6f6 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServer.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServer.cs @@ -116,10 +116,7 @@ public void MoveToAnotherSite(string siteName) } finally { - if (newParentEntry != null) - { - newParentEntry.Dispose(); - } + newParentEntry?.Dispose(); } // remove stale cached directory entries @@ -266,15 +263,8 @@ internal ArrayList GetPartitions() } finally { - if (rootDSE != null) - { - rootDSE.Dispose(); - } - - if (serverNtdsaEntry != null) - { - serverNtdsaEntry.Dispose(); - } + rootDSE?.Dispose(); + serverNtdsaEntry?.Dispose(); } return partitionList; } @@ -759,11 +749,8 @@ internal unsafe void SyncReplicaHelper(IntPtr dsHandle, bool isADAM, string part if (unmanagedGuid != (IntPtr)0) Marshal.FreeHGlobal(unmanagedGuid); - if (adamServer != null) - adamServer.Dispose(); - - if (dcServer != null) - dcServer.Dispose(); + adamServer?.Dispose(); + dcServer?.Dispose(); } } @@ -801,9 +788,7 @@ internal ReplicationConnectionCollection GetInboundConnectionsHelper() } finally { - if (srchResults != null) - srchResults.Dispose(); - + srchResults?.Dispose(); de.Dispose(); } } @@ -846,9 +831,7 @@ internal ReplicationConnectionCollection GetOutboundConnectionsHelper() } finally { - if (results != null) - results.Dispose(); - + results?.Dispose(); de.Dispose(); } } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Domain.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Domain.cs index db1b62455626f..43870acf6c9e4 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Domain.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Domain.cs @@ -243,10 +243,7 @@ public void RaiseDomainFunctionalityLevel(int domainMode) } finally { - if (domainEntry != null) - { - domainEntry.Dispose(); - } + domainEntry?.Dispose(); } // at this point the raise domain function has succeeded @@ -401,10 +398,7 @@ public void RaiseDomainFunctionality(DomainMode domainMode) } finally { - if (domainEntry != null) - { - domainEntry.Dispose(); - } + domainEntry?.Dispose(); } // at this point the raise domain function has succeeded @@ -916,10 +910,7 @@ public DomainController PdcRoleOwner get { CheckIfDisposed(); - if (_cachedPdcRoleOwner == null) - { - _cachedPdcRoleOwner = GetRoleOwner(ActiveDirectoryRole.PdcRole); - } + _cachedPdcRoleOwner ??= GetRoleOwner(ActiveDirectoryRole.PdcRole); return _cachedPdcRoleOwner; } } @@ -968,10 +959,7 @@ private int GetDomainModeLevel() finally { rootDSE.Dispose(); - if (domainEntry != null) - { - domainEntry.Dispose(); - } + domainEntry?.Dispose(); } return domainFunctionality; } @@ -1046,10 +1034,7 @@ private DomainMode GetDomainMode() } finally { - if (domainEntry != null) - { - domainEntry.Dispose(); - } + domainEntry?.Dispose(); } return domainMode; } @@ -1093,10 +1078,7 @@ private DomainController GetRoleOwner(ActiveDirectoryRole role) } finally { - if (entry != null) - { - entry.Dispose(); - } + entry?.Dispose(); } // create a new context object for the domain controller passing on the @@ -1158,10 +1140,7 @@ private void LoadCrossRefAttributes() } finally { - if (partitionsEntry != null) - { - partitionsEntry.Dispose(); - } + partitionsEntry?.Dispose(); } } @@ -1250,14 +1229,8 @@ private ArrayList GetChildDomains() } finally { - if (resCol != null) - { - resCol.Dispose(); - } - if (partitionsEntry != null) - { - partitionsEntry.Dispose(); - } + resCol?.Dispose(); + partitionsEntry?.Dispose(); } return childDomains; } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainController.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainController.cs index 2a5be2adb67fe..98eb7d7204497 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainController.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainController.cs @@ -429,10 +429,7 @@ public void SeizeRoleOwnership(ActiveDirectoryRole role) } finally { - if (roleObjectEntry != null) - { - roleObjectEntry.Dispose(); - } + roleObjectEntry?.Dispose(); } // invalidate the role collection so that it gets loaded again next time diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Forest.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Forest.cs index 19547e44578e1..e00d6e58c8092 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Forest.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Forest.cs @@ -833,10 +833,7 @@ private DomainController GetRoleOwner(ActiveDirectoryRole role) } finally { - if (entry != null) - { - entry.Dispose(); - } + entry?.Dispose(); } // create a new context object for the domain controller passing on the @@ -994,10 +991,7 @@ private ArrayList GetApplicationPartitions() } finally { - if (resCol != null) - { - resCol.Dispose(); - } + resCol?.Dispose(); partitionsEntry.Dispose(); } return appNCs; @@ -1051,10 +1045,7 @@ private ArrayList GetDomains() } finally { - if (resCol != null) - { - resCol.Dispose(); - } + resCol?.Dispose(); partitionsEntry.Dispose(); } return domains; diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationConnection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationConnection.cs index 01b0c22fca3d8..b1ecdf3a0ab60 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationConnection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationConnection.cs @@ -980,11 +980,8 @@ private void ValidateTargetAndSourceServer(DirectoryContext context, DirectorySe } finally { - if (targetDE != null) - targetDE.Close(); - - if (sourceDE != null) - sourceDE.Close(); + targetDE?.Close(); + sourceDE?.Close(); } } } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs index f707e8df0676f..4769dc9dd1b79 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs @@ -1356,14 +1356,8 @@ internal static ArrayList GetReplicaList(DirectoryContext context, string? parti } finally { - if (partitionsEntry != null) - { - partitionsEntry.Dispose(); - } - if (fsmoPartitionsEntry != null) - { - fsmoPartitionsEntry.Dispose(); - } + partitionsEntry?.Dispose(); + fsmoPartitionsEntry?.Dispose(); } } @@ -1598,10 +1592,7 @@ internal static ArrayList GetReplicaList(DirectoryContext context, string? parti } finally { - if (resCol != null) - { - resCol.Dispose(); - } + resCol?.Dispose(); } if (needToContinueRangeRetrieval) @@ -1734,10 +1725,7 @@ internal static ArrayList GetReplicaList(DirectoryContext context, string? parti } finally { - if (searchRootEntry != null) - { - searchRootEntry.Dispose(); - } + searchRootEntry?.Dispose(); } // convert the ntdsa object names to server:port @@ -2172,8 +2160,7 @@ out tokenHandle } finally { - if (tokenHandle != null) - tokenHandle.Dispose(); + tokenHandle?.Dispose(); if (pBuffer != IntPtr.Zero) Marshal.FreeHGlobal(pBuffer); @@ -2231,8 +2218,7 @@ internal static IntPtr GetMachineDomainSid() } finally { - if (policyHandle != null) - policyHandle.Dispose(); + policyHandle?.Dispose(); if (pBuffer != IntPtr.Zero) global::Interop.Advapi32.LsaFreeMemory(pBuffer); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/Design/DirectoryEntryConverter.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/Design/DirectoryEntryConverter.cs index 5ab69ecfef158..756be378e2d28 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/Design/DirectoryEntryConverter.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/Design/DirectoryEntryConverter.cs @@ -38,8 +38,7 @@ public override bool CanConvertFrom(ITypeDescriptorContext? context, Type source { newEntry = new DirectoryEntry(text); s_componentsCreated[text] = newEntry; - if (context != null) - context.Container.Add(newEntry); + context?.Container.Add(newEntry); return newEntry; } diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/EncoderParameters.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/EncoderParameters.cs index c2cbd9d771cf3..ddf56a7a13026 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/EncoderParameters.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/EncoderParameters.cs @@ -98,10 +98,7 @@ public void Dispose() { foreach (EncoderParameter p in _param) { - if (p != null) - { - p.Dispose(); - } + p?.Dispose(); } _param = null!; } diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Internal/SystemColorTracker.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Internal/SystemColorTracker.cs index c8a16f134f9d2..384ca75fa78c4 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Internal/SystemColorTracker.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Internal/SystemColorTracker.cs @@ -136,12 +136,7 @@ private static void OnUserPreferenceChanged(object sender, UserPreferenceChanged for (int i = 0; i < count; i++) { Debug.Assert(list[i] != null, "null value in active part of list"); - ISystemColorTracker? tracker = (ISystemColorTracker?)list[i].Target; - if (tracker != null) - { - // If object still around - tracker.OnSystemColorChanged(); - } + ((ISystemColorTracker?)list[i].Target)?.OnSystemColorChanged(); } } } diff --git a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.cs b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.cs index d7052b7ceeba0..816170943318b 100644 --- a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.cs +++ b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.cs @@ -263,10 +263,7 @@ private void EnsureWriteCapacity(int pendingCount) byte[]? oldBytes = _buffer; Array.Resize(ref _buffer, BlockSize * blocks); - if (oldBytes != null) - { - oldBytes.AsSpan(0, _offset).Clear(); - } + oldBytes?.AsSpan(0, _offset).Clear(); #endif #if DEBUG 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 d47a067998b79..5f3198ca15f9b 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 @@ -544,11 +544,8 @@ private void ExtractAsRegularFile(string destinationFileName) // Rely on FileStream's ctor for further checking destinationFileName parameter using (FileStream fs = new FileStream(destinationFileName, CreateFileStreamOptions(isAsync: false))) { - if (DataStream != null) - { - // Important: The DataStream will be written from its current position - DataStream.CopyTo(fs); - } + // Important: The DataStream will be written from its current position + DataStream?.CopyTo(fs); } ArchivingUtils.AttemptSetLastWriteTime(destinationFileName, ModificationTime); diff --git a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarWriter.cs b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarWriter.cs index 7095fc8b55368..4161e36fb8c38 100644 --- a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarWriter.cs +++ b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarWriter.cs @@ -138,10 +138,7 @@ private void ReadFileFromDiskAndWriteToArchiveStreamAsEntry(string fullPath, str TarEntry entry = ConstructEntryForWriting(fullPath, entryName, FileOptions.None); WriteEntry(entry); - if (entry._header._dataStream != null) - { - entry._header._dataStream.Dispose(); - } + entry._header._dataStream?.Dispose(); } // Asynchronously reads an entry from disk and writes it into the archive stream. diff --git a/src/libraries/System.IO.Compression/src/System/IO/Compression/ZipArchive.cs b/src/libraries/System.IO.Compression/src/System/IO/Compression/ZipArchive.cs index 33a4a12205d7e..4ae80c1a480cb 100644 --- a/src/libraries/System.IO.Compression/src/System/IO/Compression/ZipArchive.cs +++ b/src/libraries/System.IO.Compression/src/System/IO/Compression/ZipArchive.cs @@ -204,8 +204,7 @@ public ZipArchive(Stream stream, ZipArchiveMode mode, bool leaveOpen, Encoding? } catch { - if (extraTempStream != null) - extraTempStream.Dispose(); + extraTempStream?.Dispose(); throw; } diff --git a/src/libraries/System.IO.Compression/src/System/IO/Compression/ZipArchiveEntry.cs b/src/libraries/System.IO.Compression/src/System/IO/Compression/ZipArchiveEntry.cs index b5c9859e6069f..781e1a8881b90 100644 --- a/src/libraries/System.IO.Compression/src/System/IO/Compression/ZipArchiveEntry.cs +++ b/src/libraries/System.IO.Compression/src/System/IO/Compression/ZipArchiveEntry.cs @@ -1063,8 +1063,7 @@ private void WriteDataDescriptor() private void UnloadStreams() { - if (_storedUncompressedData != null) - _storedUncompressedData.Dispose(); + _storedUncompressedData?.Dispose(); _compressedBytes = null; _outstandingWriteStream = null; } @@ -1072,10 +1071,7 @@ private void UnloadStreams() private void CloseStreams() { // if the user left the stream open, close the underlying stream for them - if (_outstandingWriteStream != null) - { - _outstandingWriteStream.Dispose(); - } + _outstandingWriteStream?.Dispose(); } private void VersionToExtractAtLeast(ZipVersionNeededValues value) diff --git a/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/IsolatedStorageFileStream.cs b/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/IsolatedStorageFileStream.cs index 7133e760cf24d..f0d98f765bafa 100644 --- a/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/IsolatedStorageFileStream.cs +++ b/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/IsolatedStorageFileStream.cs @@ -206,8 +206,7 @@ protected override void Dispose(bool disposing) { if (disposing) { - if (_fs != null) - _fs.Dispose(); + _fs?.Dispose(); } } finally 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 ec906ee1e9891..80a4041860279 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 @@ -453,8 +453,7 @@ void IDisposable.Dispose() // close core properties // This method will write out the core properties to the stream // These will get flushed to the disk as a part of the DoFlush operation - if (_packageProperties != null) - _packageProperties.Close(); + _packageProperties?.Close(); // flush relationships FlushRelationships(); @@ -507,8 +506,7 @@ public void Flush() // Write core properties. // This call will write out the xml for the core properties to the stream // These properties will get flushed to disk as a part of the DoFlush operation - if (_packageProperties != null) - _packageProperties.Flush(); + _packageProperties?.Flush(); // Write package relationships XML to the relationship part stream. // These will get flushed to disk as a part of the DoFlush operation @@ -737,10 +735,7 @@ protected virtual void Dispose(bool disposing) { if (!_disposed && disposing) { - if (_partList != null) - { - _partList.Clear(); - } + _partList?.Clear(); if (_packageProperties != null) { @@ -1005,8 +1000,7 @@ private void EnsureRelationships() //Delete All Package-level Relationships private void ClearRelationships() { - if (_relationships != null) - _relationships.Clear(); + _relationships?.Clear(); } //Flush the relationships at package level diff --git a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackagePart.cs b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackagePart.cs index 7ce1382728465..8340ac629f173 100644 --- a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackagePart.cs +++ b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackagePart.cs @@ -578,8 +578,7 @@ internal ContentType ValidatedContentType //Delete all the relationships for this part internal void ClearRelationships() { - if (_relationships != null) - _relationships.Clear(); + _relationships?.Clear(); } //Flush all the streams that are currently opened for this part and the relationships for this part diff --git a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/XmlCompatibilityReader.cs b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/XmlCompatibilityReader.cs index 1695a4ff1e6a8..aad18a208eb4a 100644 --- a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/XmlCompatibilityReader.cs +++ b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/XmlCompatibilityReader.cs @@ -722,11 +722,11 @@ private string GetMappedNamespace(string namespaceName) // if the namespace has not yet been mapped, map it mappedNamespace = MapNewNamespace(namespaceName); } - else if (mappedNamespace == null) + else { // if the mapped namespace is null, then the namespace was not supported, just return // the given namespace - mappedNamespace = namespaceName; + mappedNamespace ??= namespaceName; } return mappedNamespace; @@ -1644,19 +1644,13 @@ public bool ShouldProcessContent(string namespaceName, string elementName) public void Ignorable(string namespaceName) { - if (_ignorables == null) - { - _ignorables = new Dictionary(); - } + _ignorables ??= new Dictionary(); _ignorables[namespaceName] = null; // we don't care about value, just key } public void ProcessContent(string namespaceName, string elementName) { - if (_processContents == null) - { - _processContents = new Dictionary(); - } + _processContents ??= new Dictionary(); ProcessContentSet? processContentSet; if (!_processContents.TryGetValue(namespaceName, out processContentSet)) { @@ -1668,10 +1662,7 @@ public void ProcessContent(string namespaceName, string elementName) public void PreserveElement(string namespaceName, string elementName) { - if (_preserveElements == null) - { - _preserveElements = new Dictionary(); - } + _preserveElements ??= new Dictionary(); PreserveItemSet? preserveElementSet; if (!_preserveElements.TryGetValue(namespaceName, out preserveElementSet)) { @@ -1683,10 +1674,7 @@ public void PreserveElement(string namespaceName, string elementName) public void PreserveAttribute(string namespaceName, string attributeName) { - if (_preserveAttributes == null) - { - _preserveAttributes = new Dictionary(); - } + _preserveAttributes ??= new Dictionary(); PreserveItemSet? preserveAttributeSet; if (!_preserveAttributes.TryGetValue(namespaceName, out preserveAttributeSet)) { diff --git a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ZipPackage.cs b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ZipPackage.cs index b14ac61ec49f7..c2cf548b6093c 100644 --- a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ZipPackage.cs +++ b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ZipPackage.cs @@ -109,11 +109,8 @@ protected override void DeletePartCore(Uri partUri) string partZipName = GetZipItemNameFromOpcName(PackUriHelper.GetStringForPartUri(partUri)); ZipArchiveEntry? zipArchiveEntry = _zipArchive.GetEntry(partZipName); - if (zipArchiveEntry != null) - { - // Case of an atomic part. - zipArchiveEntry.Delete(); - } + // Case of an atomic part. + zipArchiveEntry?.Delete(); //Delete the content type for this part if it was specified as an override _contentTypeHelper.DeleteContentType((PackUriHelper.ValidatedPartUri)partUri); @@ -339,10 +336,7 @@ internal ZipPackage(Stream s, FileMode packageFileMode, FileAccess packageFileAc } catch { - if (zipArchive != null) - { - zipArchive.Dispose(); - } + zipArchive?.Dispose(); throw; } 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 8f1e6ce4df110..187c22ba58596 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 @@ -1024,11 +1024,8 @@ public string ReadTo(string value) _readLen += _internalSerialStream.Read(_inBuffer, _readLen, bytesInStream); - if (_singleCharBuffer == null) - { - // This is somewhat of an approximate guesstimate to get the max char[] size needed to encode a single character - _singleCharBuffer = new char[_maxByteCountForSingleChar]; - } + // This is somewhat of an approximate guesstimate to get the max char[] size needed to encode a single character + _singleCharBuffer ??= new char[_maxByteCountForSingleChar]; try { diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LocalVariables.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LocalVariables.cs index 8e64650368414..784e83f305579 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LocalVariables.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LocalVariables.cs @@ -157,10 +157,7 @@ public bool TryGetLocalOrClosure(ParameterExpression var, [NotNullWhen(true)] ou internal LocalVariable AddClosureVariable(ParameterExpression variable) { - if (_closureVariables == null) - { - _closureVariables = new Dictionary(); - } + _closureVariables ??= new Dictionary(); LocalVariable result = new LocalVariable(_closureVariables.Count, true); _closureVariables.Add(variable, result); return result; diff --git a/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/CallSite.cs b/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/CallSite.cs index db739708ff44b..b98c8ec25afd9 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/CallSite.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/CallSite.cs @@ -221,18 +221,11 @@ private T GetUpdateDelegate() return GetUpdateDelegate(ref s_cachedUpdate); } - private T GetUpdateDelegate(ref T? addr) - { - if (addr == null) - { - // reduce creation cost by not using Interlocked.CompareExchange. Calling I.CE causes - // us to spend 25% of our creation time in JIT_GenericHandle. Instead we'll rarely - // create 2 delegates with no other harm caused. - addr = MakeUpdateDelegate(); - } - return addr; - } - + private T GetUpdateDelegate(ref T? addr) => + // reduce creation cost by not using Interlocked.CompareExchange. Calling I.CE causes + // us to spend 25% of our creation time in JIT_GenericHandle. Instead we'll rarely + // create 2 delegates with no other harm caused. + addr ??= MakeUpdateDelegate(); private const int MaxRules = 10; diff --git a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Channels/AsynchronousChannel.cs b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Channels/AsynchronousChannel.cs index d0e60aff91e6d..95c8d1f658ba1 100644 --- a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Channels/AsynchronousChannel.cs +++ b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Channels/AsynchronousChannel.cs @@ -235,10 +235,7 @@ internal void SetDone() // remove the lock. lock (this) { - if (_consumerEvent != null) - { - _consumerEvent.Set(_index); - } + _consumerEvent?.Set(_index); } } //----------------------------------------------------------------------------------- diff --git a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Enumerables/EmptyEnumerable.cs b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Enumerables/EmptyEnumerable.cs index 3d675df1796a4..1556040c70058 100644 --- a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Enumerables/EmptyEnumerable.cs +++ b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Enumerables/EmptyEnumerable.cs @@ -30,30 +30,13 @@ private EmptyEnumerable() private static volatile EmptyEnumerable? s_instance; private static volatile EmptyEnumerator? s_enumeratorInstance; - internal static EmptyEnumerable Instance - { - get - { - if (s_instance == null) - { - // There is no need for thread safety here. - s_instance = new EmptyEnumerable(); - } - - return s_instance; - } - } + internal static EmptyEnumerable Instance => + // There is no need for thread safety here. + s_instance ??= new EmptyEnumerable(); - public override IEnumerator GetEnumerator() - { - if (s_enumeratorInstance == null) - { - // There is no need for thread safety here. - s_enumeratorInstance = new EmptyEnumerator(); - } - - return s_enumeratorInstance; - } + public override IEnumerator GetEnumerator() => + // There is no need for thread safety here. + s_enumeratorInstance ??= new EmptyEnumerator(); } internal sealed class EmptyEnumerator : QueryOperatorEnumerator, IEnumerator diff --git a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Binary/UnionQueryOperator.cs b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Binary/UnionQueryOperator.cs index eefc4629c4ff8..132e10dce0939 100644 --- a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Binary/UnionQueryOperator.cs +++ b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Binary/UnionQueryOperator.cs @@ -284,14 +284,8 @@ internal override bool MoveNext([MaybeNullWhen(false), AllowNull] ref TInputOutp protected override void Dispose(bool disposing) { - if (_leftSource != null) - { - _leftSource.Dispose(); - } - if (_rightSource != null) - { - _rightSource.Dispose(); - } + _leftSource?.Dispose(); + _rightSource?.Dispose(); } } diff --git a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Unary/DistinctQueryOperator.cs b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Unary/DistinctQueryOperator.cs index 5ebbefa0be9a4..50373196ebf98 100644 --- a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Unary/DistinctQueryOperator.cs +++ b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Unary/DistinctQueryOperator.cs @@ -270,10 +270,7 @@ protected override void Dispose(bool disposing) Debug.Assert(_source != null); _source.Dispose(); - if (_hashLookupEnumerator != null) - { - _hashLookupEnumerator.Dispose(); - } + _hashLookupEnumerator?.Dispose(); } } } diff --git a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Unary/SelectManyQueryOperator.cs b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Unary/SelectManyQueryOperator.cs index 769bacece22d6..624ac920293fc 100644 --- a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Unary/SelectManyQueryOperator.cs +++ b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Unary/SelectManyQueryOperator.cs @@ -351,10 +351,7 @@ internal override bool MoveNext([MaybeNullWhen(false), AllowNull] ref TOutput cu protected override void Dispose(bool disposing) { _leftSource.Dispose(); - if (_currentRightSource != null) - { - _currentRightSource.Dispose(); - } + _currentRightSource?.Dispose(); } } @@ -483,10 +480,7 @@ internal override bool MoveNext([MaybeNullWhen(false), AllowNull] ref TOutput cu protected override void Dispose(bool disposing) { _leftSource.Dispose(); - if (_currentRightSource != null) - { - _currentRightSource.Dispose(); - } + _currentRightSource?.Dispose(); } } } diff --git a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Scheduling/QueryTaskGroupState.cs b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Scheduling/QueryTaskGroupState.cs index 859c74931749e..c3dff145ea172 100644 --- a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Scheduling/QueryTaskGroupState.cs +++ b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Scheduling/QueryTaskGroupState.cs @@ -133,9 +133,7 @@ internal void QueryEnd(bool userInitiatedDispose) finally { //_rootTask don't support Dispose on some platforms - IDisposable disposable = _rootTask as IDisposable; - if (disposable != null) - disposable.Dispose(); + (_rootTask as IDisposable)?.Dispose(); } if (_cancellationState.MergedCancellationToken.IsCancellationRequested) diff --git a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Scheduling/SpoolingTask.cs b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Scheduling/SpoolingTask.cs index 55cfdc28c6682..198fd693c458d 100644 --- a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Scheduling/SpoolingTask.cs +++ b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Scheduling/SpoolingTask.cs @@ -246,10 +246,7 @@ protected override void SpoolingFinally() base.SpoolingFinally(); // Signal that we are done, in the case of asynchronous consumption. - if (_destination != null) - { - _destination.SetDone(); - } + _destination?.SetDone(); // Dispose of the source enumerator *after* signaling that the task is done. // We call Dispose() last to ensure that if it throws an exception, we will not cause a deadlock. @@ -338,10 +335,7 @@ protected override void SpoolingFinally() base.SpoolingFinally(); // Signal that we are done, in the case of asynchronous consumption. - if (_destination != null) - { - _destination.SetDone(); - } + _destination?.SetDone(); // Dispose of the source enumerator *after* signaling that the task is done. // We call Dispose() last to ensure that if it throws an exception, we will not cause a deadlock. diff --git a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Utils/Sorting.cs b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Utils/Sorting.cs index 4bfc75ce850dc..5a0fb29343b15 100644 --- a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Utils/Sorting.cs +++ b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Utils/Sorting.cs @@ -167,11 +167,7 @@ public void Dispose() { for (int j = 0; j < _sharedBarriers[i].Length; j++) { - Barrier b = _sharedBarriers[i][j]; - if (b != null) - { - b.Dispose(); - } + _sharedBarriers[i][j]?.Dispose(); } } } diff --git a/src/libraries/System.Linq.Queryable/src/System/Linq/EnumerableRewriter.cs b/src/libraries/System.Linq.Queryable/src/System/Linq/EnumerableRewriter.cs index 9a0e36f5fb97f..17cedfed6291f 100644 --- a/src/libraries/System.Linq.Queryable/src/System/Linq/EnumerableRewriter.cs +++ b/src/libraries/System.Linq.Queryable/src/System/Linq/EnumerableRewriter.cs @@ -171,17 +171,14 @@ static bool TryGetImplementedIEnumerable(Type type, [NotNullWhen(true)] out Type private Type GetEquivalentType(Type type) { Type? equiv; - if (_equivalentTypeCache == null) - { - // Pre-loading with the non-generic IQueryable and IEnumerable not only covers this case - // without any reflection-based introspection, but also means the slightly different - // code needed to catch this case can be omitted safely. - _equivalentTypeCache = new Dictionary + // Pre-loading with the non-generic IQueryable and IEnumerable not only covers this case + // without any reflection-based introspection, but also means the slightly different + // code needed to catch this case can be omitted safely. + _equivalentTypeCache ??= new Dictionary { { typeof(IQueryable), typeof(IEnumerable) }, { typeof(IEnumerable), typeof(IEnumerable) } }; - } if (!_equivalentTypeCache.TryGetValue(type, out equiv)) { Type pubType = GetPublicType(type); diff --git a/src/libraries/System.Management/src/System/Management/ManagementClass.cs b/src/libraries/System.Management/src/System/Management/ManagementClass.cs index 24f280e1606d0..86e691f562bda 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementClass.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementClass.cs @@ -473,8 +473,7 @@ public ManagementObjectCollection GetInstances(EnumerationOptions options) } finally { - if (securityHandler != null) - securityHandler.Reset(); + securityHandler?.Reset(); } if (status < 0) @@ -604,8 +603,7 @@ public void GetInstances(ManagementOperationObserver watcher, EnumerationOptions ClassName, o.Flags, o.GetContext(), sink.Stub); - if (securityHandler != null) - securityHandler.Reset(); + securityHandler?.Reset(); if (status < 0) { @@ -691,8 +689,7 @@ public ManagementObjectCollection GetSubclasses(EnumerationOptions options) } finally { - if (securityHandler != null) - securityHandler.Reset(); + securityHandler?.Reset(); } if (status < 0) @@ -758,8 +755,7 @@ public void GetSubclasses(ManagementOperationObserver watcher, ClassName, o.Flags, o.GetContext(), sink.Stub); - if (securityHandler != null) - securityHandler.Reset(); + securityHandler?.Reset(); if (status < 0) { @@ -1049,8 +1045,7 @@ public ManagementObjectCollection GetRelatedClasses( } finally { - if (securityHandler != null) - securityHandler.Reset(); + securityHandler?.Reset(); } if (status < 0) @@ -1153,8 +1148,7 @@ public void GetRelatedClasses( q.QueryLanguage, q.QueryString, o.Flags, o.GetContext(), sink.Stub); - if (securityHandler != null) - securityHandler.Reset(); + securityHandler?.Reset(); if (status < 0) { @@ -1248,8 +1242,7 @@ public ManagementObjectCollection GetRelationshipClasses( } finally { - if (securityHandler != null) - securityHandler.Reset(); + securityHandler?.Reset(); } if (status < 0) @@ -1341,8 +1334,7 @@ public void GetRelationshipClasses( q.QueryLanguage, q.QueryString, o.Flags, o.GetContext(), sink.Stub); - if (securityHandler != null) - securityHandler.Reset(); + securityHandler?.Reset(); if (status < 0) { diff --git a/src/libraries/System.Management/src/System/Management/ManagementObject.cs b/src/libraries/System.Management/src/System/Management/ManagementObject.cs index 26bc04d259ab2..18b70aa9b6ecf 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementObject.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementObject.cs @@ -795,8 +795,7 @@ public void Get() } finally { - if (securityHandler != null) - securityHandler.Reset(); + securityHandler?.Reset(); } } } @@ -915,8 +914,7 @@ public void Get(ManagementOperationObserver watcher) sink.Stub); - if (securityHandler != null) - securityHandler.Reset(); + securityHandler?.Reset(); if (status < 0) { @@ -1066,8 +1064,7 @@ public ManagementObjectCollection GetRelated( } finally { - if (securityHandler != null) - securityHandler.Reset(); + securityHandler?.Reset(); } //Create collection object @@ -1299,8 +1296,7 @@ public ManagementObjectCollection GetRelationships( } finally { - if (securityHandler != null) - securityHandler.Reset(); + securityHandler?.Reset(); } //Create collection object @@ -1406,8 +1402,7 @@ public void GetRelationships( sink.Stub); - if (securityHandler != null) - securityHandler.Reset(); + securityHandler?.Reset(); if (status < 0) { @@ -1514,8 +1509,7 @@ public ManagementPath Put(PutOptions options) } finally { - if (securityHandler != null) - securityHandler.Reset(); + securityHandler?.Reset(); if (ppwbemCallResult != IntPtr.Zero) // Cleanup from allocations above. Marshal.FreeHGlobal(ppwbemCallResult); @@ -1654,8 +1648,7 @@ public void Put(ManagementOperationObserver watcher, PutOptions options) } - if (securityHandler != null) - securityHandler.Reset(); + securityHandler?.Reset(); if (status < 0) { @@ -1814,8 +1807,7 @@ public ManagementPath CopyTo(ManagementPath path, PutOptions options) } finally { - if (securityHandler != null) - securityHandler.Reset(); + securityHandler?.Reset(); if (ppwbemCallResult != IntPtr.Zero) // Cleanup from allocations above. Marshal.FreeHGlobal(ppwbemCallResult); @@ -1913,8 +1905,7 @@ public void CopyTo(ManagementOperationObserver watcher, ManagementPath path, Put } - if (securityHandler != null) - securityHandler.Reset(); + securityHandler?.Reset(); if (status < 0) { @@ -1989,8 +1980,7 @@ public void Delete(DeleteOptions options) } finally { - if (securityHandler != null) - securityHandler.Reset(); + securityHandler?.Reset(); } } @@ -2048,8 +2038,7 @@ public void Delete(ManagementOperationObserver watcher, DeleteOptions options) } - if (securityHandler != null) - securityHandler.Reset(); + securityHandler?.Reset(); if (status < 0) { @@ -2322,8 +2311,7 @@ public ManagementBaseObject InvokeMethod( } finally { - if (securityHandler != null) - securityHandler.Reset(); + securityHandler?.Reset(); } } @@ -2383,8 +2371,7 @@ public void InvokeMethod( inParams, sink.Stub); - if (securityHandler != null) - securityHandler.Reset(); + securityHandler?.Reset(); if (status < 0) { @@ -2670,8 +2657,7 @@ internal override void Initialize(bool getObject) } finally { - if (securityHandler != null) - securityHandler.Reset(); + securityHandler?.Reset(); } } } diff --git a/src/libraries/System.Management/src/System/Management/ManagementQuery.cs b/src/libraries/System.Management/src/System/Management/ManagementQuery.cs index 64816f8c3a0cd..0a5e548c75f6b 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementQuery.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementQuery.cs @@ -964,8 +964,7 @@ protected internal override void ParseQuery(string query) //Clear out previous property values className = null; condition = null; - if (selectedProperties != null) - selectedProperties.Clear(); + selectedProperties?.Clear(); //Trim whitespaces string q = query.Trim(); @@ -3024,8 +3023,7 @@ protected internal override void ParseQuery(string query) withinInterval = TimeSpan.Zero; condition = null; groupWithinInterval = TimeSpan.Zero; - if (groupByPropertyList != null) - groupByPropertyList.Clear(); + groupByPropertyList?.Clear(); havingCondition = null; //Trim whitespaces diff --git a/src/libraries/System.Management/src/System/Management/ManagementScope.cs b/src/libraries/System.Management/src/System/Management/ManagementScope.cs index 720b15e200057..79e2f1558863f 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementScope.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementScope.cs @@ -68,10 +68,7 @@ e is System.Threading.ThreadAbortException || finally { // dispose of the key - if (s_switchesRegKey != null) - { - s_switchesRegKey.Dispose(); - } + s_switchesRegKey?.Dispose(); } // if for any reason we cannot retrieve the value of the switch from the Registry, diff --git a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestCallback.cs b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestCallback.cs index a8e3ef9558f53..c8e2ca4090285 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestCallback.cs +++ b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestCallback.cs @@ -109,18 +109,16 @@ private static void RequestCallback( catch (Exception ex) { state.SavedException = ex; - if (state.RequestHandle != null) - { - // Since we got a fatal error processing the request callback, - // we need to close the WinHttp request handle in order to - // abort the currently executing WinHttp async operation. - // - // We must always call Dispose() against the SafeWinHttpHandle - // wrapper and never close directly the raw WinHttp handle. - // The SafeWinHttpHandle wrapper is thread-safe and guarantees - // calling the underlying WinHttpCloseHandle() function only once. - state.RequestHandle.Dispose(); - } + + // Since we got a fatal error processing the request callback, + // we need to close the WinHttp request handle in order to + // abort the currently executing WinHttp async operation. + // + // We must always call Dispose() against the SafeWinHttpHandle + // wrapper and never close directly the raw WinHttp handle. + // The SafeWinHttpHandle wrapper is thread-safe and guarantees + // calling the underlying WinHttpCloseHandle() function only once. + state.RequestHandle?.Dispose(); } } @@ -310,11 +308,7 @@ private static void OnRequestSendingRequest(WinHttpRequestState state) } finally { - if (chain != null) - { - chain.Dispose(); - } - + chain?.Dispose(); serverCertificate.Dispose(); } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/DelegatingHandler.cs b/src/libraries/System.Net.Http/src/System/Net/Http/DelegatingHandler.cs index 2178e1b3a02ce..cb6d1ed4cc70c 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/DelegatingHandler.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/DelegatingHandler.cs @@ -63,10 +63,7 @@ protected override void Dispose(bool disposing) if (disposing && !_disposed) { _disposed = true; - if (_innerHandler != null) - { - _innerHandler.Dispose(); - } + _innerHandler?.Dispose(); } base.Dispose(disposing); diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpRequestMessage.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpRequestMessage.cs index e4cb6d90cc31b..4a9470d7b85e3 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpRequestMessage.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpRequestMessage.cs @@ -177,10 +177,7 @@ protected virtual void Dispose(bool disposing) if (disposing && !_disposed) { _disposed = true; - if (_content != null) - { - _content.Dispose(); - } + _content?.Dispose(); } } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpResponseMessage.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpResponseMessage.cs index 45799f11965e5..50eb9daba380d 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpResponseMessage.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpResponseMessage.cs @@ -216,10 +216,7 @@ protected virtual void Dispose(bool disposing) if (disposing && !_disposed) { _disposed = true; - if (_content != null) - { - _content.Dispose(); - } + _content?.Dispose(); } } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnection.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnection.cs index de5973e46780e..e42c83bbd60be 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnection.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnection.cs @@ -200,12 +200,9 @@ public bool PrepareForReuse(bool async) public override bool CheckUsabilityOnScavenge() { // We may already have a read-ahead task if we did a previous scavenge and haven't used the connection since. - if (_readAheadTask is null) - { #pragma warning disable CA2012 // we're very careful to ensure the ValueTask is only consumed once, even though it's stored into a field - _readAheadTask = ReadAheadWithZeroByteReadAsync(); + _readAheadTask ??= ReadAheadWithZeroByteReadAsync(); #pragma warning restore CA2012 - } // If the read-ahead task is completed, then we've received either EOF or erroneous data the connection, so it's not usable. return !_readAheadTask.Value.IsCompleted; diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpConnection.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpConnection.cs index 96a85b9339dd1..3927d63b775df 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpConnection.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpConnection.cs @@ -101,9 +101,7 @@ public HttpConnection(Socket sock, HttpEndPointListener epl, bool secure, X509Ce } _timer = new Timer(OnTimeout, null, Timeout.Infinite, Timeout.Infinite); - if (_sslStream != null) { - _sslStream.AuthenticateAsServer (_cert, true, (SslProtocols)ServicePointManager.SecurityProtocol, false); - } + _sslStream?.AuthenticateAsServer(_cert, true, (SslProtocols)ServicePointManager.SecurityProtocol, false); Init(); } @@ -496,9 +494,7 @@ internal void Close(bool force) { if (_socket != null) { - Stream st = GetResponseStream(); - if (st != null) - st.Close(); + GetResponseStream()?.Close(); _responseStream = null; } @@ -532,16 +528,14 @@ internal void Close(bool force) _socket = null; try { - if (s != null) - s.Shutdown(SocketShutdown.Both); + s?.Shutdown(SocketShutdown.Both); } catch { } finally { - if (s != null) - s.Close(); + s?.Close(); } Unbind(); RemoveConnection(); diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListener.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListener.Managed.cs index a709cf3dffbc3..a202354e77e3e 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListener.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListener.Managed.cs @@ -207,10 +207,7 @@ internal void RegisterContext(HttpListenerContext context) } } - if (ares != null) - { - ares.Complete(context); - } + ares?.Complete(context); } private void Cleanup(bool close_existing) diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpStreamAsyncResult.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpStreamAsyncResult.cs index 53be0f5793dcd..eb1b9bebcf799 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpStreamAsyncResult.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpStreamAsyncResult.cs @@ -69,8 +69,7 @@ public void Complete() return; _completed = true; - if (_handle != null) - _handle.Set(); + _handle?.Set(); if (_callback != null) Task.Run(() => _callback(this)); diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ListenerAsyncResult.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ListenerAsyncResult.Managed.cs index 4e7d5b4666b5f..9cf9322402018 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ListenerAsyncResult.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ListenerAsyncResult.Managed.cs @@ -71,8 +71,7 @@ internal void Complete(Exception exc) lock (_locker) { _completed = true; - if (_handle != null) - _handle.Set(); + _handle?.Set(); if (_cb != null) ThreadPool.UnsafeQueueUserWorkItem(s_invokeCB, this); @@ -177,8 +176,7 @@ internal void Complete(HttpListenerContext context, bool synch) _completed = true; _synch = false; - if (_handle != null) - _handle.Set(); + _handle?.Set(); if (_cb != null) ThreadPool.UnsafeQueueUserWorkItem(s_invokeCB, this); 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 7a530aae5f0a0..11a0f6345f91e 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 @@ -997,10 +997,7 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) } finally { - if (userContext != null) - { - userContext.Dispose(); - } + userContext?.Dispose(); } } else @@ -1161,10 +1158,7 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) Debug.Assert(disconnectResult != null); disconnectResult!.Session = newContext; - if (toClose != null) - { - toClose.CloseContext(); - } + toClose?.CloseContext(); } // Send the 401 here. @@ -1232,10 +1226,7 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) { // Check if the connection got deleted while in this method, and clear out the hashtables if it did. // In a nested finally because if this doesn't happen, we leak. - if (disconnectResult != null) - { - disconnectResult.FinishOwningDisconnectHandling(); - } + disconnectResult?.FinishOwningDisconnectHandling(); } } } @@ -1879,10 +1870,7 @@ private void HandleDisconnect() if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"DisconnectResults {listener.DisconnectResults} removing for _connectionId: {_connectionId}"); listener.DisconnectResults.Remove(_connectionId); - if (_session != null) - { - _session.CloseContext(); - } + _session?.CloseContext(); // Clean up the identity. This is for scenarios where identity was not cleaned up before due to // identity caching for unsafe ntlm authentication diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequest.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequest.Windows.cs index 8807cdc5ec607..c1dca80c03d85 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequest.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequest.Windows.cs @@ -273,10 +273,7 @@ public IPEndPoint RemoteEndPoint { get { - if (_remoteEndPoint == null) - { - _remoteEndPoint = Interop.HttpApi.GetRemoteEndPoint(RequestBuffer, OriginalBlobAddress); - } + _remoteEndPoint ??= Interop.HttpApi.GetRemoteEndPoint(RequestBuffer, OriginalBlobAddress); if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "_remoteEndPoint" + _remoteEndPoint); return _remoteEndPoint!; } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBase.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBase.cs index e39b53f4f970a..f29b9f186a743 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBase.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBase.cs @@ -83,10 +83,7 @@ protected WebSocketBase(Stream innerStream, _closeStatus = null; _closeStatusDescription = null; _innerStreamAsWebSocketStream = innerStream as IWebSocketStream; - if (_innerStreamAsWebSocketStream != null) - { - _innerStreamAsWebSocketStream.SwitchToOpaqueMode(this); - } + _innerStreamAsWebSocketStream?.SwitchToOpaqueMode(this); _keepAliveTracker = KeepAliveTracker.Create(keepAliveInterval); } @@ -372,10 +369,7 @@ public override void Abort() _sendOutstandingOperationHelper.CancelIO(); _closeOutputOutstandingOperationHelper.CancelIO(); _closeOutstandingOperationHelper.CancelIO(); - if (_innerStreamAsWebSocketStream != null) - { - _innerStreamAsWebSocketStream.Abort(); - } + _innerStreamAsWebSocketStream?.Abort(); CleanUp(); } finally @@ -564,11 +558,8 @@ private async Task StartOnCloseCompleted(bool thisLockTakenSnapshot, try { - if (_closeNetworkConnectionTask == null) - { - _closeNetworkConnectionTask = - _innerStreamAsWebSocketStream.CloseNetworkConnectionAsync(cancellationToken); - } + _closeNetworkConnectionTask ??= + _innerStreamAsWebSocketStream.CloseNetworkConnectionAsync(cancellationToken); if (thisLockTaken && sessionHandleLockTaken) { @@ -960,10 +951,7 @@ private void EnsureCloseOutputOperation() { lock (_thisLock) { - if (_closeOutputOperation == null) - { - _closeOutputOperation = new WebSocketOperation.CloseOutputOperation(this); - } + _closeOutputOperation ??= new WebSocketOperation.CloseOutputOperation(this); } } } @@ -1157,35 +1145,12 @@ private void CleanUp() _cleanedUp = true; - if (SessionHandle != null) - { - SessionHandle.Dispose(); - } - - if (_internalBuffer != null) - { - _internalBuffer.Dispose(this.State); - } - - if (_receiveOutstandingOperationHelper != null) - { - _receiveOutstandingOperationHelper.Dispose(); - } - - if (_sendOutstandingOperationHelper != null) - { - _sendOutstandingOperationHelper.Dispose(); - } - - if (_closeOutputOutstandingOperationHelper != null) - { - _closeOutputOutstandingOperationHelper.Dispose(); - } - - if (_closeOutstandingOperationHelper != null) - { - _closeOutstandingOperationHelper.Dispose(); - } + SessionHandle?.Dispose(); + _internalBuffer?.Dispose(this.State); + _receiveOutstandingOperationHelper?.Dispose(); + _sendOutstandingOperationHelper?.Dispose(); + _closeOutputOutstandingOperationHelper?.Dispose(); + _closeOutstandingOperationHelper?.Dispose(); if (_innerStream != null) { @@ -2104,10 +2069,7 @@ public void CompleteOperation(bool ownsCancellationTokenSource) } } - if (snapshot != null) - { - snapshot.Dispose(); - } + snapshot?.Dispose(); } // Has to be called under _ThisLock lock @@ -2169,10 +2131,7 @@ public void Dispose() _cancellationTokenSource = null; } - if (snapshot != null) - { - snapshot.Dispose(); - } + snapshot?.Dispose(); } private void ThrowIfDisposed() diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketHttpListenerDuplexStream.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketHttpListenerDuplexStream.cs index d32841971016e..406ecafc1eeeb 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketHttpListenerDuplexStream.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketHttpListenerDuplexStream.cs @@ -597,22 +597,12 @@ protected override void Dispose(bool disposing) { if (disposing && Interlocked.Exchange(ref _cleanedUp, 1) == 0) { - if (_readTaskCompletionSource != null) - { - _readTaskCompletionSource.TrySetCanceled(); - } + _readTaskCompletionSource?.TrySetCanceled(); _writeTaskCompletionSource?.TrySetCanceled(); - if (_readEventArgs != null) - { - _readEventArgs.Dispose(); - } - - if (_writeEventArgs != null) - { - _writeEventArgs.Dispose(); - } + _readEventArgs?.Dispose(); + _writeEventArgs?.Dispose(); try { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketProtocolComponent.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketProtocolComponent.cs index 53da835ab8165..8381a7831e3e5 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketProtocolComponent.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketProtocolComponent.cs @@ -195,10 +195,7 @@ internal static string GetSupportedVersion() } finally { - if (webSocketHandle != null) - { - webSocketHandle.Dispose(); - } + webSocketHandle?.Dispose(); } } 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 21b82f7b9a0a5..9487709fd2344 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 @@ -299,18 +299,9 @@ protected virtual void Dispose(bool disposing) { _disposed = true; - if (_views != null) - { - _views.Dispose(); - } - if (_attachments != null) - { - _attachments.Dispose(); - } - if (_bodyView != null) - { - _bodyView.Dispose(); - } + _views?.Dispose(); + _attachments?.Dispose(); + _bodyView?.Dispose(); } } diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs index ce53964d46755..017805a111d45 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs @@ -542,10 +542,7 @@ e is AuthenticationException || finally { InCall = false; - if (_timer != null) - { - _timer.Dispose(); - } + _timer?.Dispose(); } } @@ -633,8 +630,7 @@ public void SendAsync(MailMessage message, object? userToken) ValidateUnicodeRequirement(message, _recipients, allowUnicode); message.Send(_writer, true, allowUnicode); - if (_writer != null) - _writer.Close(); + _writer?.Close(); AsyncCompletedEventArgs eventArgs = new AsyncCompletedEventArgs(null, false, _asyncOp.UserSuppliedState); InCall = false; diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpNegotiateAuthenticationModule.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpNegotiateAuthenticationModule.cs index 0447b01e9ae55..faf36ea008969 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpNegotiateAuthenticationModule.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpNegotiateAuthenticationModule.cs @@ -108,10 +108,7 @@ public void CloseContext(object sessionCookie) _sessions.Remove(sessionCookie); } } - if (clientContext != null) - { - clientContext.CloseContext(); - } + clientContext?.CloseContext(); } // Function for SASL security layer negotiation after diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpReplyReaderFactory.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpReplyReaderFactory.cs index a13e89be80791..dc60300bce1c1 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpReplyReaderFactory.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpReplyReaderFactory.cs @@ -99,10 +99,7 @@ internal static LineInfo EndReadLine(IAsyncResult result) internal SmtpReplyReader GetNextReplyReader() { - if (_currentReader != null) - { - _currentReader.Close(); - } + _currentReader?.Close(); _readState = ReadState.Status0; _currentReader = new SmtpReplyReader(this); diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mime/MimePart.cs b/src/libraries/System.Net.Mail/src/System/Net/Mime/MimePart.cs index 6b78fd200e128..8f2bb67e74183 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mime/MimePart.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mime/MimePart.cs @@ -153,10 +153,7 @@ internal static void Complete(IAsyncResult result, Exception? e) try { - if (context._outputStream != null) - { - context._outputStream.Close(); - } + context._outputStream?.Close(); } catch (Exception ex) { diff --git a/src/libraries/System.Net.Mail/src/System/Net/TrackingValidationObjectDictionary.cs b/src/libraries/System.Net.Mail/src/System/Net/TrackingValidationObjectDictionary.cs index 95da9b720abd7..0c7c4d0985c1c 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/TrackingValidationObjectDictionary.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/TrackingValidationObjectDictionary.cs @@ -170,20 +170,14 @@ public override void Add(string key, string? value) public override void Clear() { - if (_internalObjects != null) - { - _internalObjects.Clear(); - } + _internalObjects?.Clear(); base.Clear(); IsChanged = true; } public override void Remove(string key) { - if (_internalObjects != null) - { - _internalObjects.Remove(key); - } + _internalObjects?.Remove(key); base.Remove(key); IsChanged = true; } diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/UnixNetworkInterface.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/UnixNetworkInterface.cs index 00c5b3a9a3028..444d19bf01a42 100644 --- a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/UnixNetworkInterface.cs +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/UnixNetworkInterface.cs @@ -69,11 +69,8 @@ protected void AddAddress(IPAddress ipAddress, int prefix) { if (IPAddressUtil.IsMulticast(ipAddress)) { - if (_multicastAddresses == null) - { - // Deferred initialization. - _multicastAddresses = new List(); - } + // Deferred initialization. + _multicastAddresses ??= new List(); _multicastAddresses.Add(ipAddress); } diff --git a/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs b/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs index 79b050d75a978..4dd5ff5ac2681 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs @@ -566,8 +566,7 @@ public override WebResponse GetResponse() } // GetRequeststream or BeginGetRequestStream has not finished yet - if (_readAsyncResult != null) - _readAsyncResult.InternalWaitForCompletion(); + _readAsyncResult?.InternalWaitForCompletion(); CheckError(); } @@ -1386,8 +1385,9 @@ private RequestStage FinishRequestStage(RequestStage stage) if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Releasing connection: {connection}"); connection.CloseSocket(); if (_async) - if (_requestCompleteAsyncResult != null) - _requestCompleteAsyncResult.InvokeCallback(); + { + _requestCompleteAsyncResult?.InvokeCallback(); + } } } return prev; @@ -1406,8 +1406,7 @@ private RequestStage FinishRequestStage(RequestStage stage) // request/pipeline can continue if (_methodInfo.IsUpload && !_getRequestStreamStarted) { - if (_stream != null) - _stream.Close(); + _stream?.Close(); } else if (writeResult != null && !writeResult.InternalPeekCompleted) writeResult.InvokeCallback(); @@ -1688,8 +1687,7 @@ internal void DataStreamClosed(CloseExState closeState) { if (!_async) { - if (_connection != null) - _connection.CheckContinuePipeline(); + _connection?.CheckContinuePipeline(); } else { @@ -1699,9 +1697,7 @@ internal void DataStreamClosed(CloseExState closeState) } else { - FtpControlStream? connection = _connection; - if (connection != null) - connection.Abort(ExceptionHelper.RequestAbortedException); + _connection?.Abort(ExceptionHelper.RequestAbortedException); } } } // class FtpWebRequest diff --git a/src/libraries/System.Net.Requests/src/System/Net/HttpWebRequest.cs b/src/libraries/System.Net.Requests/src/System/Net/HttpWebRequest.cs index 86d9b7b13c4ed..09c7f28697d98 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/HttpWebRequest.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/HttpWebRequest.cs @@ -1166,11 +1166,8 @@ private async Task SendRequest(bool async) // are only allowed in the request headers collection and not in the request content headers collection. if (IsWellKnownContentHeader(headerName)) { - if (request.Content == null) - { - // Create empty content so that we can send the entity-body header. - request.Content = new ByteArrayContent(Array.Empty()); - } + // Create empty content so that we can send the entity-body header. + request.Content ??= new ByteArrayContent(Array.Empty()); request.Content.Headers.TryAddWithoutValidation(headerName, _webHeaderCollection[headerName!]); } diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs index bee9708a5ea54..836d4485a4c24 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs @@ -1385,11 +1385,8 @@ public int SendTo(ReadOnlySpan buffer, SocketFlags socketFlags, EndPoint r if (SocketType == SocketType.Dgram) SocketsTelemetry.Log.DatagramSent(); } - if (_rightEndPoint == null) - { - // Save a copy of the EndPoint so we can use it for Create(). - _rightEndPoint = remoteEP; - } + // Save a copy of the EndPoint so we can use it for Create(). + _rightEndPoint ??= remoteEP; return bytesTransferred; } @@ -1834,11 +1831,9 @@ public int ReceiveFrom(Span buffer, SocketFlags socketFlags, ref EndPoint catch { } - if (_rightEndPoint == null) - { - // Save a copy of the EndPoint so we can use it for Create(). - _rightEndPoint = endPointSnapshot; - } + + // Save a copy of the EndPoint so we can use it for Create(). + _rightEndPoint ??= endPointSnapshot; } if (socketException != null) diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/UDPClient.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/UDPClient.cs index dc737f4a4d983..bf6cec5d18507 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/UDPClient.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/UDPClient.cs @@ -746,19 +746,13 @@ public void Connect(string hostname, int port) { ipv4Socket.Connect(address, port); _clientSocket = ipv4Socket; - if (ipv6Socket != null) - { - ipv6Socket.Close(); - } + ipv6Socket?.Close(); } else if (ipv6Socket != null) { ipv6Socket.Connect(address, port); _clientSocket = ipv6Socket; - if (ipv4Socket != null) - { - ipv4Socket.Close(); - } + ipv4Socket?.Close(); } @@ -801,15 +795,8 @@ public void Connect(string hostname, int port) //did we connect? if (!_active) { - if (ipv6Socket != null) - { - ipv6Socket.Close(); - } - - if (ipv4Socket != null) - { - ipv4Socket.Close(); - } + ipv6Socket?.Close(); + ipv4Socket?.Close(); // The connect failed - rethrow the last error we had if (lastex != null) diff --git a/src/libraries/System.Net.WebHeaderCollection/src/System/Net/WebHeaderCollection.cs b/src/libraries/System.Net.WebHeaderCollection/src/System/Net/WebHeaderCollection.cs index ef803b8f8a1af..f28ca8de82104 100644 --- a/src/libraries/System.Net.WebHeaderCollection/src/System/Net/WebHeaderCollection.cs +++ b/src/libraries/System.Net.WebHeaderCollection/src/System/Net/WebHeaderCollection.cs @@ -260,10 +260,7 @@ public override string GetKey(int index) public override void Clear() { InvalidateCachedArrays(); - if (_innerCollection != null) - { - _innerCollection.Clear(); - } + _innerCollection?.Clear(); } public override string? Get(int index) diff --git a/src/libraries/System.Private.CoreLib/src/Internal/Win32/RegistryKey.cs b/src/libraries/System.Private.CoreLib/src/Internal/Win32/RegistryKey.cs index 9df331d4ab2a2..9bc76f0513f69 100644 --- a/src/libraries/System.Private.CoreLib/src/Internal/Win32/RegistryKey.cs +++ b/src/libraries/System.Private.CoreLib/src/Internal/Win32/RegistryKey.cs @@ -37,10 +37,7 @@ private RegistryKey(SafeRegistryHandle hkey) void IDisposable.Dispose() { - if (_hkey != null) - { - _hkey.Dispose(); - } + _hkey?.Dispose(); } public void DeleteValue(string name, bool throwOnMissingValue) diff --git a/src/libraries/System.Private.CoreLib/src/System/Array.cs b/src/libraries/System.Private.CoreLib/src/System/Array.cs index 82c2ccc831430..32435ec4367ec 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Array.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Array.cs @@ -2469,13 +2469,11 @@ private void DownHeap(int i, int n, int lo) break; keys.SetValue(keys.GetValue(lo + child - 1), lo + i - 1); - if (items != null) - items.SetValue(items.GetValue(lo + child - 1), lo + i - 1); + items?.SetValue(items.GetValue(lo + child - 1), lo + i - 1); i = child; } keys.SetValue(d, lo + i - 1); - if (items != null) - items.SetValue(dt, lo + i - 1); + items?.SetValue(dt, lo + i - 1); } private void InsertionSort(int lo, int hi) @@ -2492,14 +2490,12 @@ private void InsertionSort(int lo, int hi) while (j >= lo && comparer.Compare(t, keys.GetValue(j)) < 0) { keys.SetValue(keys.GetValue(j), j + 1); - if (items != null) - items.SetValue(items.GetValue(j), j + 1); + items?.SetValue(items.GetValue(j), j + 1); j--; } keys.SetValue(t, j + 1); - if (items != null) - items.SetValue(dt, j + 1); + items?.SetValue(dt, j + 1); } } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs index d71b3a3ff26e5..11b9b5fa38f34 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs @@ -578,8 +578,7 @@ public static void SetCurrentThreadActivityId(Guid activityId) return; } - if (TplEventSource.Log != null) - TplEventSource.Log.SetActivityId(activityId); + TplEventSource.Log?.SetActivityId(activityId); // We ignore errors to keep with the convention that EventSources do not throw errors. // Note we can't access m_throwOnWrites because this is a static method. @@ -680,8 +679,7 @@ public static void SetCurrentThreadActivityId(Guid activityId, out Guid oldActiv // We don't call the activityDying callback here because the caller has declared that // it is not dying. - if (TplEventSource.Log != null) - TplEventSource.Log.SetActivityId(activityId); + TplEventSource.Log?.SetActivityId(activityId); } #endregion @@ -2235,10 +2233,7 @@ static TraceLoggingEventTypes GetTrimSafeTraceLoggingEventTypes() => data.Size = (uint)(2 * (msgString.Length + 1)); data.Reserved = 0; #if FEATURE_MANAGED_ETW - if (m_etwProvider != null) - { - m_etwProvider.WriteEvent(ref descr, IntPtr.Zero, null, null, 1, (IntPtr)((void*)&data)); - } + m_etwProvider?.WriteEvent(ref descr, IntPtr.Zero, null, null, 1, (IntPtr)((void*)&data)); #endif // FEATURE_MANAGED_ETW #if FEATURE_PERFTRACING if (m_eventPipeProvider != null) diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingMetadataCollector.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingMetadataCollector.cs index 598898fc1b772..5f78812a53453 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingMetadataCollector.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingMetadataCollector.cs @@ -307,10 +307,7 @@ private void AddField(FieldMetadata fieldMetadata) this.bufferedArrayFieldCount++; this.impl.fields.Add(fieldMetadata); - if (this.currentGroup != null) - { - this.currentGroup.IncrementStructFieldCount(); - } + this.currentGroup?.IncrementStructFieldCount(); } private sealed class Impl diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormatInfoScanner.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormatInfoScanner.cs index 5b73baa63c7ef..02f8b8f1acd1d 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormatInfoScanner.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormatInfoScanner.cs @@ -352,11 +352,9 @@ internal static int ScanRepeatChar(string pattern, char ch, int index, out int c internal void AddIgnorableSymbols(string? text) { - if (m_dateWords == null) - { - // Create the date word array. - m_dateWords = new List(); - } + // Create the date word array. + m_dateWords ??= new List(); + // Add the ignorable symbol into the ArrayList. string temp = IgnorableSymbolChar + text; if (!m_dateWords.Contains(temp)) diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/ReadLinesIterator.cs b/src/libraries/System.Private.CoreLib/src/System/IO/ReadLinesIterator.cs index cc77c9064a5b6..39ff9a4317c69 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/ReadLinesIterator.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/ReadLinesIterator.cs @@ -76,10 +76,7 @@ protected override void Dispose(bool disposing) { if (disposing) { - if (_reader != null) - { - _reader.Dispose(); - } + _reader?.Dispose(); } } finally diff --git a/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceReader.cs b/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceReader.cs index d204ab23c2178..2fccfcf22ea9e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceReader.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceReader.cs @@ -158,8 +158,7 @@ private unsafe void Dispose(bool disposing) // that we may call Close n times, but that's safe. BinaryReader copyOfStore = _store; _store = null!; - if (copyOfStore != null) - copyOfStore.Close(); + copyOfStore?.Close(); } _store = null!; _namePositions = null; diff --git a/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceSet.cs b/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceSet.cs index abb3f2ca9afbd..981a390ef9489 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceSet.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceSet.cs @@ -83,8 +83,7 @@ protected virtual void Dispose(bool disposing) // Close the Reader in a thread-safe way. IResourceReader? copyOfReader = Reader; Reader = null!; - if (copyOfReader != null) - copyOfReader.Close(); + copyOfReader?.Close(); } Reader = null!; _caseInsensitiveTable = null; diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/ManualResetEventSlim.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/ManualResetEventSlim.cs index 4f88b6670e270..cdcfe33ee97ac 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/ManualResetEventSlim.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/ManualResetEventSlim.cs @@ -312,11 +312,8 @@ private void Set(bool duringCancellation) lock (eventObj) { - if (m_eventObj != null) - { - // If somebody is waiting, we must set the event. - m_eventObj.Set(); - } + // If somebody is waiting, we must set the event. + m_eventObj?.Set(); } } } @@ -331,11 +328,9 @@ private void Set(bool duringCancellation) public void Reset() { ThrowIfDisposed(); + // If there's an event, reset it. - if (m_eventObj != null) - { - m_eventObj.Reset(); - } + m_eventObj?.Reset(); // There is a race condition here. If another thread Sets the event, we will get into a state // where m_state will be unsignaled, yet the Win32 event object will have been signaled. 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 675cf7f12f4f8..9f8413e543216 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/SemaphoreSlim.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/SemaphoreSlim.cs @@ -101,19 +101,17 @@ public WaitHandle AvailableWaitHandle CheckDispose(); // Return it directly if it is not null - if (m_waitHandle is not null) - return m_waitHandle; - - // lock the count to avoid multiple threads initializing the handle if it is null - lock (m_lockObjAndDisposed) + if (m_waitHandle is null) { - if (m_waitHandle is null) + // lock the count to avoid multiple threads initializing the handle if it is null + lock (m_lockObjAndDisposed) { // The initial state for the wait handle is true if the count is greater than zero // false otherwise - m_waitHandle = new ManualResetEvent(m_currentCount != 0); + m_waitHandle ??= new ManualResetEvent(m_currentCount != 0); } } + return m_waitHandle; } } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CollectionDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CollectionDataContract.cs index f56630822de1c..df57f68205cf2 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CollectionDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CollectionDataContract.cs @@ -496,28 +496,19 @@ private sealed class CollectionDataContractCriticalHelper : DataContract.DataCon private XmlFormatCollectionWriterDelegate? _xmlFormatWriterDelegate; private bool _isConstructorCheckRequired; - internal static Type[] KnownInterfaces - { - get + internal static Type[] KnownInterfaces => + // Listed in priority order + s_knownInterfaces ??= new Type[] { - if (s_knownInterfaces == null) - { - // Listed in priority order - s_knownInterfaces = new Type[] - { - Globals.TypeOfIDictionaryGeneric, - Globals.TypeOfIDictionary, - Globals.TypeOfIListGeneric, - Globals.TypeOfICollectionGeneric, - Globals.TypeOfIList, - Globals.TypeOfIEnumerableGeneric, - Globals.TypeOfICollection, - Globals.TypeOfIEnumerable - }; - } - return s_knownInterfaces; - } - } + Globals.TypeOfIDictionaryGeneric, + Globals.TypeOfIDictionary, + Globals.TypeOfIListGeneric, + Globals.TypeOfICollectionGeneric, + Globals.TypeOfIList, + Globals.TypeOfIEnumerableGeneric, + Globals.TypeOfICollection, + Globals.TypeOfIEnumerable + }; [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private void Init(CollectionKind kind, Type? itemType, CollectionDataContractAttribute? collectionContractAttribute) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs index 5a054d5f9b2bb..9e010d58cd565 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs @@ -1575,8 +1575,7 @@ internal static List GetDataContractNameForGenericName(string typeName, Str endIndex = typeName.IndexOf('`', startIndex); if (endIndex < 0) { - if (localName != null) - localName.Append(typeName.AsSpan(startIndex)); + localName?.Append(typeName.AsSpan(startIndex)); nestedParamCounts.Add(0); break; } @@ -1596,8 +1595,7 @@ internal static List GetDataContractNameForGenericName(string typeName, Str else nestedParamCounts.Add(int.Parse(typeName.AsSpan(endIndex + 1, startIndex - endIndex - 1), provider: CultureInfo.InvariantCulture)); } - if (localName != null) - localName.Append("Of"); + localName?.Append("Of"); return nestedParamCounts; } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/EnumDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/EnumDataContract.cs index 148efe5f81fc8..9014a71b47d40 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/EnumDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/EnumDataContract.cs @@ -369,8 +369,7 @@ public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, Xml public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext? context) { object obj = ReadEnumValue(xmlReader); - if (context != null) - context.AddNewObject(obj); + context?.AddNewObject(obj); return obj; } } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonEnumDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonEnumDataContract.cs index 726eafe2ab061..76f774cde91f0 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonEnumDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonEnumDataContract.cs @@ -31,10 +31,7 @@ public JsonEnumDataContract(EnumDataContract traditionalDataContract) enumValue = Enum.ToObject(TraditionalDataContract.UnderlyingType, jsonReader.ReadElementContentAsLong()); } - if (context != null) - { - context.AddNewObject(enumValue); - } + context?.AddNewObject(enumValue); return enumValue; } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonObjectDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonObjectDataContract.cs index 4f3f51603c8a7..c6e4945072ef8 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonObjectDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonObjectDataContract.cs @@ -49,10 +49,7 @@ public JsonObjectDataContract(DataContract traditionalDataContract) throw XmlObjectSerializer.CreateSerializationException(SR.Format(SR.JsonUnexpectedAttributeValue, contentMode)); } - if (context != null) - { - context.AddNewObject(obj); - } + context?.AddNewObject(obj); return obj; } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonXmlDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonXmlDataContract.cs index c38615a5ab805..99640f43461ac 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonXmlDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonXmlDataContract.cs @@ -36,10 +36,7 @@ public JsonXmlDataContract(XmlDataContract traditionalXmlDataContract) { xmlValue = dataContractSerializer.ReadObject(XmlDictionaryReader.CreateTextReader(memoryStream, quotas)); } - if (context != null) - { - context.AddNewObject(xmlValue); - } + context?.AddNewObject(xmlValue); return xmlValue; } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseReader.cs index 38e29e8609563..6c583883717ad 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseReader.cs @@ -470,10 +470,8 @@ public override void Close() _elementNodes = null; _nsMgr.Close(); _bufferReader.Close(); - if (_signingWriter != null) - _signingWriter.Close(); - if (_attributeSorter != null) - _attributeSorter.Close(); + _signingWriter?.Close(); + _attributeSorter?.Close(); } public sealed override int Depth diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseWriter.cs index f009bccb33587..4ddcff94559aa 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseWriter.cs @@ -97,10 +97,7 @@ public override void Close() _attributeValue = null; _attributeLocalName = null; _nodeWriter.Close(); - if (_signingWriter != null) - { - _signingWriter.Close(); - } + _signingWriter?.Close(); } } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReaderSession.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReaderSession.cs index 2ecc252ee1b08..1ddadff2f519c 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReaderSession.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReaderSession.cs @@ -120,8 +120,7 @@ public void Clear() if (_strings != null) Array.Clear(_strings); - if (_stringDict != null) - _stringDict.Clear(); + _stringDict?.Clear(); } } } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriterSession.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriterSession.cs index aa52a871e813a..e091403af295b 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriterSession.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriterSession.cs @@ -115,8 +115,7 @@ public void Clear() _now = 0; _listCount = 0; Array.Clear(_list); - if (_dictionary != null) - _dictionary.Clear(); + _dictionary?.Clear(); } public bool TryGetValue(K key, [MaybeNullWhen(false)] out V value) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlCanonicalWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlCanonicalWriter.cs index 7ebc16de436f6..e7552f0e39c33 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlCanonicalWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlCanonicalWriter.cs @@ -110,10 +110,8 @@ public void Flush() public void Close() { - if (_writer != null) - _writer.Close(); - if (_elementWriter != null) - _elementWriter.Close(); + _writer?.Close(); + _elementWriter?.Close(); if (_elementStream != null && _elementStream.Length > 512) _elementStream = null!; _elementBuffer = null; diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/Extensions.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/Extensions.cs index e255b0e1afbf3..cc19960503629 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/Extensions.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/Extensions.cs @@ -317,8 +317,7 @@ public static void Remove(this IEnumerable source) XAttribute?[] attributes = EnumerableHelpers.ToArray(source, out count); for (int i = 0; i < count; i++) { - XAttribute? a = attributes[i]; - if (a != null) a.Remove(); + attributes[i]?.Remove(); } } @@ -335,8 +334,7 @@ public static void Remove(this IEnumerable source) where T : XNode T?[] nodes = EnumerableHelpers.ToArray(source, out count); for (int i = 0; i < count; i++) { - T? node = nodes[i]; - if (node != null) node.Remove(); + nodes[i]?.Remove(); } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathDocumentBuilder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathDocumentBuilder.cs index 388852fcbac94..f96795772147a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathDocumentBuilder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathDocumentBuilder.cs @@ -616,8 +616,7 @@ public void CreateIdTables(IDtdInfo dtdInfo) private XPathNodeRef LinkSimilarElements(XPathNode[] pagePrev, int idxPrev, XPathNode[] pageNext, int idxNext) { // Set link on previous element - if (pagePrev != null) - pagePrev[idxPrev].SetSimilarElement(_infoTable, pageNext, idxNext); + pagePrev?[idxPrev].SetSimilarElement(_infoTable, pageNext, idxNext); // Add next element to index return new XPathNodeRef(pageNext, idxNext); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/ValidatingReaderNodeData.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/ValidatingReaderNodeData.cs index 127710f9754d0..9106c536541e3 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/ValidatingReaderNodeData.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/ValidatingReaderNodeData.cs @@ -179,10 +179,7 @@ internal void Clear(XmlNodeType nodeType) _namespaceUri = string.Empty; _rawValue = string.Empty; - if (_attributePSVIInfo != null) - { - _attributePSVIInfo.Reset(); - } + _attributePSVIInfo?.Reset(); _nameWPrefix = null; _lineNo = 0; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingReader.cs index 6dd3669724df7..3aeefe3b256f4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingReader.cs @@ -644,10 +644,7 @@ private static void CheckCharacters(string value) private void FinishReadBinary() { _state = State.Interactive; - if (_readBinaryHelper != null) - { - _readBinaryHelper.Finish(); - } + _readBinaryHelper?.Finish(); } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriter.cs index 015403eef28ae..697b874077194 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriter.cs @@ -427,10 +427,7 @@ private static void ValidateQName(string name) continue; } - if (sb == null) - { - sb = new StringBuilder(str.Length + 5); - } + sb ??= new StringBuilder(str.Length + 5); sb.Append(str, start, i - start); } @@ -480,10 +477,7 @@ private static void ValidateQName(string name) continue; } - if (sb == null) - { - sb = new StringBuilder(len + 5); - } + sb ??= new StringBuilder(len + 5); sb.Append(data, start, i - start); } @@ -497,10 +491,7 @@ private static void ValidateQName(string name) continue; } - if (sb == null) - { - sb = new StringBuilder(len + 5); - } + sb ??= new StringBuilder(len + 5); sb.Append(data, start, i - start); i++; @@ -512,10 +503,7 @@ private static void ValidateQName(string name) continue; } - if (sb == null) - { - sb = new StringBuilder(len + 5); - } + sb ??= new StringBuilder(len + 5); sb.Append(data, start, i - start); } @@ -556,10 +544,7 @@ private static string InterleaveInvalidChars(string text, char invChar1, char in } if (i > 0 && text[i - 1] == invChar1) { - if (sb == null) - { - sb = new StringBuilder(text.Length + 5); - } + sb ??= new StringBuilder(text.Length + 5); sb.Append(text, start, i - start); sb.Append(' '); 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 ecef56ad3c4c9..0a03f287d8b0a 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 @@ -766,9 +766,9 @@ public override void Flush() { _stream.Flush(); } - else if (_writer != null) + else { - _writer.Flush(); + _writer?.Flush(); } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEventCache.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEventCache.cs index 4d51b5af35b66..4425294a42a67 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEventCache.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEventCache.cs @@ -189,18 +189,15 @@ public void EventsToWriter(XmlWriter writer) break; case XmlEventType.XmlDecl1: - if (rawWriter != null) - rawWriter.WriteXmlDeclaration((XmlStandalone)page[idxEvent].Object!); + rawWriter?.WriteXmlDeclaration((XmlStandalone)page[idxEvent].Object!); break; case XmlEventType.XmlDecl2: - if (rawWriter != null) - rawWriter.WriteXmlDeclaration(page[idxEvent].String1!); + rawWriter?.WriteXmlDeclaration(page[idxEvent].String1!); break; case XmlEventType.StartContent: - if (rawWriter != null) - rawWriter.StartElementContent(); + rawWriter?.StartElementContent(); break; case XmlEventType.EndElem: @@ -225,8 +222,7 @@ public void EventsToWriter(XmlWriter writer) break; case XmlEventType.EndBase64: - if (rawWriter != null) - rawWriter.WriteEndBase64(); + rawWriter?.WriteEndBase64(); break; case XmlEventType.Close: diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs index 3927f99cbaf7f..8606248f3e6d2 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs @@ -2821,10 +2821,7 @@ private void SendValidationEvent(XmlSeverityType severity, string code, string? private void SendValidationEvent(XmlSeverityType severity, XmlSchemaException exception) { - if (_validationEventHandling != null) - { - _validationEventHandling.SendEvent(exception, severity); - } + _validationEventHandling?.SendEvent(exception, severity); } // @@ -7174,10 +7171,7 @@ private int EatWhitespaces(StringBuilder? sb) int tmp2 = pos - _ps.charPos; if (tmp2 > 0) { - if (sb != null) - { - sb.Append(_ps.chars, _ps.charPos, tmp2); - } + sb?.Append(_ps.chars, _ps.charPos, tmp2); _ps.charPos = pos; wsCount += tmp2; } @@ -7190,10 +7184,7 @@ private int EatWhitespaces(StringBuilder? sb) int tmp3 = pos - _ps.charPos; if (tmp3 > 0) { - if (sb != null) - { - sb.Append(_ps.chars, _ps.charPos, tmp3); - } + sb?.Append(_ps.chars, _ps.charPos, tmp3); _ps.charPos = pos; wsCount += tmp3; } @@ -7356,10 +7347,7 @@ private int ParseNumericCharRefInline(int startPos, bool expand, StringBuilder? if (expand) { - if (internalSubsetBuilder != null) - { - internalSubsetBuilder.Append(_ps.chars, _ps.charPos, pos - _ps.charPos + 1); - } + internalSubsetBuilder?.Append(_ps.chars, _ps.charPos, pos - _ps.charPos + 1); chars[pos] = ch; } charCount = 1; @@ -7387,10 +7375,7 @@ private int ParseNumericCharRefInline(int startPos, bool expand, StringBuilder? Debug.Assert(pos > 0); if (expand) { - if (internalSubsetBuilder != null) - { - internalSubsetBuilder.Append(_ps.chars, _ps.charPos, pos - _ps.charPos + 1); - } + internalSubsetBuilder?.Append(_ps.chars, _ps.charPos, pos - _ps.charPos + 1); chars[pos - 1] = (char)high; chars[pos] = (char)low; } @@ -7556,10 +7541,7 @@ private int ParseNamedCharRefInline(int startPos, bool expand, StringBuilder? in Debug.Assert(pos > 0); if (expand) { - if (internalSubsetBuilder != null) - { - internalSubsetBuilder.Append(_ps.chars, _ps.charPos, pos - _ps.charPos); - } + internalSubsetBuilder?.Append(_ps.chars, _ps.charPos, pos - _ps.charPos); _ps.chars[pos - 1] = ch; } return pos; @@ -8122,10 +8104,7 @@ private void PushInternalEntity(IDtdEntityInfo entity) private void PopEntity() { - if (_ps.stream != null) - { - _ps.stream.Dispose(); - } + _ps.stream?.Dispose(); UnregisterEntity(); PopParsingState(); @@ -8151,10 +8130,7 @@ private void RegisterEntity(IDtdEntityInfo entity) // register entity for recursion checkes if (entity != null) { - if (_currentEntities == null) - { - _currentEntities = new Dictionary(); - } + _currentEntities ??= new Dictionary(); _currentEntities.Add(entity, entity); } @@ -9323,10 +9299,7 @@ internal bool AddDefaultAttributeNonDtd(SchemaAttDef attrDef) prefix = _namespaceManager.LookupPrefix(ns); Debug.Assert(prefix != null); - if (prefix == null) - { - prefix = string.Empty; - } + prefix ??= string.Empty; } // find out if the attribute is already there @@ -9733,10 +9706,7 @@ internal static string StripSpaces(string value) } if (j > i + 1) { - if (norValue == null) - { - norValue = new StringBuilder(len); - } + norValue ??= new StringBuilder(len); norValue.Append(value, startPos, i - startPos + 1); startPos = j; i = j - 1; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplAsync.cs index 346796339d07a..fd17ffd1c58ce 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplAsync.cs @@ -4905,10 +4905,7 @@ private async Task EatWhitespacesAsync(StringBuilder? sb) int tmp2 = pos - _ps.charPos; if (tmp2 > 0) { - if (sb != null) - { - sb.Append(_ps.chars, _ps.charPos, tmp2); - } + sb?.Append(_ps.chars, _ps.charPos, tmp2); _ps.charPos = pos; wsCount += tmp2; } @@ -4921,10 +4918,7 @@ private async Task EatWhitespacesAsync(StringBuilder? sb) int tmp3 = pos - _ps.charPos; if (tmp3 > 0) { - if (sb != null) - { - sb.Append(_ps.chars, _ps.charPos, tmp3); - } + sb?.Append(_ps.chars, _ps.charPos, tmp3); _ps.charPos = pos; wsCount += tmp3; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplHelpers.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplHelpers.cs index fa09441641ca4..9e503cbb6f4af 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplHelpers.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplHelpers.cs @@ -92,9 +92,9 @@ internal void Close(bool closeInput) { stream.Dispose(); } - else if (textReader != null) + else { - textReader.Dispose(); + textReader?.Dispose(); } } } @@ -336,18 +336,9 @@ private sealed class NodeData : IComparable private static volatile NodeData? s_None; // NOTE: Do not use this property for reference comparison. It may not be unique. - internal static NodeData None - { - get - { - if (s_None == null) - { - // no locking; s_None is immutable so it's not a problem that it may get initialized more than once - s_None = new NodeData(); - } - return s_None; - } - } + internal static NodeData None => + // no locking; s_None is immutable so it's not a problem that it may get initialized more than once + s_None ??= new NodeData(); // type internal XmlNodeType type; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextWriter.cs index 18dd3a606f154..d48a03a80cd20 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextWriter.cs @@ -1805,11 +1805,8 @@ private void PushStack() private void FlushEncoders() { - if (null != _base64Encoder) - { - // The Flush will call WriteRaw to write out the rest of the encoded characters - _base64Encoder.Flush(); - } + // The Flush will call WriteRaw to write out the rest of the encoded characters + _base64Encoder?.Flush(); _flush = false; } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlUtf8RawTextWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlUtf8RawTextWriter.cs index aff223143cbb8..2ab7b53a8565d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlUtf8RawTextWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlUtf8RawTextWriter.cs @@ -648,10 +648,7 @@ public override void Flush() { FlushBuffer(); - if (_stream != null) - { - _stream.Flush(); - } + _stream?.Flush(); } // 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 6bd337be0dbd2..7e97af503db3f 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 @@ -899,10 +899,7 @@ public override void WriteProcessingInstruction(string name, string? text) CheckNCName(name); // check text - if (text == null) - { - text = string.Empty; - } + text ??= string.Empty; // xml declaration is a special case (not a processing instruction, but we allow WriteProcessingInstruction as a convenience) if (name.Length == 3 && string.Equals(name, "xml", StringComparison.OrdinalIgnoreCase)) @@ -1022,10 +1019,7 @@ public override void WriteWhitespace(string? ws) { try { - if (ws == null) - { - ws = string.Empty; - } + ws ??= string.Empty; if (!XmlCharType.IsOnlyWhitespace(ws)) { throw new ArgumentException(SR.Xml_NonWhitespace); @@ -1584,10 +1578,7 @@ private void SetSpecialAttribute(SpecialAttribute special) else Debug.Fail("State.Attribute == currentState || State.RootLevelAttr == currentState"); - if (_attrValueCache == null) - { - _attrValueCache = new AttributeValueCache(); - } + _attrValueCache ??= new AttributeValueCache(); } private void WriteStartDocumentImpl(XmlStandalone standalone) @@ -1964,26 +1955,17 @@ private void AdvanceState(Token token) break; case State.PostB64Cont: - if (_rawWriter != null) - { - _rawWriter.WriteEndBase64(); - } + _rawWriter?.WriteEndBase64(); _currentState = State.Content; goto Advance; case State.PostB64Attr: - if (_rawWriter != null) - { - _rawWriter.WriteEndBase64(); - } + _rawWriter?.WriteEndBase64(); _currentState = State.Attribute; goto Advance; case State.PostB64RootAttr: - if (_rawWriter != null) - { - _rawWriter.WriteEndBase64(); - } + _rawWriter?.WriteEndBase64(); _currentState = State.RootLevelAttr; goto Advance; @@ -2028,10 +2010,7 @@ private void StartElementContent() } } - if (_rawWriter != null) - { - _rawWriter.StartElementContent(); - } + _rawWriter?.StartElementContent(); } private static string GetStateName(State state) @@ -2182,10 +2161,7 @@ private void AddAttribute(string prefix, string localName, string namespaceName) // reached the threshold -> add all attributes to hash table if (_attrCount == MaxAttrDuplWalkCount) { - if (_attrHashTable == null) - { - _attrHashTable = new Dictionary(); - } + _attrHashTable ??= new Dictionary(); Debug.Assert(_attrHashTable.Count == 0); for (int i = 0; i < top; i++) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterAsync.cs index 37709097126d7..f6e02486f6685 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterAsync.cs @@ -761,10 +761,7 @@ public override async Task WriteCDataAsync(string? text) { try { - if (text == null) - { - text = string.Empty; - } + text ??= string.Empty; await AdvanceStateAsync(Token.CData).ConfigureAwait(false); await _writer.WriteCDataAsync(text).ConfigureAwait(false); @@ -804,10 +801,7 @@ public override async Task WriteProcessingInstructionAsync(string name, string? CheckNCName(name); // check text - if (text == null) - { - text = string.Empty; - } + text ??= string.Empty; // xml declaration is a special case (not a processing instruction, but we allow WriteProcessingInstruction as a convenience) if (name.Length == 3 && string.Equals(name, "xml", StringComparison.OrdinalIgnoreCase)) @@ -928,10 +922,7 @@ public override async Task WriteWhitespaceAsync(string? ws) { try { - if (ws == null) - { - ws = string.Empty; - } + ws ??= string.Empty; if (!XmlCharType.IsOnlyWhitespace(ws)) { @@ -1439,10 +1430,7 @@ private async Task StartElementContentAsync_WithNS() } } - if (_rawWriter != null) - { - _rawWriter.StartElementContent(); - } + _rawWriter?.StartElementContent(); } private Task StartElementContentAsync() @@ -1452,10 +1440,7 @@ private Task StartElementContentAsync() return StartElementContentAsync_WithNS(); } - if (_rawWriter != null) - { - _rawWriter.StartElementContent(); - } + _rawWriter?.StartElementContent(); return Task.CompletedTask; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReader.cs index 5176203480aa3..2926921c6cc73 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReader.cs @@ -2765,10 +2765,7 @@ private XsdCachingReader GetCachingReader() internal ValidatingReaderNodeData CreateDummyTextNode(string attributeValue, int depth) { - if (_textNode == null) - { - _textNode = new ValidatingReaderNodeData(XmlNodeType.Text); - } + _textNode ??= new ValidatingReaderNodeData(XmlNodeType.Text); _textNode.Depth = depth; _textNode.RawValue = attributeValue; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentSchemaValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentSchemaValidator.cs index e7e221078b940..d2d83d120b786 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentSchemaValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentSchemaValidator.cs @@ -426,10 +426,7 @@ private void ValidateAttributes(XmlElement elementNode) attr.AppendChild(_document.CreateTextNode(schemaAttribute.AttDef!.DefaultValueRaw)); attributes.Append(attr); XmlUnspecifiedAttribute? defAttr = attr as XmlUnspecifiedAttribute; - if (defAttr != null) - { - defAttr.SetSpecified(false); - } + defAttr?.SetSpecified(false); } } } @@ -520,10 +517,7 @@ private void SetDefaultAttributeSchemaInfo(XmlSchemaAttribute schemaAttribute) CheckNodeSequenceCapacity(nodeIndex); _nodeSequenceToValidate![nodeIndex++] = parentNode; XmlSchemaObject? ancestorSchemaObject = parentSchemaInfo.SchemaElement; - if (ancestorSchemaObject == null) - { - ancestorSchemaObject = parentSchemaInfo.SchemaType; - } + ancestorSchemaObject ??= parentSchemaInfo.SchemaType; return GetTypeFromAncestors(elementToValidate, ancestorSchemaObject, nodeIndex); } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlAttribute.cs index b29fea07407c1..db2f88015a006 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlAttribute.cs @@ -155,10 +155,7 @@ internal bool PrepareOwnerElementInElementIdAttrMap() internal void ResetOwnerElementInElementIdAttrMap(string oldInnerText) { XmlElement? ownerElement = OwnerElement; - if (ownerElement != null) - { - ownerElement.Attributes.ResetParentInElementIdAttrMap(oldInnerText, InnerText); - } + ownerElement?.Attributes.ResetParentInElementIdAttrMap(oldInnerText, InnerText); } internal override bool IsContainer 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 0f42ececd81ac..3df97a5f07f4e 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 @@ -715,10 +715,7 @@ private XmlAttribute PrepareDefaultAttribute(SchemaAttDef attdef, string attrPre defattr.InnerXml = attdef.DefaultValueRaw; //during the expansion of the tree, the flag could be set to true, we need to set it back. XmlUnspecifiedAttribute? unspAttr = defattr as XmlUnspecifiedAttribute; - if (unspAttr != null) - { - unspAttr.SetSpecified(false); - } + unspAttr?.SetSpecified(false); return defattr; } 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 f8dd9c8766af7..3b96851ef6b88 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 @@ -125,10 +125,7 @@ private void LoadDocSequence(XmlDocument parentDoc) // recursively load all children. if (!fEmptyElement) { - if (parent != null) - { - parent.AppendChildForLoad(element, _doc); - } + parent?.AppendChildForLoad(element, _doc); parent = element; continue; } @@ -315,8 +312,7 @@ private XmlAttribute LoadDefaultAttribute() XmlUnspecifiedAttribute? defAttr = attr as XmlUnspecifiedAttribute; // If user overrides CreateDefaultAttribute, then attr will NOT be a XmlUnspecifiedAttribute instance. - if (defAttr != null) - defAttr.SetSpecified(false); + defAttr?.SetSpecified(false); return attr; } 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 46faa530e57e4..d0dda8c64c54d 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 @@ -270,8 +270,7 @@ internal bool IsConnected() if (!CanInsertBefore(newChild, refChild)) throw new InvalidOperationException(SR.Xdom_Node_Insert_Location); - if (newChild.ParentNode != null) - newChild.ParentNode.RemoveChild(newChild); + newChild.ParentNode?.RemoveChild(newChild); // special case for doc-fragment. if (newChild.NodeType == XmlNodeType.DocumentFragment) @@ -385,8 +384,7 @@ internal bool IsConnected() if (!CanInsertAfter(newChild, refChild)) throw new InvalidOperationException(SR.Xdom_Node_Insert_Location); - if (newChild.ParentNode != null) - newChild.ParentNode.RemoveChild(newChild); + newChild.ParentNode?.RemoveChild(newChild); // special case for doc-fragment. if (newChild.NodeType == XmlNodeType.DocumentFragment) @@ -588,8 +586,7 @@ public virtual XmlNode RemoveChild(XmlNode oldChild) if (this == newChild || AncestorNode(newChild)) throw new ArgumentException(SR.Xdom_Node_Insert_Child); - if (newChild.ParentNode != null) - newChild.ParentNode.RemoveChild(newChild); + newChild.ParentNode?.RemoveChild(newChild); XmlDocument? childDoc = newChild.OwnerDocument; if (childDoc != null && childDoc != thisDoc && childDoc != this) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/ContentValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/ContentValidator.cs index 4a2f2eae8568c..306d605dda442 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/ContentValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/ContentValidator.cs @@ -450,10 +450,7 @@ protected void ExpandTreeNoRecursive(InteriorNode parent, SymbolsDictionary symb this_._leftChild!.ExpandTree(this_, symbols, positions); ProcessRight: - if (this_._rightChild != null) - { - this_._rightChild.ExpandTree(this_, symbols, positions); - } + this_._rightChild?.ExpandTree(this_, symbols, positions); if (nodeStack.Count == 0) break; @@ -466,10 +463,7 @@ protected void ExpandTreeNoRecursive(InteriorNode parent, SymbolsDictionary symb public override void ExpandTree(InteriorNode parent, SymbolsDictionary symbols, Positions positions) { _leftChild!.ExpandTree(this, symbols, positions); - if (_rightChild != null) - { - _rightChild.ExpandTree(this, symbols, positions); - } + _rightChild?.ExpandTree(this, symbols, positions); } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParser.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParser.cs index b490e2b2be553..7936efc832a42 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParser.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParser.cs @@ -1317,10 +1317,7 @@ private void ParseNotationDecl() SchemaNotation? notation = null; if (!_schemaInfo.Notations.ContainsKey(notationName.Name)) { - if (_undeclaredNotations != null) - { - _undeclaredNotations.Remove(notationName.Name); - } + _undeclaredNotations?.Remove(notationName.Name); notation = new SchemaNotation(notationName); _schemaInfo.Notations.Add(notation.Name.Name, notation); } @@ -3418,10 +3415,7 @@ private void SendValidationEvent(XmlSeverityType severity, XmlSchemaException e) { Debug.Assert(_validate); IValidationEventHandling? eventHandling = _readerAdapterWithValidation!.ValidationEventHandling; - if (eventHandling != null) - { - eventHandling.SendEvent(e, severity); - } + eventHandling?.SendEvent(e, severity); } private static bool IsAttributeValueType(Token token) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParserAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParserAsync.cs index fef18e325fbcf..dcb228e18bc79 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParserAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParserAsync.cs @@ -951,10 +951,7 @@ private async Task ParseNotationDeclAsync() SchemaNotation? notation = null; if (!_schemaInfo.Notations.ContainsKey(notationName.Name)) { - if (_undeclaredNotations != null) - { - _undeclaredNotations.Remove(notationName.Name); - } + _undeclaredNotations?.Remove(notationName.Name); notation = new SchemaNotation(notationName); _schemaInfo.Notations.Add(notation.Name.Name, notation); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Preprocessor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Preprocessor.cs index fd6222afab167..78951fd91b0a4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Preprocessor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Preprocessor.cs @@ -488,10 +488,7 @@ private void BuildRefNamespaces(XmlSchema schema) { import = (include as XmlSchemaImport)!; ns = import.Namespace; - if (ns == null) - { - ns = string.Empty; - } + ns ??= string.Empty; if (_referenceNamespaces[ns] == null) _referenceNamespaces.Add(ns, ns); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionCompiler.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionCompiler.cs index 436da7c0611cb..30981fa3c4e06 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionCompiler.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionCompiler.cs @@ -2065,10 +2065,7 @@ private void CompileAttribute(XmlSchemaAttribute xa) xa.SetAttributeType(DatatypeImplementation.AnySimpleType); } } - if (decl.Datatype != null) - { - decl.Datatype.VerifySchemaValid(_schema!.Notations, xa); - } + decl.Datatype?.VerifySchemaValid(_schema!.Notations, xa); if (xa.DefaultValue != null || xa.FixedValue != null) { if (xa.DefaultValue != null) @@ -2285,10 +2282,7 @@ private void CompileElement(XmlSchemaElement xe) decl.IsNillable = xe.IsNillable; decl.Block |= xe.BlockResolved; } - if (decl.Datatype != null) - { - decl.Datatype.VerifySchemaValid(_schema!.Notations, xe); - } + decl.Datatype?.VerifySchemaValid(_schema!.Notations, xe); if (xe.DefaultValue != null || xe.FixedValue != null) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaSetCompiler.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaSetCompiler.cs index d74f3575417aa..82e55eb9e06e1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaSetCompiler.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaSetCompiler.cs @@ -595,10 +595,7 @@ private void CompileGroup(XmlSchemaGroup group) else { group.IsProcessing = true; - if (group.CanonicalParticle == null) - { - group.CanonicalParticle = CannonicalizeParticle(group.Particle, true); - } + group.CanonicalParticle ??= CannonicalizeParticle(group.Particle, true); Debug.Assert(group.CanonicalParticle != null); group.IsProcessing = false; //Not enclosung in try -finally as cannonicalizeParticle will not throw exception } @@ -2501,10 +2498,7 @@ private void CompileAttribute(XmlSchemaAttribute xa) xa.SetAttributeType(DatatypeImplementation.AnySimpleType); } //} //Removed this here since the following should be done only if RefName is Empty - if (decl.Datatype != null) - { - decl.Datatype.VerifySchemaValid(_notations, xa); - } + decl.Datatype?.VerifySchemaValid(_notations, xa); SetDefaultFixed(xa, decl); } //End of Else for !RefName.IsEmpty @@ -2747,10 +2741,7 @@ private void CompileElement(XmlSchemaElement xe) decl.IsNillable = xe.IsNillable; decl.Block |= xe.BlockResolved; } - if (decl.Datatype != null) - { - decl.Datatype.VerifySchemaValid(_notations, xe); - } + decl.Datatype?.VerifySchemaValid(_notations, xe); if (xe.DefaultValue != null || xe.FixedValue != null) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrBuilder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrBuilder.cs index 17825cd22177f..c0b5726f7378c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrBuilder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrBuilder.cs @@ -536,10 +536,7 @@ private bool LoadSchema(string uri) } finally { - if (reader != null) - { - reader.Close(); - } + reader?.Close(); } if (schemaInfo != null && schemaInfo.ErrorCount == 0) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrValidator.cs index 7ee3d2039088c..f5419f97e5ba6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrValidator.cs @@ -361,10 +361,7 @@ private void LoadSchemaFromLocation(string uri) } finally { - if (reader != null) - { - reader.Close(); - } + reader?.Close(); } if (xdrSchema != null && xdrSchema.ErrorCount == 0) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaObjectCollection.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaObjectCollection.cs index 210f13523da3b..d9d9eb4bd85bc 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaObjectCollection.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaObjectCollection.cs @@ -63,10 +63,7 @@ public void CopyTo(XmlSchemaObject[] array, int index) protected override void OnInsert(int index, object? item) { - if (_parent != null) - { - _parent.OnAdd(this, item); - } + _parent?.OnAdd(this, item); } protected override void OnSet(int index, object? oldValue, object? newValue) @@ -80,18 +77,12 @@ protected override void OnSet(int index, object? oldValue, object? newValue) protected override void OnClear() { - if (_parent != null) - { - _parent.OnClear(this); - } + _parent?.OnClear(this); } protected override void OnRemove(int index, object? item) { - if (_parent != null) - { - _parent.OnRemove(this, item); - } + _parent?.OnRemove(this, item); } internal XmlSchemaObjectCollection Clone() 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 ce3757ba4040a..40774f4335c14 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 @@ -241,10 +241,7 @@ private void Reset() _partialValidationType = null; //Clear previous tables - if (_IDs != null) - { - _IDs.Clear(); - } + _IDs?.Clear(); if (ProcessSchemaHints) { _validatedNamespaces!.Clear(); @@ -519,10 +516,7 @@ public void ValidateElement(string localName, string namespaceUri, XmlSchemaInfo if (_attPresence[attQName] != null) { //this attribute already checked as it is duplicate; SendValidationEvent(SR.Sch_DuplicateAttribute, attQName.ToString()); - if (schemaInfo != null) - { - schemaInfo.Clear(); - } + schemaInfo?.Clear(); return null; } @@ -1686,10 +1680,7 @@ private void AddXsiAttributes(ArrayList attList) if (elementDeclXsi == null && xsiTypeName.Namespace == _nsXs) { XmlSchemaType? schemaType = DatatypeImplementation.GetSimpleTypeFromXsdType(xsiTypeName); - if (schemaType == null) - { //try getting complexType - xs:anyType - schemaType = XmlSchemaType.GetBuiltInComplexType(xsiTypeName); - } + schemaType ??= XmlSchemaType.GetBuiltInComplexType(xsiTypeName); if (schemaType != null) { elementDeclXsi = schemaType.ElementDecl; @@ -1859,10 +1850,7 @@ private void LoadSchema(string uri, string url) } finally { - if (Reader != null) - { - Reader.Close(); - } + Reader?.Close(); } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdValidator.cs index 3e892ab55e16f..391d9fe7338ab 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdValidator.cs @@ -610,10 +610,7 @@ private void LoadSchemaFromLocation(string uri, string url) } finally { - if (reader != null) - { - reader.Close(); - } + reader?.Close(); } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Models.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Models.cs index b9254d8f30f6c..1bf2e8d62ad27 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Models.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Models.cs @@ -206,10 +206,7 @@ private void CheckSupportedMember(TypeDesc? typeDesc, MemberInfo member, Type ty return; if (typeDesc.IsUnsupported) { - if (typeDesc.Exception == null) - { - typeDesc.Exception = new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, typeDesc.FullName)); - } + typeDesc.Exception ??= new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, typeDesc.FullName)); throw new InvalidOperationException(SR.Format(SR.XmlSerializerUnsupportedMember, $"{member.DeclaringType!.FullName}.{member.Name}", type.FullName), typeDesc.Exception); } CheckSupportedMember(typeDesc.BaseTypeDesc, member, type); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationReader.cs index 8208a6865a550..e3a3075f97ea0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationReader.cs @@ -1720,10 +1720,7 @@ void Wrapper(object? _) { string specifiedMemberName = $"{member.Mapping.Name}Specified"; MethodInfo? specifiedMethodInfo = o!.GetType().GetMethod($"set_{specifiedMemberName}"); - if (specifiedMethodInfo != null) - { - specifiedMethodInfo.Invoke(o, new object[] { true }); - } + specifiedMethodInfo?.Invoke(o, new object[] { true }); } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Types.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Types.cs index e7b6c39348f6b..5646a18296eaa 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Types.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Types.cs @@ -384,10 +384,8 @@ internal void CheckSupported() throw new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, FullName)); } } - if (_baseTypeDesc != null) - _baseTypeDesc.CheckSupported(); - if (_arrayElementTypeDesc != null) - _arrayElementTypeDesc.CheckSupported(); + _baseTypeDesc?.CheckSupported(); + _arrayElementTypeDesc?.CheckSupported(); } internal void CheckNeedConstructor() @@ -910,10 +908,7 @@ private TypeDesc ImportTypeDesc(Type type, MemberInfo? memberInfo, bool directRe { kind = TypeKind.Void; flags |= TypeFlags.Unsupported; - if (exception == null) - { - exception = new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, type.FullName)); - } + exception ??= new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, type.FullName)); } // check to see if the type has public default constructor for classes diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs index 7a1a45431e1db..0e18a2484a6e9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs @@ -847,10 +847,7 @@ private MemberMapping ImportChoiceGroup(XmlSchemaGroupBase group, string identif if (membersScope != null) { choiceAccessor.Name = choiceIdentifier.Name = member.ChoiceIdentifier.MemberName = membersScope.AddUnique(member.ChoiceIdentifier.MemberName, choiceIdentifier); - if (members != null) - { - members.Add(choiceAccessor.Name, choiceIdentifier); - } + members?.Add(choiceAccessor.Name, choiceIdentifier); } } return member; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs index 82b930ab92305..d43d757389941 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs @@ -1896,7 +1896,7 @@ private object ReadXmlNodes(bool elementCanBeType) } XmlAttribute xmlAttribute = (XmlAttribute)Document.ReadNode(_r)!; xmlNodeList.Add(xmlAttribute); - if (unknownElement != null) unknownElement.SetAttributeNode(xmlAttribute); + unknownElement?.SetAttributeNode(xmlAttribute); } // If the node is referenced (or in case of paramStyle = bare) and if xsi:type is not @@ -1932,7 +1932,7 @@ private object ReadXmlNodes(bool elementCanBeType) { XmlNode xmlNode = Document.ReadNode(_r)!; xmlNodeList.Add(xmlNode); - if (unknownElement != null) unknownElement.AppendChild(xmlNode); + unknownElement?.AppendChild(xmlNode); Reader.MoveToContent(); } ReadEndElement(); @@ -3648,12 +3648,7 @@ private void WriteXmlNodeEqual(string? source, string? name, string? ns) private void WriteID(string? name) { - if (name == null) - { - //Writer.Write("null"); - //return; - name = ""; - } + name ??= ""; string? idName = (string?)_idNames[name]; if (idName == null) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs index a11fd8473e4cf..56d8bd29f1399 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs @@ -1804,12 +1804,7 @@ private void WriteXmlNodeEqual(string source, string name, string? ns, bool doAn private void WriteID(string? name) { - if (name == null) - { - //Writer.Write("null"); - //return; - name = ""; - } + name ??= ""; if (!_idNames.ContainsKey(name)) { string? idName = NextIdName(name); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/BooleanFunctions.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/BooleanFunctions.cs index 2ae24d53792e8..c7edf3d604e6d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/BooleanFunctions.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/BooleanFunctions.cs @@ -28,10 +28,7 @@ private BooleanFunctions(BooleanFunctions other) : base(other) public override void SetXsltContext(XsltContext context) { - if (_arg != null) - { - _arg.SetXsltContext(context); - } + _arg?.SetXsltContext(context); } public override object Evaluate(XPathNodeIterator nodeIterator) => diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ExtensionQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ExtensionQuery.cs index ab28f99c7ddfd..a3fc80014209e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ExtensionQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ExtensionQuery.cs @@ -30,10 +30,7 @@ protected ExtensionQuery(ExtensionQuery other) : base(other) public override void Reset() { - if (_queryIterator != null) - { - _queryIterator.Reset(); - } + _queryIterator?.Reset(); } public override XPathNavigator? Current diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/NodeFunctions.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/NodeFunctions.cs index 07a96cf22dfbd..c132df83775d5 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/NodeFunctions.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/NodeFunctions.cs @@ -23,10 +23,7 @@ public NodeFunctions(FT funcType, Query? arg) public override void SetXsltContext(XsltContext context) { _xsltContext = context.Whitespace ? context : null; - if (_arg != null) - { - _arg.SetXsltContext(context); - } + _arg?.SetXsltContext(context); } private XPathNavigator? EvaluateArg(XPathNodeIterator context) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/NumberFunctions.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/NumberFunctions.cs index ca970b84f8749..0cd9e90c3e9d4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/NumberFunctions.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/NumberFunctions.cs @@ -28,10 +28,7 @@ private NumberFunctions(NumberFunctions other) : base(other) public override void SetXsltContext(XsltContext context) { - if (_arg != null) - { - _arg.SetXsltContext(context); - } + _arg?.SetXsltContext(context); } internal static double Number(bool arg) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigator.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigator.cs index 8e995b37e0aa7..406f3bba1a4b9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigator.cs @@ -126,10 +126,7 @@ public virtual void SetTypedValue(object typedValue) { value = schemaType.ValueConverter.ToString(typedValue, this); XmlSchemaDatatype? datatype = schemaType.Datatype; - if (datatype != null) - { - datatype.ParseValue(value, NameTable, this); - } + datatype?.ParseValue(value, NameTable, this); } } value ??= XmlUntypedConverter.Untyped.ToString(typedValue, this); @@ -346,10 +343,7 @@ public override long ValueAsLong public override object ValueAs(Type returnType, IXmlNamespaceResolver? nsResolver) { - if (nsResolver == null) - { - nsResolver = this; - } + nsResolver ??= this; IXmlSchemaInfo? schemaInfo = SchemaInfo; XmlSchemaType? schemaType; XmlSchemaDatatype? datatype; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs index e24e90987d214..8ed8a836f83cb 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs @@ -1165,36 +1165,33 @@ private static string[] AllDateTimeFormats private static void CreateAllDateTimeFormats() { - if (s_allDateTimeFormats == null) - { - // no locking; the array is immutable so it's not a problem that it may get initialized more than once - s_allDateTimeFormats = new string[] { - "yyyy-MM-ddTHH:mm:ss.FFFFFFFzzzzzz", //dateTime - "yyyy-MM-ddTHH:mm:ss.FFFFFFF", - "yyyy-MM-ddTHH:mm:ss.FFFFFFFZ", - "HH:mm:ss.FFFFFFF", //time - "HH:mm:ss.FFFFFFFZ", - "HH:mm:ss.FFFFFFFzzzzzz", - "yyyy-MM-dd", // date - "yyyy-MM-ddZ", - "yyyy-MM-ddzzzzzz", - "yyyy-MM", // yearMonth - "yyyy-MMZ", - "yyyy-MMzzzzzz", - "yyyy", // year - "yyyyZ", - "yyyyzzzzzz", - "--MM-dd", // monthDay - "--MM-ddZ", - "--MM-ddzzzzzz", - "---dd", // day - "---ddZ", - "---ddzzzzzz", - "--MM--", // month - "--MM--Z", - "--MM--zzzzzz", - }; - } + // no locking; the array is immutable so it's not a problem that it may get initialized more than once + s_allDateTimeFormats ??= new string[] { + "yyyy-MM-ddTHH:mm:ss.FFFFFFFzzzzzz", //dateTime + "yyyy-MM-ddTHH:mm:ss.FFFFFFF", + "yyyy-MM-ddTHH:mm:ss.FFFFFFFZ", + "HH:mm:ss.FFFFFFF", //time + "HH:mm:ss.FFFFFFFZ", + "HH:mm:ss.FFFFFFFzzzzzz", + "yyyy-MM-dd", // date + "yyyy-MM-ddZ", + "yyyy-MM-ddzzzzzz", + "yyyy-MM", // yearMonth + "yyyy-MMZ", + "yyyy-MMzzzzzz", + "yyyy", // year + "yyyyZ", + "yyyyzzzzzz", + "--MM-dd", // monthDay + "--MM-ddZ", + "--MM-ddzzzzzz", + "---dd", // day + "---ddZ", + "---ddzzzzzz", + "--MM--", // month + "--MM--Z", + "--MM--zzzzzz", + }; } [Obsolete("Use XmlConvert.ToDateTime() that accepts an XmlDateTimeSerializationMode instead.")] 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 fdb8db849b409..f2f1d753cf6ac 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 @@ -445,7 +445,7 @@ public void EndTree() public void WriteStartElementUnchecked(string prefix, string localName, string ns) { Debug.Assert(_xstate == XmlState.WithinContent, $"WriteStartElement cannot be called in the {_xstate} state."); - if (_nsmgr != null) _nsmgr.PushScope(); + _nsmgr?.PushScope(); Writer.WriteStartElement(prefix, localName, ns); //reset when enter element _usedPrefixes.Clear(); @@ -486,7 +486,7 @@ public void WriteEndElementUnchecked(string prefix, string localName, string ns) Writer.WriteEndElement(prefix, localName, ns); _xstate = XmlState.WithinContent; _depth--; - if (_nsmgr != null) _nsmgr.PopScope(); + _nsmgr?.PopScope(); } /// diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Focus.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Focus.cs index e3aa61adbfa94..9818b1f27534a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Focus.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Focus.cs @@ -182,15 +182,9 @@ public QilNode GetPosition() return _f.XsltConvert(_f.PositionOf(_current!), T.DoubleX); } - public QilNode GetLast() - { - if (_last == null) - { - // Create a let that will be fixed up later in ConstructLoop or by LastFixupVisitor - _last = _f.Let(_f.Double(0)); - } - return _last; - } + public QilNode GetLast() => + // Create a let that will be fixed up later in ConstructLoop or by LastFixupVisitor + _last ??= _f.Let(_f.Double(0)); public void EnsureCache() { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XsltLoader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XsltLoader.cs index 1032449681118..a7ab6fd2c0ccf 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XsltLoader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XsltLoader.cs @@ -2137,10 +2137,7 @@ private XslNode XslSort(int sortNumber) } } - if (select == null /*&& content.Count == 0*/) - { - select = "."; - } + select ??= "."; return SetInfo(F.Sort(select, lang, dataType, order, caseOrder, _input.XslVersion), null, ctxInfo diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/RootAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/RootAction.cs index 845fafa739e24..a03f38f66b04b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/RootAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/RootAction.cs @@ -119,10 +119,7 @@ public void PorcessAttributeSets(Stylesheet rootStylesheet) // As we mentioned we need to invert all lists. foreach (AttributeSetAction attSet in _attributeSetTable.Values) { - if (attSet.containedActions != null) - { - attSet.containedActions.Reverse(); - } + attSet.containedActions?.Reverse(); } // ensures there are no cycles in the attribute-sets use dfs marking method diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Stylesheet.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Stylesheet.cs index 907bfbe5742dc..7fa0c4e4bb882 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Stylesheet.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Stylesheet.cs @@ -357,10 +357,7 @@ internal void ReplaceNamespaceAlias(Compiler compiler) // If unsuccessful, search in imported documents from backwards // - if (action == null) - { - action = FindTemplateImports(processor, navigator); - } + action ??= FindTemplateImports(processor, navigator); return action; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TemplateManager.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TemplateManager.cs index bab17452c33a5..40c2b332e3b90 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TemplateManager.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TemplateManager.cs @@ -69,10 +69,7 @@ internal void AddTemplate(TemplateAction template) internal void ProcessTemplates() { - if (this.templates != null) - { - this.templates.Sort(s_TemplateComparer); - } + this.templates?.Sort(s_TemplateComparer); } internal TemplateAction? FindTemplate(Processor processor, XPathNavigator navigator) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XslTransform.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XslTransform.cs index afbfb2ccbe774..fbc9448619fdb 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XslTransform.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XslTransform.cs @@ -229,10 +229,7 @@ public void Transform(string inputfile, string outputfile, XmlResolver? resolver } finally { - if (fs != null) - { - fs.Dispose(); - } + fs?.Dispose(); } } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/PathUtilities.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/PathUtilities.cs index 03c69af04a2a1..e00e510ff412a 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/PathUtilities.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/PathUtilities.cs @@ -14,20 +14,10 @@ internal static class PathUtilities private static string? s_platformSpecificDirectorySeparator; - private static string PlatformSpecificDirectorySeparator - { - get - { - if (s_platformSpecificDirectorySeparator == null) - { - // '*' is a valid char on Unix-based FS - s_platformSpecificDirectorySeparator = - (Array.IndexOf(Path.GetInvalidFileNameChars(), '*') >= 0 ? DirectorySeparatorChar : AltDirectorySeparatorChar).ToString(); - } - - return s_platformSpecificDirectorySeparator; - } - } + private static string PlatformSpecificDirectorySeparator => + // '*' is a valid char on Unix-based FS + s_platformSpecificDirectorySeparator ??= + (Array.IndexOf(Path.GetInvalidFileNameChars(), '*') >= 0 ? DirectorySeparatorChar : AltDirectorySeparatorChar).ToString(); /// /// Returns the position in given path where the file name starts. diff --git a/src/libraries/System.Resources.Extensions/src/System/Resources/Extensions/PreserializedResourceWriter.cs b/src/libraries/System.Resources.Extensions/src/System/Resources/Extensions/PreserializedResourceWriter.cs index c7d52eebb8296..150b1183af657 100644 --- a/src/libraries/System.Resources.Extensions/src/System/Resources/Extensions/PreserializedResourceWriter.cs +++ b/src/libraries/System.Resources.Extensions/src/System/Resources/Extensions/PreserializedResourceWriter.cs @@ -163,14 +163,11 @@ public void AddBinaryFormattedResource(string name, byte[] value, string? typeNa throw new ArgumentNullException(nameof(value)); } - if (typeName == null) - { - // Some resx-files are missing type information for binary-formatted resources. - // These would have previously been handled by deserializing once, capturing the type - // and reserializing when writing the resources. We don't want to do that so instead - // we just omit the type. - typeName = UnknownObjectTypeName; - } + // Some resx-files are missing type information for binary-formatted resources. + // These would have previously been handled by deserializing once, capturing the type + // and reserializing when writing the resources. We don't want to do that so instead + // we just omit the type. + typeName ??= UnknownObjectTypeName; AddResourceData(name, typeName, new ResourceDataRecord(SerializationFormat.BinaryFormatter, value)); diff --git a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheMemoryMonitor.cs b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheMemoryMonitor.cs index 0443f61b3a886..e0c0f4a42402c 100644 --- a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheMemoryMonitor.cs +++ b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheMemoryMonitor.cs @@ -137,11 +137,7 @@ public void Dispose() { sref.Dispose(); } - IMemoryCacheManager memoryCacheManager = s_memoryCacheManager; - if (memoryCacheManager != null) - { - memoryCacheManager.ReleaseCache(_memoryCache); - } + s_memoryCacheManager?.ReleaseCache(_memoryCache); } internal static long EffectiveProcessMemoryLimit @@ -181,11 +177,7 @@ protected override int GetCurrentPressure() // remember the sample value _cacheSizeSamples[_idx] = sref.ApproximateSize; Dbg.Trace("MemoryCacheStats", "SizedRef.ApproximateSize=" + _cacheSizeSamples[_idx]); - IMemoryCacheManager memoryCacheManager = s_memoryCacheManager; - if (memoryCacheManager != null) - { - memoryCacheManager.UpdateCacheSize(_cacheSizeSamples[_idx], _memoryCache); - } + s_memoryCacheManager?.UpdateCacheSize(_cacheSizeSamples[_idx], _memoryCache); } // if there's no memory limit, then there's nothing more to do diff --git a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/Counters.cs b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/Counters.cs index fb91beb33db7d..7385f82d91280 100644 --- a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/Counters.cs +++ b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/Counters.cs @@ -81,11 +81,7 @@ private PollingCounter CreatePollingCounter(string name, string displayName, int { for (int i = 0; i < NUM_COUNTERS; i++) { - var counter = counters[i]; - if (counter != null) - { - counter.Dispose(); - } + counters[i]?.Dispose(); } } } diff --git a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCache.cs b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCache.cs index c135219062a6f..e740eed69ed51 100644 --- a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCache.cs +++ b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCache.cs @@ -109,10 +109,7 @@ private static bool IsPolicyValid(CacheItemPolicy policy) { foreach (ChangeMonitor monitor in changeMonitors) { - if (monitor != null) - { - monitor.Dispose(); - } + monitor?.Dispose(); } } return false; @@ -429,10 +426,7 @@ private object AddOrGetExistingInternal(string key, object value, CacheItemPolic { foreach (ChangeMonitor monitor in changeMonitors) { - if (monitor != null) - { - monitor.Dispose(); - } + monitor?.Dispose(); } } @@ -480,18 +474,12 @@ public void Dispose() // unhook domain events DisposeSafeCritical(); // stats must be disposed prior to disposing the stores. - if (_stats != null) - { - _stats.Dispose(); - } + _stats?.Dispose(); if (_storeRefs != null) { foreach (var storeRef in _storeRefs) { - if (storeRef != null) - { - storeRef.Dispose(); - } + storeRef?.Dispose(); } } if (_perfCounters != null) @@ -718,10 +706,7 @@ public override void Set(string key, object value, CacheItemPolicy policy, strin { foreach (ChangeMonitor monitor in changeMonitors) { - if (monitor != null) - { - monitor.Dispose(); - } + monitor?.Dispose(); } } @@ -762,10 +747,7 @@ internal void Set(string key, { foreach (ChangeMonitor monitor in changeMonitors) { - if (monitor != null) - { - monitor.Dispose(); - } + monitor?.Dispose(); } } diff --git a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCacheEntry.cs b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCacheEntry.cs index dcf2a6dadeb69..404091cda8c90 100644 --- a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCacheEntry.cs +++ b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCacheEntry.cs @@ -261,10 +261,7 @@ internal void Release(MemoryCache cache, CacheEntryRemovedReason reason) { foreach (MemoryCacheEntryChangeMonitor dependent in deps) { - if (dependent != null) - { - dependent.OnCacheEntryReleased(); - } + dependent?.OnCacheEntryReleased(); } } diff --git a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCacheEntryChangeMonitor.cs b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCacheEntryChangeMonitor.cs index 05d3aeca4b137..65c09fcc10d9d 100644 --- a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCacheEntryChangeMonitor.cs +++ b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCacheEntryChangeMonitor.cs @@ -115,10 +115,7 @@ protected override void Dispose(bool disposing) { foreach (MemoryCacheEntry entry in _dependencies) { - if (entry != null) - { - entry.RemoveDependent(this); - } + entry?.RemoveDependent(this); } } } diff --git a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCacheStatistics.cs b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCacheStatistics.cs index c6302aba8954d..96cfc3bda655b 100644 --- a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCacheStatistics.cs +++ b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCacheStatistics.cs @@ -348,10 +348,7 @@ public void Dispose() { Thread.Sleep(100); } - if (_cacheMemoryMonitor != null) - { - _cacheMemoryMonitor.Dispose(); - } + _cacheMemoryMonitor?.Dispose(); // Don't need to call GC.SuppressFinalize(this) for sealed types without finalizers. } } 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 27fde8ab2826f..343f3beb4a845 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 @@ -211,10 +211,7 @@ internal MemoryCacheEntry AddOrGetExisting(MemoryCacheKey key, MemoryCacheEntry // Call Release after the new entry has been completely added so // that the CacheItemRemovedCallback can take a dependency on the newly inserted item. - if (toBeReleasedEntry != null) - { - toBeReleasedEntry.Release(_cache, CacheEntryRemovedReason.Expired); - } + toBeReleasedEntry?.Release(_cache, CacheEntryRemovedReason.Expired); return existingEntry; } @@ -370,10 +367,7 @@ internal void Set(MemoryCacheKey key, MemoryCacheEntry entry) // Call Release after the new entry has been completely added so // that the CacheItemRemovedCallback can take a dependency on the newly inserted item. - if (existingEntry != null) - { - existingEntry.Release(_cache, reason); - } + existingEntry?.Release(_cache, reason); } internal long TrimInternal(int percent) diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryFormatterWriter.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryFormatterWriter.cs index 6e0362697b3c4..aee6fc66fbb77 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryFormatterWriter.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryFormatterWriter.cs @@ -122,20 +122,14 @@ internal void WriteObject(NameInfo nameInfo, NameInfo? typeNameInfo, int numMemb typeNameInfo.NIname : // Nested Object nameInfo.NIname; // Non-Nested - if (_objectMapTable == null) - { - _objectMapTable = new Dictionary(); - } + _objectMapTable ??= new Dictionary(); Debug.Assert(objectName != null); if (_objectMapTable.TryGetValue(objectName, out ObjectMapInfo? objectMapInfo) && objectMapInfo.IsCompatible(numMembers, memberNames, memberTypes)) { // Object - if (_binaryObject == null) - { - _binaryObject = new BinaryObject(); - } + _binaryObject ??= new BinaryObject(); _binaryObject.Set(objectId, objectMapInfo._objectId); _binaryObject.Write(this); @@ -143,10 +137,7 @@ internal void WriteObject(NameInfo nameInfo, NameInfo? typeNameInfo, int numMemb else if (!typeNameInfo._transmitTypeOnObject) { // ObjectWithMap - if (_binaryObjectWithMap == null) - { - _binaryObjectWithMap = new BinaryObjectWithMap(); - } + _binaryObjectWithMap ??= new BinaryObjectWithMap(); // BCL types are not placed into table assemId = (int)typeNameInfo._assemId; @@ -172,10 +163,7 @@ internal void WriteObject(NameInfo nameInfo, NameInfo? typeNameInfo, int numMemb assemIdA[i] = assemId; } - if (_binaryObjectWithMapTyped == null) - { - _binaryObjectWithMapTyped = new BinaryObjectWithMapTyped(); - } + _binaryObjectWithMapTyped ??= new BinaryObjectWithMapTyped(); // BCL types are not placed in table assemId = (int)typeNameInfo._assemId; @@ -192,10 +180,7 @@ internal void WriteObjectString(int objectId, string? value) { InternalWriteItemNull(); - if (_binaryObjectString == null) - { - _binaryObjectString = new BinaryObjectString(); - } + _binaryObjectString ??= new BinaryObjectString(); _binaryObjectString.Set(objectId, value); _binaryObjectString.Write(this); @@ -225,10 +210,7 @@ internal void WriteSingleArray(NameInfo memberNameInfo, NameInfo arrayNameInfo, BinaryTypeEnum binaryTypeEnum = BinaryTypeConverter.GetBinaryTypeInfo( arrayElemTypeNameInfo._type!, objectInfo, arrayElemTypeNameInfo.NIname, _objectWriter, out typeInformation, out assemId); - if (_binaryArray == null) - { - _binaryArray = new BinaryArray(); - } + _binaryArray ??= new BinaryArray(); _binaryArray.Set((int)arrayNameInfo._objectId, 1, lengthA, lowerBoundA, binaryTypeEnum, typeInformation, binaryArrayTypeEnum, assemId); _binaryArray.Write(this); @@ -255,10 +237,7 @@ private void WriteArrayAsBytes(Array array, int typeLength) { InternalWriteItemNull(); int arrayOffset = 0; - if (_byteBuffer == null) - { - _byteBuffer = new byte[ChunkSize]; - } + _byteBuffer ??= new byte[ChunkSize]; while (arrayOffset < array.Length) { @@ -306,10 +285,7 @@ internal void WriteJaggedArray(NameInfo memberNameInfo, NameInfo arrayNameInfo, BinaryTypeEnum binaryTypeEnum = BinaryTypeConverter.GetBinaryTypeInfo(arrayElemTypeNameInfo._type!, objectInfo, arrayElemTypeNameInfo.NIname, _objectWriter, out typeInformation, out assemId); - if (_binaryArray == null) - { - _binaryArray = new BinaryArray(); - } + _binaryArray ??= new BinaryArray(); _binaryArray.Set((int)arrayNameInfo._objectId, 1, lengthA, lowerBoundA, binaryTypeEnum, typeInformation, binaryArrayTypeEnum, assemId); _binaryArray.Write(this); @@ -324,10 +300,7 @@ internal void WriteRectangleArray(NameInfo memberNameInfo, NameInfo arrayNameInf int assemId; BinaryTypeEnum binaryTypeEnum = BinaryTypeConverter.GetBinaryTypeInfo(arrayElemTypeNameInfo._type!, objectInfo, arrayElemTypeNameInfo.NIname, _objectWriter, out typeInformation, out assemId); - if (_binaryArray == null) - { - _binaryArray = new BinaryArray(); - } + _binaryArray ??= new BinaryArray(); for (int i = 0; i < rank; i++) { @@ -356,19 +329,13 @@ internal void WriteMember(NameInfo memberNameInfo, NameInfo typeNameInfo, object // Writes Members with primitive values if (memberNameInfo._transmitTypeOnMember) { - if (_memberPrimitiveTyped == null) - { - _memberPrimitiveTyped = new MemberPrimitiveTyped(); - } + _memberPrimitiveTyped ??= new MemberPrimitiveTyped(); _memberPrimitiveTyped.Set(typeInformation, value); _memberPrimitiveTyped.Write(this); } else { - if (_memberPrimitiveUnTyped == null) - { - _memberPrimitiveUnTyped = new MemberPrimitiveUnTyped(); - } + _memberPrimitiveUnTyped ??= new MemberPrimitiveUnTyped(); _memberPrimitiveUnTyped.Set(typeInformation, value); _memberPrimitiveUnTyped.Write(this); } @@ -377,10 +344,7 @@ internal void WriteMember(NameInfo memberNameInfo, NameInfo typeNameInfo, object internal void WriteNullMember(NameInfo memberNameInfo, NameInfo typeNameInfo) { InternalWriteItemNull(); - if (_objectNull == null) - { - _objectNull = new ObjectNull(); - } + _objectNull ??= new ObjectNull(); if (!memberNameInfo._isArrayItem) { @@ -393,10 +357,7 @@ internal void WriteNullMember(NameInfo memberNameInfo, NameInfo typeNameInfo) internal void WriteMemberObjectRef(NameInfo memberNameInfo, int idRef) { InternalWriteItemNull(); - if (_memberReference == null) - { - _memberReference = new MemberReference(); - } + _memberReference ??= new MemberReference(); _memberReference.Set(idRef); _memberReference.Write(this); } @@ -435,10 +396,7 @@ private void InternalWriteItemNull() { if (_consecutiveNullArrayEntryCount > 0) { - if (_objectNull == null) - { - _objectNull = new ObjectNull(); - } + _objectNull ??= new ObjectNull(); _objectNull.SetNullCount(_consecutiveNullArrayEntryCount); _objectNull.Write(this); _consecutiveNullArrayEntryCount = 0; @@ -456,17 +414,11 @@ internal void WriteAssembly(Type? type, string assemblyString, int assemId, bool //If the file being tested wasn't built as an assembly, then we're going to get null back //for the assembly name. This is very unfortunate. InternalWriteItemNull(); - if (assemblyString == null) - { - assemblyString = string.Empty; - } + assemblyString ??= string.Empty; if (isNew) { - if (_binaryAssembly == null) - { - _binaryAssembly = new BinaryAssembly(); - } + _binaryAssembly ??= new BinaryAssembly(); _binaryAssembly.Set(assemId, assemblyString); _binaryAssembly.Write(this); } diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectInfo.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectInfo.cs index bcd5cd84e52ec..3a5476f069eb2 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectInfo.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectInfo.cs @@ -209,10 +209,7 @@ private void InitSiWrite() if (!_si.IsAssemblyNameSetExplicit) { - if (typeInformation == null) - { - typeInformation = BinaryFormatter.GetTypeInformation(_si.ObjectType); - } + typeInformation ??= BinaryFormatter.GetTypeInformation(_si.ObjectType); assemblyString = typeInformation.AssemblyString; hasTypeForwardedFrom = typeInformation.HasTypeForwardedFrom; } 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 ba514525295f1..4411b3b42d255 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 @@ -146,10 +146,7 @@ private void InitFullDeserialization() _fullDeserialization = true; _stack = new SerStack("ObjectReader Object Stack"); _objectManager = new ObjectManager(_surrogates, _context); - if (_formatterConverter == null) - { - _formatterConverter = new FormatterConverter(); - } + _formatterConverter ??= new FormatterConverter(); } internal object CrossAppDomainArray(int index) @@ -296,10 +293,7 @@ private void ParseObject(ParseRecord pr) TopObject = pr._newObj; } - if (pr._objectInfo == null) - { - pr._objectInfo = ReadObjectInfo.Create(pr._dtType, _surrogates, _context, _objectManager, _serObjectInfoInit, _formatterConverter, _isSimpleAssembly); - } + pr._objectInfo ??= ReadObjectInfo.Create(pr._dtType, _surrogates, _context, _objectManager, _serObjectInfoInit, _formatterConverter, _isSimpleAssembly); } // End of object encountered in stream @@ -926,10 +920,7 @@ internal long GetId(long objectId) { // Alarm bells. This is an old format. Deal with it. _oldFormatDetected = true; - if (_valTypeObjectIdTable == null) - { - _valTypeObjectIdTable = new IntSizedArray(); - } + _valTypeObjectIdTable ??= new IntSizedArray(); long tempObjId; if ((tempObjId = _valTypeObjectIdTable[(int)objectId]) == 0) diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectWriter.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectWriter.cs index 75edd9aa6ca1f..925e6eca7e207 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectWriter.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectWriter.cs @@ -963,10 +963,7 @@ internal InternalPrimitiveTypeE ToCode(Type? type) private long GetAssemblyId(WriteObjectInfo objectInfo) { //use objectInfo to get assembly string with new criteria - if (_assemblyToIdTable == null) - { - _assemblyToIdTable = new Dictionary(); - } + _assemblyToIdTable ??= new Dictionary(); long assemId; string assemblyString = objectInfo.GetAssemblyString(); diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryParser.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryParser.cs index 146240d838b03..b648c85b0ac4a 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryParser.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryParser.cs @@ -310,10 +310,7 @@ internal void ReadAssembly(BinaryHeaderEnum binaryHeaderEnum) [RequiresUnreferencedCode(BinaryParserUnreferencedCodeMessage)] private void ReadObject() { - if (_binaryObject == null) - { - _binaryObject = new BinaryObject(); - } + _binaryObject ??= new BinaryObject(); _binaryObject.Read(this); ObjectMap? objectMap = (ObjectMap?)ObjectMapIdTable[_binaryObject._mapId]; @@ -602,10 +599,7 @@ private void ReadObjectWithMapTyped(BinaryObjectWithMapTyped record) [RequiresUnreferencedCode(BinaryParserUnreferencedCodeMessage)] private void ReadObjectString(BinaryHeaderEnum binaryHeaderEnum) { - if (_objectString == null) - { - _objectString = new BinaryObjectString(); - } + _objectString ??= new BinaryObjectString(); if (binaryHeaderEnum == BinaryHeaderEnum.ObjectString) { @@ -613,10 +607,7 @@ private void ReadObjectString(BinaryHeaderEnum binaryHeaderEnum) } else { - if (_crossAppDomainString == null) - { - _crossAppDomainString = new BinaryCrossAppDomainString(); - } + _crossAppDomainString ??= new BinaryCrossAppDomainString(); _crossAppDomainString.Read(this); _objectString._value = _objectReader.CrossAppDomainArray(_crossAppDomainString._value) as string; if (_objectString._value == null) @@ -679,10 +670,7 @@ private void ReadObjectString(BinaryHeaderEnum binaryHeaderEnum) [RequiresUnreferencedCode(BinaryParserUnreferencedCodeMessage)] private void ReadMemberPrimitiveTyped() { - if (_memberPrimitiveTyped == null) - { - _memberPrimitiveTyped = new MemberPrimitiveTyped(); - } + _memberPrimitiveTyped ??= new MemberPrimitiveTyped(); _memberPrimitiveTyped.Read(this); PRs._objectTypeEnum = InternalObjectTypeE.Object; //Get rid of @@ -881,10 +869,7 @@ private void ReadArrayAsBytes(ParseRecord pr) Array array = (Array)pr._newObj; int arrayOffset = 0; - if (_byteBuffer == null) - { - _byteBuffer = new byte[ChunkSize]; - } + _byteBuffer ??= new byte[ChunkSize]; while (arrayOffset < array.Length) { @@ -914,10 +899,7 @@ private void ReadArrayAsBytes(ParseRecord pr) private void ReadMemberPrimitiveUnTyped() { ObjectProgress? objectOp = (ObjectProgress?)_stack.Peek(); - if (memberPrimitiveUnTyped == null) - { - memberPrimitiveUnTyped = new MemberPrimitiveUnTyped(); - } + memberPrimitiveUnTyped ??= new MemberPrimitiveUnTyped(); memberPrimitiveUnTyped.Set((InternalPrimitiveTypeE)_expectedTypeInformation!); memberPrimitiveUnTyped.Read(this); @@ -946,10 +928,7 @@ private void ReadMemberPrimitiveUnTyped() [RequiresUnreferencedCode(BinaryParserUnreferencedCodeMessage)] private void ReadMemberReference() { - if (_memberReference == null) - { - _memberReference = new MemberReference(); - } + _memberReference ??= new MemberReference(); _memberReference.Read(this); ObjectProgress? objectOp = (ObjectProgress?)_stack.Peek(); @@ -977,10 +956,7 @@ private void ReadMemberReference() [RequiresUnreferencedCode(BinaryParserUnreferencedCodeMessage)] private void ReadObjectNull(BinaryHeaderEnum binaryHeaderEnum) { - if (_objectNull == null) - { - _objectNull = new ObjectNull(); - } + _objectNull ??= new ObjectNull(); _objectNull.Read(this, binaryHeaderEnum); ObjectProgress? objectOp = (ObjectProgress?)_stack.Peek(); @@ -1009,10 +985,7 @@ private void ReadObjectNull(BinaryHeaderEnum binaryHeaderEnum) private void ReadMessageEnd() { - if (_messageEnd == null) - { - _messageEnd = new MessageEnd(); - } + _messageEnd ??= new MessageEnd(); _messageEnd.Read(this); if (!_stack.IsEmpty()) @@ -1062,10 +1035,7 @@ private ObjectProgress GetOp() private void PutOp(ObjectProgress op) { - if (_opPool == null) - { - _opPool = new SerStack("opPool"); - } + _opPool ??= new SerStack("opPool"); _opPool.Push(op); } } diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ObjectManager.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ObjectManager.cs index 408628217be32..523daff89fc77 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ObjectManager.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ObjectManager.cs @@ -1138,10 +1138,7 @@ internal void RemoveDependency(long id) /// The associated object manager. internal void AddFixup(FixupHolder fixup, ObjectManager manager) { - if (_missingElements == null) - { - _missingElements = new FixupHolderList(); - } + _missingElements ??= new FixupHolderList(); _missingElements.Add(fixup); _missingElementsRemaining++; @@ -1180,10 +1177,7 @@ private void UpdateDescendentDependencyChain(int amount, ObjectManager manager) /// the id of the object which is dependent on this object being provided. internal void AddDependency(long dependentObject) { - if (_dependentObjects == null) - { - _dependentObjects = new LongList(); - } + _dependentObjects ??= new LongList(); _dependentObjects.Add(dependentObject); } diff --git a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ObjectSecurity.cs b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ObjectSecurity.cs index a0103260f383c..38f8a1478a849 100644 --- a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ObjectSecurity.cs +++ b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ObjectSecurity.cs @@ -305,18 +305,12 @@ protected virtual void Persist(bool enableOwnershipPrivilege, string name, Acces catch { // protection against exception filter-based luring attacks - if (ownerPrivilege != null) - { - ownerPrivilege.Revert(); - } + ownerPrivilege?.Revert(); throw; } finally { - if (ownerPrivilege != null) - { - ownerPrivilege.Revert(); - } + ownerPrivilege?.Revert(); } } diff --git a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/SecurityDescriptor.cs b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/SecurityDescriptor.cs index abe5c5eb4a069..9fca7d63012e5 100644 --- a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/SecurityDescriptor.cs +++ b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/SecurityDescriptor.cs @@ -874,14 +874,11 @@ private void CreateFromParts(bool isContainer, bool isDS, ControlFlags flags, Se // Replace null DACL with an allow-all for everyone DACL // - if (discretionaryAcl == null) - { - // - // to conform to native behavior, we will add allow everyone ace for DACL - // + // + // to conform to native behavior, we will add allow everyone ace for DACL + // - discretionaryAcl = DiscretionaryAcl.CreateAllowEveryoneFullAccess(_isDS, _isContainer); - } + discretionaryAcl ??= DiscretionaryAcl.CreateAllowEveryoneFullAccess(_isDS, _isContainer); _dacl = discretionaryAcl; @@ -1191,20 +1188,14 @@ public void PurgeAccessControl(SecurityIdentifier sid) { ArgumentNullException.ThrowIfNull(sid); - if (DiscretionaryAcl != null) - { - DiscretionaryAcl.Purge(sid); - } + DiscretionaryAcl?.Purge(sid); } public void PurgeAudit(SecurityIdentifier sid) { ArgumentNullException.ThrowIfNull(sid); - if (SystemAcl != null) - { - SystemAcl.Purge(sid); - } + SystemAcl?.Purge(sid); } public void AddDiscretionaryAcl(byte revision, int trusted) diff --git a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/Win32.cs b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/Win32.cs index fda6a851db428..ba70283b6105b 100644 --- a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/Win32.cs +++ b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/Win32.cs @@ -168,18 +168,12 @@ out RawSecurityDescriptor? resultSd catch { // protection against exception filter-based luring attacks - if (privilege != null) - { - privilege.Revert(); - } + privilege?.Revert(); throw; } finally { - if (privilege != null) - { - privilege.Revert(); - } + privilege?.Revert(); } // @@ -321,18 +315,12 @@ internal static int SetSecurityInfo( catch { // protection against exception filter-based luring attacks - if (securityPrivilege != null) - { - securityPrivilege.Revert(); - } + securityPrivilege?.Revert(); throw; } finally { - if (securityPrivilege != null) - { - securityPrivilege.Revert(); - } + securityPrivilege?.Revert(); } return 0; diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.cs index 37ed52b63948a..c0831046595a2 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.cs @@ -34,16 +34,12 @@ public override byte[] GetSubjectKeyIdentifier(X509Certificate2 certificate) { Debug.Assert(certificate != null); - X509Extension? extension = certificate.Extensions[Oids.SubjectKeyIdentifier]; - - if (extension == null) - { - // Construct the value from the public key info. - extension = new X509SubjectKeyIdentifierExtension( + X509Extension extension = + certificate.Extensions[Oids.SubjectKeyIdentifier] ?? + new X509SubjectKeyIdentifierExtension( // Construct the value from the public key info. certificate.PublicKey, X509SubjectKeyIdentifierHashAlgorithm.CapiSha1, false); - } try { diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedXml.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedXml.cs index 537d1a5671dc3..3eb0d8d4a168b 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedXml.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedXml.cs @@ -235,8 +235,7 @@ private byte[] GetCipherValue(CipherData cipherData) Utils.Pump(decInputStream, ms); cipherValue = ms.ToArray(); // Close the stream and return - if (inputStream != null) - inputStream.Close(); + inputStream?.Close(); decInputStream.Close(); } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoX509Data.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoX509Data.cs index f92b4dbeee8c1..cfde60fc31ddb 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoX509Data.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoX509Data.cs @@ -184,10 +184,10 @@ public byte[] CRL private void Clear() { _CRL = null; - if (_subjectKeyIds != null) _subjectKeyIds.Clear(); - if (_subjectNames != null) _subjectNames.Clear(); - if (_issuerSerials != null) _issuerSerials.Clear(); - if (_certificates != null) _certificates.Clear(); + _subjectKeyIds?.Clear(); + _subjectNames?.Clear(); + _issuerSerials?.Clear(); + _certificates?.Clear(); } // diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Reference.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Reference.cs index 32a7cc444745e..e57a6117e3c5b 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Reference.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Reference.cs @@ -467,12 +467,9 @@ internal byte[] CalculateHashValue(XmlDocument document, CanonicalXmlNodeList re } finally { - if (hashInputStream != null) - hashInputStream.Close(); - if (response != null) - response.Close(); - if (inputStream != null) - inputStream.Close(); + hashInputStream?.Close(); + response?.Close(); + inputStream?.Close(); } return hashval; diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigXsltTransform.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigXsltTransform.cs index 4dfc3bc1a63b9..486888f48f13d 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigXsltTransform.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigXsltTransform.cs @@ -79,8 +79,7 @@ protected override XmlNodeList GetInnerXml() public override void LoadInput(object obj) { - if (_inputStream != null) - _inputStream.Close(); + _inputStream?.Close(); _inputStream = new MemoryStream(); if (obj is Stream) { diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlLicenseTransform.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlLicenseTransform.cs index 7222346b85b4e..5d4ec348f7288 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlLicenseTransform.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlLicenseTransform.cs @@ -83,14 +83,9 @@ private void DecryptEncryptedGrants(XmlNodeList encryptedGrantList, IRelDecrypto } finally { - if (toDecrypt != null) - toDecrypt.Close(); - - if (decryptedContent != null) - decryptedContent.Close(); - - if (streamReader != null) - streamReader.Close(); + toDecrypt?.Close(); + decryptedContent?.Close(); + streamReader?.Close(); } } } @@ -145,8 +140,7 @@ public override void LoadInput(object obj) throw new CryptographicException(SR.Cryptography_Xml_XrmlMissingIssuer); signatureNode = currentIssuerContext.SelectSingleNode("descendant-or-self::dsig:Signature[1]", _namespaceManager) as XmlElement; - if (signatureNode != null) - signatureNode.ParentNode.RemoveChild(signatureNode); + signatureNode?.ParentNode.RemoveChild(signatureNode); // Get the nearest license node currentLicenseContext = currentIssuerContext.SelectSingleNode("ancestor-or-self::r:license[1]", _namespaceManager) as XmlElement; diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/BasicSymmetricCipherCsp.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/BasicSymmetricCipherCsp.cs index 0ecad1312e15f..64129e5d57752 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/BasicSymmetricCipherCsp.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/BasicSymmetricCipherCsp.cs @@ -44,16 +44,16 @@ protected override void Dispose(bool disposing) if (disposing) { SafeCapiKeyHandle hKey = _hKey; - _hKey = null!; if (hKey != null) { + _hKey = null!; hKey.Dispose(); } SafeProvHandle hProvider = _hProvider; - _hProvider = null!; if (hProvider != null) { + _hProvider = null!; hProvider.Dispose(); } } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CapiHelper.Windows.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CapiHelper.Windows.cs index 53ad76441211e..5f626aa985803 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CapiHelper.Windows.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CapiHelper.Windows.cs @@ -1414,10 +1414,7 @@ private static SafeHashHandle CreateHashHandle(this SafeProvHandle hProv, byte[] } finally { - if (hHash != null) - { - hHash.Dispose(); - } + hHash?.Dispose(); } } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.Exists.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.Exists.cs index d91f72af329e0..c730c41372177 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.Exists.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.Exists.cs @@ -51,8 +51,7 @@ public static bool Exists(string keyName, CngProvider provider, CngKeyOpenOption } finally { - if (keyHandle != null) - keyHandle.Dispose(); + keyHandle?.Dispose(); } } } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.OpenHandle.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.OpenHandle.cs index 46f440a605af5..3344c0346742d 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.OpenHandle.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.OpenHandle.cs @@ -65,8 +65,7 @@ public static CngKey Open(SafeNCryptKeyHandle keyHandle, CngKeyHandleOpenOptions catch { // Make sure that we don't leak the handle the CngKey duplicated - if (key != null) - key.Dispose(); + key?.Dispose(); throw; } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.cs index dd78630eecf6f..9bfbd3a64ca55 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.cs @@ -25,15 +25,8 @@ private CngKey(SafeNCryptProviderHandle providerHandle, SafeNCryptKeyHandle keyH public void Dispose() { - if (_providerHandle != null) - { - _providerHandle.Dispose(); - } - - if (_keyHandle != null) - { - _keyHandle.Dispose(); - } + _providerHandle?.Dispose(); + _keyHandle?.Dispose(); } // diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CryptoConfig.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CryptoConfig.cs index 9b3e28ba527a4..dec1bb8460803 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CryptoConfig.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CryptoConfig.cs @@ -454,10 +454,7 @@ public static void AddAlgorithm(Type algorithm, params string[] names) return null; } - if (args == null) - { - args = Array.Empty(); - } + args ??= Array.Empty(); List candidates = new List(); for (int i = 0; i < cons.Length; i++) diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HashProviderCng.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HashProviderCng.cs index c4ff3154ab4ee..6e43501192766 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HashProviderCng.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HashProviderCng.cs @@ -145,9 +145,9 @@ public override void Reset() private void DestroyHash() { SafeBCryptHashHandle? hHash = _hHash; - _hHash = null; if (hHash != null) { + _hHash = null; hHash.Dispose(); } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/AppleCertificatePal.ImportExport.macOS.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/AppleCertificatePal.ImportExport.macOS.cs index f15d48e8ea61f..4e9d87d798c3f 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/AppleCertificatePal.ImportExport.macOS.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/AppleCertificatePal.ImportExport.macOS.cs @@ -94,11 +94,7 @@ public static ICertificatePal FromBlob( public void DisposeTempKeychain() { - SafeKeychainHandle? tempKeychain = Interlocked.Exchange(ref _tempKeychain, null); - if (tempKeychain != null) - { - tempKeychain.Dispose(); - } + Interlocked.Exchange(ref _tempKeychain, null)?.Dispose(); } internal unsafe byte[] ExportPkcs8(ReadOnlySpan password) diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/CertificatePal.Windows.Import.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/CertificatePal.Windows.Import.cs index c3d082cec1577..e79e50136887e 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/CertificatePal.Windows.Import.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/CertificatePal.Windows.Import.cs @@ -97,12 +97,9 @@ out pCertContext } finally { - if (hCertStore != null) - hCertStore.Dispose(); - if (hCryptMsg != null) - hCryptMsg.Dispose(); - if (pCertContext != null) - pCertContext.Dispose(); + hCertStore?.Dispose(); + hCryptMsg?.Dispose(); + pCertContext?.Dispose(); } } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/CertificatePal.Windows.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/CertificatePal.Windows.cs index 8c49a91f7aa85..f083e78cdf513 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/CertificatePal.Windows.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/CertificatePal.Windows.cs @@ -153,8 +153,7 @@ private byte[] PropagateKeyAlgorithmParametersFromChain() } finally { - if (certChainContext != null) - certChainContext.Dispose(); + certChainContext?.Dispose(); } } } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/ChainPal.Android.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/ChainPal.Android.cs index ba5e81365c994..99f807e63fb20 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/ChainPal.Android.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/ChainPal.Android.cs @@ -64,10 +64,7 @@ private sealed class AndroidCertPath : IChainPal public void Dispose() { - if (_chainContext != null) - { - _chainContext.Dispose(); - } + _chainContext?.Dispose(); } public bool? Verify(X509VerificationFlags flags, out Exception? exception) diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/ChainPal.Windows.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/ChainPal.Windows.cs index e2214b0de8944..4682b66e0ef0d 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/ChainPal.Windows.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/ChainPal.Windows.cs @@ -116,9 +116,11 @@ internal static partial bool ReleaseSafeX509ChainHandle(IntPtr handle) public void Dispose() { SafeX509ChainHandle? chain = _chain; - _chain = null!; if (chain != null) + { + _chain = null!; chain.Dispose(); + } } } } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/OpenSslDirectoryBasedStoreProvider.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/OpenSslDirectoryBasedStoreProvider.cs index 71bf0736ba3ee..f232e73cd5f79 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/OpenSslDirectoryBasedStoreProvider.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/OpenSslDirectoryBasedStoreProvider.cs @@ -316,15 +316,12 @@ internal static string GetStorePath(string storeName) { string directoryName = GetDirectoryName(storeName); - if (s_userStoreRoot == null) - { - // Do this here instead of a static field initializer so that - // the static initializer isn't capable of throwing the "home directory not found" - // exception. - s_userStoreRoot = PersistedFiles.GetUserFeatureDirectory( - X509Persistence.CryptographyFeatureName, - X509Persistence.X509StoresSubFeatureName); - } + // Do this here instead of a static field initializer so that + // the static initializer isn't capable of throwing the "home directory not found" + // exception. + s_userStoreRoot ??= PersistedFiles.GetUserFeatureDirectory( + X509Persistence.CryptographyFeatureName, + X509Persistence.X509StoresSubFeatureName); return Path.Combine(s_userStoreRoot, directoryName); } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/StorePal.Android.LoaderPal.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/StorePal.Android.LoaderPal.cs index 0bf66a2c3e6d4..b7c2758474d83 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/StorePal.Android.LoaderPal.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/StorePal.Android.LoaderPal.cs @@ -32,8 +32,7 @@ public AndroidCertLoader(ICertificatePal[] certs) public void Dispose() { - if (_certs != null) - _certs.DisposeAll(); + _certs?.DisposeAll(); } public void MoveTo(X509Certificate2Collection collection) diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/StorePal.Windows.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/StorePal.Windows.cs index f7c6079585c63..f8e871e76fee0 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/StorePal.Windows.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/StorePal.Windows.cs @@ -71,9 +71,11 @@ public void Remove(ICertificatePal certificate) public void Dispose() { SafeCertStoreHandle? certStore = _certStore; - _certStore = null!; if (certStore != null) + { + _certStore = null!; certStore.Dispose(); + } } internal SafeCertStoreHandle SafeCertStoreHandle diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Chain.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Chain.cs index e7b5cb142d798..29833577a7fac 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Chain.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Chain.cs @@ -182,9 +182,11 @@ public void Reset() _useMachineContext = false; IChainPal? pal = _pal; - _pal = null; if (pal != null) + { + _pal = null; pal.Dispose(); + } } } } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Store.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Store.cs index 0b666f842546f..07e68341d2c2e 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Store.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Store.cs @@ -113,10 +113,7 @@ public X509Certificate2Collection Certificates get { X509Certificate2Collection certificates = new X509Certificate2Collection(); - if (_storePal != null) - { - _storePal.CloneTo(certificates); - } + _storePal?.CloneTo(certificates); return certificates; } } @@ -211,9 +208,9 @@ public void Dispose() public void Close() { IStorePal? storePal = _storePal; - _storePal = null; if (storePal != null) { + _storePal = null; storePal.Dispose(); } } diff --git a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/WindowsIdentity.cs b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/WindowsIdentity.cs index 3eca69a5fb2e4..13b0e460657c7 100644 --- a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/WindowsIdentity.cs +++ b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/WindowsIdentity.cs @@ -198,8 +198,7 @@ public WindowsIdentity(string sUserPrincipalName) if (subStatus < 0) // non-negative numbers indicate success throw GetExceptionFromNtStatus(subStatus); - if (profileBuffer != null) - profileBuffer.Dispose(); + profileBuffer?.Dispose(); _safeTokenHandle = accessTokenHandle; } diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10FeedFormatter.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10FeedFormatter.cs index ec4388dfaaf26..74e4c851458cb 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10FeedFormatter.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10FeedFormatter.cs @@ -381,10 +381,7 @@ internal bool TryParseItemElementFrom(XmlReader reader, SyndicationItem result) internal static void WriteContentTo(XmlWriter writer, string elementName, SyndicationContent content) { - if (content != null) - { - content.WriteTo(writer, elementName, Atom10Constants.Atom10Namespace); - } + content?.WriteTo(writer, elementName, Atom10Constants.Atom10Namespace); } internal static void WriteElement(XmlWriter writer, string elementName, string value) diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/AtomPub10ServiceDocumentFormatter.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/AtomPub10ServiceDocumentFormatter.cs index a67968146a2aa..4056f67ce36e7 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/AtomPub10ServiceDocumentFormatter.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/AtomPub10ServiceDocumentFormatter.cs @@ -577,10 +577,7 @@ private void WriteCollection(XmlWriter writer, ResourceCollectionInfo collection writer.WriteAttributeString(App10Constants.Href, FeedUtils.GetUriString(collection.Link)); } WriteAttributeExtensions(writer, collection, Version); - if (collection.Title != null) - { - collection.Title.WriteTo(writer, Atom10Constants.TitleTag, Atom10Constants.Atom10Namespace); - } + collection.Title?.WriteTo(writer, Atom10Constants.TitleTag, Atom10Constants.Atom10Namespace); for (int i = 0; i < collection.Accepts.Count; ++i) { writer.WriteElementString(App10Constants.Prefix, App10Constants.Accept, App10Constants.Namespace, collection.Accepts[i]); @@ -625,10 +622,7 @@ private void WriteWorkspace(XmlWriter writer, Workspace workspace, Uri baseUri) WriteXmlBase(writer, baseUriToWrite); } WriteAttributeExtensions(writer, workspace, Version); - if (workspace.Title != null) - { - workspace.Title.WriteTo(writer, Atom10Constants.TitleTag, Atom10Constants.Atom10Namespace); - } + workspace.Title?.WriteTo(writer, Atom10Constants.TitleTag, Atom10Constants.Atom10Namespace); for (int i = 0; i < workspace.Collections.Count; ++i) { WriteCollection(writer, workspace.Collections[i], baseUri); diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ExtensibleSyndicationObject.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ExtensibleSyndicationObject.cs index 2695cb4645f63..3ae098aaa550b 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ExtensibleSyndicationObject.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ExtensibleSyndicationObject.cs @@ -109,10 +109,7 @@ internal void WriteElementExtensions(XmlWriter writer, Func new ExtensibleSyndicationObject(this); diff --git a/src/libraries/System.Speech/src/Internal/AsyncSerializedWorker.cs b/src/libraries/System.Speech/src/Internal/AsyncSerializedWorker.cs index 5d9184f059328..1b8275a770533 100644 --- a/src/libraries/System.Speech/src/Internal/AsyncSerializedWorker.cs +++ b/src/libraries/System.Speech/src/Internal/AsyncSerializedWorker.cs @@ -270,10 +270,7 @@ internal AsyncWorkItem(Delegate dynamicCallback, params object[] postData) internal void Invoke() { - if (_dynamicCallback != null) - { - _dynamicCallback.DynamicInvoke(_postData); - } + _dynamicCallback?.DynamicInvoke(_postData); } private Delegate _dynamicCallback; diff --git a/src/libraries/System.Speech/src/Internal/GrammarBuilding/OneOfElement.cs b/src/libraries/System.Speech/src/Internal/GrammarBuilding/OneOfElement.cs index 8045b2e59e8ac..c22631c65d4a6 100644 --- a/src/libraries/System.Speech/src/Internal/GrammarBuilding/OneOfElement.cs +++ b/src/libraries/System.Speech/src/Internal/GrammarBuilding/OneOfElement.cs @@ -33,11 +33,7 @@ internal override IElement CreateElement(IElementFactory elementFactory, IElemen IOneOf oneOf = elementFactory.CreateOneOf(parent, rule); foreach (GrammarBuilderBase item in Items) { - ItemElement newItem = item as ItemElement; - if (newItem == null) - { - newItem = new ItemElement(item); - } + ItemElement newItem = item as ItemElement ?? new ItemElement(item); IItem element = (IItem)newItem.CreateElement(elementFactory, oneOf, rule, ruleIds); element.PostParse(oneOf); diff --git a/src/libraries/System.Speech/src/Internal/ObjectToken/SAPICategories.cs b/src/libraries/System.Speech/src/Internal/ObjectToken/SAPICategories.cs index 057ded55c2ff1..afc092b996505 100644 --- a/src/libraries/System.Speech/src/Internal/ObjectToken/SAPICategories.cs +++ b/src/libraries/System.Speech/src/Internal/ObjectToken/SAPICategories.cs @@ -16,17 +16,11 @@ internal static ObjectToken DefaultToken(string category) { Helpers.ThrowIfEmptyOrNull(category, nameof(category)); - ObjectToken token = null; // Try first to get the preferred token for the current user - token = DefaultToken(@"HKEY_CURRENT_USER\SOFTWARE\Microsoft\Speech\" + category, _defaultTokenIdValueName); - - // IF failed try to get it for the local machine - if (token == null) - { - token = DefaultToken(SpeechRegistryKey + category, _defaultTokenIdValueName); - } - - return token; + // If failed try to get it for the local machine + return + DefaultToken(@"HKEY_CURRENT_USER\SOFTWARE\Microsoft\Speech\" + category, _defaultTokenIdValueName) ?? + DefaultToken(SpeechRegistryKey + category, _defaultTokenIdValueName); } /// diff --git a/src/libraries/System.Speech/src/Internal/SapiInterop/SapiGrammar.cs b/src/libraries/System.Speech/src/Internal/SapiInterop/SapiGrammar.cs index 290af3331d561..35b0a2b9ae1ac 100644 --- a/src/libraries/System.Speech/src/Internal/SapiInterop/SapiGrammar.cs +++ b/src/libraries/System.Speech/src/Internal/SapiInterop/SapiGrammar.cs @@ -92,17 +92,8 @@ internal void SetDictationWeight(float weight) #region Internal Properties - internal ISpRecoGrammar2 SpRecoGrammar2 - { - get - { - if (_sapiGrammar2 == null) - { - _sapiGrammar2 = (ISpRecoGrammar2)_sapiGrammar; - } - return _sapiGrammar2; - } - } + internal ISpRecoGrammar2 SpRecoGrammar2 => + _sapiGrammar2 ??= (ISpRecoGrammar2)_sapiGrammar; #endregion diff --git a/src/libraries/System.Speech/src/Internal/SapiInterop/SapiProxy.cs b/src/libraries/System.Speech/src/Internal/SapiInterop/SapiProxy.cs index c7a7269638289..59c4859ca9bb5 100644 --- a/src/libraries/System.Speech/src/Internal/SapiInterop/SapiProxy.cs +++ b/src/libraries/System.Speech/src/Internal/SapiInterop/SapiProxy.cs @@ -35,29 +35,11 @@ internal ISpRecognizer Recognizer } } - internal ISpRecognizer2 Recognizer2 - { - get - { - if (_recognizer2 == null) - { - _recognizer2 = (ISpRecognizer2)_recognizer; - } - return _recognizer2; - } - } + internal ISpRecognizer2 Recognizer2 => + _recognizer2 ??= (ISpRecognizer2)_recognizer; - internal ISpeechRecognizer SapiSpeechRecognizer - { - get - { - if (_speechRecognizer == null) - { - _speechRecognizer = (ISpeechRecognizer)_recognizer; - } - return _speechRecognizer; - } - } + internal ISpeechRecognizer SapiSpeechRecognizer => + _speechRecognizer ??= (ISpeechRecognizer)_recognizer; #endregion diff --git a/src/libraries/System.Speech/src/Internal/SrgsCompiler/Arc.cs b/src/libraries/System.Speech/src/Internal/SrgsCompiler/Arc.cs index 8d7f0e1d271da..1887709010a15 100644 --- a/src/libraries/System.Speech/src/Internal/SrgsCompiler/Arc.cs +++ b/src/libraries/System.Speech/src/Internal/SrgsCompiler/Arc.cs @@ -315,19 +315,13 @@ internal static int CompareIdenticalTransitions(Arc arc1, Arc arc2) internal void AddStartTag(Tag tag) { - if (_startTags == null) - { - _startTags = new Collection(); - } + _startTags ??= new Collection(); _startTags.Add(tag); } internal void AddEndTag(Tag tag) { - if (_endTags == null) - { - _endTags = new Collection(); - } + _endTags ??= new Collection(); _endTags.Add(tag); } @@ -403,10 +397,7 @@ internal void CloneTags(Arc arc, List _tags, Dictionary endArcs, { if (arc._startTags != null) { - if (_startTags == null) - { - _startTags = new Collection(); - } + _startTags ??= new Collection(); foreach (Tag tag in arc._startTags) { Tag newTag = new(tag); @@ -432,10 +423,7 @@ internal void CloneTags(Arc arc, List _tags, Dictionary endArcs, if (arc._endTags != null) { - if (_endTags == null) - { - _endTags = new Collection(); - } + _endTags ??= new Collection(); foreach (Tag tag in arc._endTags) { Tag newTag = endArcs[tag]; @@ -480,15 +468,8 @@ internal bool SameTags(Arc arc) internal void ConnectStates() { - if (_end != null) - { - _end.InArcs.Add(this); - } - - if (_start != null) - { - _start.OutArcs.Add(this); - } + _end?.InArcs.Add(this); + _start?.OutArcs.Add(this); } /// @@ -639,15 +620,9 @@ internal State Start { if (value != _start) { - if (_start != null) - { - _start.OutArcs.Remove(this); - } + _start?.OutArcs.Remove(this); _start = value; - if (_start != null) - { - _start.OutArcs.Add(this); - } + _start?.OutArcs.Add(this); } } } @@ -663,15 +638,9 @@ internal State End // If no change, then do nothing if (value != _end) { - if (_end != null) - { - _end.InArcs.Remove(this); - } + _end?.InArcs.Remove(this); _end = value; - if (_end != null) - { - _end.InArcs.Add(this); - } + _end?.InArcs.Add(this); } } } diff --git a/src/libraries/System.Speech/src/Internal/SrgsCompiler/BackEnd.cs b/src/libraries/System.Speech/src/Internal/SrgsCompiler/BackEnd.cs index 574cd63be4097..e9459c9192298 100644 --- a/src/libraries/System.Speech/src/Internal/SrgsCompiler/BackEnd.cs +++ b/src/libraries/System.Speech/src/Internal/SrgsCompiler/BackEnd.cs @@ -612,10 +612,7 @@ internal void CloneSubGraph(Rule rule, Backend org, Backend extra, Dictionary mergeStat if (!skipTransition) { // Lazy init as entering this loop is a rare event - if (arcsToMerge == null) - { - arcsToMerge = new List(); - } + arcsToMerge ??= new List(); // Add the first element if (!refSet) { @@ -618,10 +615,7 @@ private void MergeDuplicateOutputTransitions(ArcList arcs, Stack mergeSta if (!skipTransition) { // Lazy init as entering this loop is a rare event - if (arcsToMerge == null) - { - arcsToMerge = new List(); - } + arcsToMerge ??= new List(); // Add the first element if (!refSet) { @@ -847,10 +841,7 @@ private static void MergeIdenticalTransitions(ArcList arcs, List identicalW if (identicalWords.Count >= 2) { identicalWords.Sort(Arc.CompareIdenticalTransitions); - if (segmentsToDelete == null) - { - segmentsToDelete = new List>(); - } + segmentsToDelete ??= new List>(); // Add the list of same words into a list for further processing. // The expectation of having an identical transition is very low so the code @@ -908,11 +899,8 @@ private static void MergeIdenticalTransitions(List identicalWords) // Identical transition arc.Weight += refArc.Weight; refArc.ClearTags(); - if (arcsToDelete == null) - { - // delay the creation of the collection as this operation in infrequent. - arcsToDelete = new Collection(); - } + // delay the creation of the collection as this operation in infrequent. + arcsToDelete ??= new Collection(); arcsToDelete.Add(refArc); } refArc = arc; diff --git a/src/libraries/System.Speech/src/Internal/SrgsCompiler/ParseElementCollection.cs b/src/libraries/System.Speech/src/Internal/SrgsCompiler/ParseElementCollection.cs index cd15cffe0b3e3..c1f8922e74c4e 100644 --- a/src/libraries/System.Speech/src/Internal/SrgsCompiler/ParseElementCollection.cs +++ b/src/libraries/System.Speech/src/Internal/SrgsCompiler/ParseElementCollection.cs @@ -37,10 +37,7 @@ internal void AddSemanticInterpretationTag(CfgGrammar.CfgProperty propertyInfo) } else { - if (_startArc == null) - { - _startArc = _endArc = _backend.EpsilonTransition(1.0f); - } + _startArc ??= _endArc = _backend.EpsilonTransition(1.0f); _backend.AddSemanticInterpretationTag(_endArc, propertyInfo); } } @@ -49,10 +46,7 @@ internal void AddSemanticInterpretationTag(CfgGrammar.CfgProperty propertyInfo) // _propInfo._ulId = (uint) ((ParseElement) parent).StartState._rule._iSerialize2; internal void AddSementicPropertyTag(CfgGrammar.CfgProperty propertyInfo) { - if (_startArc == null) - { - _startArc = _endArc = _backend.EpsilonTransition(1.0f); - } + _startArc ??= _endArc = _backend.EpsilonTransition(1.0f); _backend.AddPropertyTag(_startArc, _endArc, propertyInfo); } diff --git a/src/libraries/System.Speech/src/Internal/SrgsCompiler/RuleRef.cs b/src/libraries/System.Speech/src/Internal/SrgsCompiler/RuleRef.cs index 0d3e3aa49af1f..4538990bbb3d6 100644 --- a/src/libraries/System.Speech/src/Internal/SrgsCompiler/RuleRef.cs +++ b/src/libraries/System.Speech/src/Internal/SrgsCompiler/RuleRef.cs @@ -68,10 +68,7 @@ internal RuleRef(ParseElementCollection parent, Backend backend, Uri uri, List(); - } + tags ??= new List(); tags.Add(tag); } break; diff --git a/src/libraries/System.Speech/src/Internal/Synthesis/AudioDeviceOut.cs b/src/libraries/System.Speech/src/Internal/Synthesis/AudioDeviceOut.cs index 40b1ecfcfa20d..216e3149ac651 100644 --- a/src/libraries/System.Speech/src/Internal/Synthesis/AudioDeviceOut.cs +++ b/src/libraries/System.Speech/src/Internal/Synthesis/AudioDeviceOut.cs @@ -454,20 +454,14 @@ internal InItem(object userData) } public void Dispose() { - if (_waveHeader != null) - { - _waveHeader.Dispose(); - } + _waveHeader?.Dispose(); GC.SuppressFinalize(this); } internal void ReleaseData() { - if (_waveHeader != null) - { - _waveHeader.ReleaseData(); - } + _waveHeader?.ReleaseData(); } internal WaveHeader _waveHeader; diff --git a/src/libraries/System.Speech/src/Internal/Synthesis/EngineSite.cs b/src/libraries/System.Speech/src/Internal/Synthesis/EngineSite.cs index edbdc5deb2e26..fc88d65b50552 100644 --- a/src/libraries/System.Speech/src/Internal/Synthesis/EngineSite.cs +++ b/src/libraries/System.Speech/src/Internal/Synthesis/EngineSite.cs @@ -204,10 +204,7 @@ public void FlushEvent() internal void SetEventsInterest(int eventInterest) { _eventInterest = eventInterest; - if (_eventMapper != null) - { - _eventMapper.FlushEvent(); - } + _eventMapper?.FlushEvent(); } #endregion @@ -347,10 +344,7 @@ internal TtsEventMapper(ITtsEventSink sink) protected virtual void SendToOutput(TTSEvent evt) { - if (_sink != null) - { - _sink.AddEvent(evt); - } + _sink?.AddEvent(evt); } public virtual void AddEvent(TTSEvent evt) @@ -360,10 +354,7 @@ public virtual void AddEvent(TTSEvent evt) public virtual void FlushEvent() { - if (_sink != null) - { - _sink.FlushEvent(); - } + _sink?.FlushEvent(); } private ITtsEventSink _sink; diff --git a/src/libraries/System.Speech/src/Internal/Synthesis/SSmlParser.cs b/src/libraries/System.Speech/src/Internal/Synthesis/SSmlParser.cs index de41d0223ea56..f8122222920f0 100644 --- a/src/libraries/System.Speech/src/Internal/Synthesis/SSmlParser.cs +++ b/src/libraries/System.Speech/src/Internal/Synthesis/SSmlParser.cs @@ -1156,10 +1156,7 @@ private static void ParseVoice(XmlReader reader, ISsmlParser engine, SsmlElement { if (reader.Value != xmlNamespaceSsml) { - if (localUnknownNamespaces == null) - { - localUnknownNamespaces = new List(); - } + localUnknownNamespaces ??= new List(); SsmlXmlAttribute ns = new(reader.Prefix, reader.LocalName, reader.Value, reader.NamespaceURI); localUnknownNamespaces.Add(ns); @@ -1168,10 +1165,7 @@ private static void ParseVoice(XmlReader reader, ISsmlParser engine, SsmlElement } else { - if (extraAttributesVoice == null) - { - extraAttributesVoice = new List(); - } + extraAttributesVoice ??= new List(); extraAttributesVoice.Add(new SsmlXmlAttribute(reader.Prefix, reader.LocalName, reader.Value, reader.NamespaceURI)); } } @@ -1840,10 +1834,7 @@ internal bool AddUnknowAttribute(SsmlXmlAttribute attribute, ref List(); - } + extraAttributes ??= new List(); extraAttributes.Add(attribute); return true; } @@ -1857,10 +1848,7 @@ internal bool AddUnknowAttribute(XmlReader reader, ref List ex { if (ns._name == reader.Prefix) { - if (extraAttributes == null) - { - extraAttributes = new List(); - } + extraAttributes ??= new List(); extraAttributes.Add(new SsmlXmlAttribute(reader.Prefix, reader.LocalName, reader.Value, reader.NamespaceURI)); return true; } diff --git a/src/libraries/System.Speech/src/Internal/Synthesis/VoiceSynthesis.cs b/src/libraries/System.Speech/src/Internal/Synthesis/VoiceSynthesis.cs index 53ff9e4d5b2ec..47576c0a0d4d2 100644 --- a/src/libraries/System.Speech/src/Internal/Synthesis/VoiceSynthesis.cs +++ b/src/libraries/System.Speech/src/Internal/Synthesis/VoiceSynthesis.cs @@ -449,10 +449,7 @@ internal void Pause() { lock (_waveOut) { - if (_waveOut != null) - { - _waveOut.Pause(); - } + _waveOut?.Pause(); lock (_pendingSpeakQueue) { @@ -474,10 +471,7 @@ internal void Resume() { lock (_waveOut) { - if (_waveOut != null) - { - _waveOut.Resume(); - } + _waveOut?.Resume(); lock (_pendingSpeakQueue) { if (_pendingSpeakQueue.Count > 0 || _currentPrompt != null) @@ -964,10 +958,7 @@ private static uint GetDefaultRate() uint lCurrRateAd = 0; using (ObjectTokenCategory category = ObjectTokenCategory.Create(SAPICategories.CurrentUserVoices)) { - if (category != null) - { - category.TryGetDWORD(defaultVoiceRate, ref lCurrRateAd); - } + category?.TryGetDWORD(defaultVoiceRate, ref lCurrRateAd); } return lCurrRateAd; } @@ -977,10 +968,7 @@ private void InjectEvent(TtsEventId evtId, Prompt prompt, Exception exception, V // If the prompt is terminated, release it ASAP if (evtId == TtsEventId.EndInputStream) { - if (_site.EventMapper != null) - { - _site.EventMapper.FlushEvent(); - } + _site.EventMapper?.FlushEvent(); prompt.Exception = exception; } @@ -1139,10 +1127,7 @@ private TTSVoice GetEngineWithVoice(TTSVoice defaultVoice, VoiceInfo defaultVoic // Pick the first one in the list as the backup default while (voice == null && _installedVoices.Count > 0) { - if (viDefault == null) - { - viDefault = InstalledVoice.FirstEnabled(_installedVoices, CultureInfo.CurrentUICulture); - } + viDefault ??= InstalledVoice.FirstEnabled(_installedVoices, CultureInfo.CurrentUICulture); if (viDefault != null) { @@ -1363,10 +1348,7 @@ private TTSVoice GetProxyEngine(VoiceInfo voiceInfo) ITtsEngineProxy engineProxy = GetSsmlEngine(voiceInfo); // Try to get a COM engine - if (engineProxy == null) - { - engineProxy = GetComEngine(voiceInfo); - } + engineProxy ??= GetComEngine(voiceInfo); // store the proxy object TTSVoice voice = null; @@ -1633,10 +1615,7 @@ private void Dispose(bool disposing) // Free the COM resources used foreach (KeyValuePair kv in _voiceDictionary) { - if (kv.Value != null) - { - kv.Value.TtsEngine.ReleaseInterface(); - } + kv.Value?.TtsEngine.ReleaseInterface(); } _voiceDictionary.Clear(); diff --git a/src/libraries/System.Speech/src/Recognition/Grammar.cs b/src/libraries/System.Speech/src/Recognition/Grammar.cs index 7a3135dc8c90a..d7f19a4262dd5 100644 --- a/src/libraries/System.Speech/src/Recognition/Grammar.cs +++ b/src/libraries/System.Speech/src/Recognition/Grammar.cs @@ -553,10 +553,7 @@ internal Grammar Find(string ruleName) /// internal void AddRuleRef(Grammar ruleRef, uint grammarId) { - if (_ruleRefs == null) - { - _ruleRefs = new Collection(); - } + _ruleRefs ??= new Collection(); _ruleRefs.Add(ruleRef); _sapiGrammarId = grammarId; } diff --git a/src/libraries/System.Speech/src/Recognition/RecognizerBase.cs b/src/libraries/System.Speech/src/Recognition/RecognizerBase.cs index c91a07ee333e3..e30f7c1830f55 100644 --- a/src/libraries/System.Speech/src/Recognition/RecognizerBase.cs +++ b/src/libraries/System.Speech/src/Recognition/RecognizerBase.cs @@ -1180,10 +1180,7 @@ internal SpeechAudioFormatInfo AudioFormat return null; } - if (_audioFormat == null) - { - _audioFormat = GetSapiAudioFormat(); - } + _audioFormat ??= GetSapiAudioFormat(); } return _audioFormat; } @@ -2905,11 +2902,8 @@ private void FireRecognizeCompletedEvent(RecognitionResult result, bool initialS { // In the synchronous case, fire the private event EventHandler recognizeCompletedHandler = RecognizeCompletedSync; - if (recognizeCompletedHandler == null) - { - // If not in sync mode, fire the public event. - recognizeCompletedHandler = RecognizeCompleted; - } + // If not in sync mode, fire the public event. + recognizeCompletedHandler ??= RecognizeCompleted; // Fire the completed event if (recognizeCompletedHandler != null) @@ -2929,11 +2923,8 @@ private void FireEmulateRecognizeCompletedEvent(RecognitionResult result, Except { // In the synchronous case, fire the private event emulateRecognizeCompletedHandler = EmulateRecognizeCompletedSync; - if (emulateRecognizeCompletedHandler == null) - { - // If not in sync mode, fire the public event. - emulateRecognizeCompletedHandler = EmulateRecognizeCompleted; - } + // If not in sync mode, fire the public event. + emulateRecognizeCompletedHandler ??= EmulateRecognizeCompleted; _lastResult = null; _lastException = null; _isEmulateRecognition = false; diff --git a/src/libraries/System.Speech/src/Result/RecognizedPhrase.cs b/src/libraries/System.Speech/src/Result/RecognizedPhrase.cs index 004b7609400a5..864b97a902470 100644 --- a/src/libraries/System.Speech/src/Result/RecognizedPhrase.cs +++ b/src/libraries/System.Speech/src/Result/RecognizedPhrase.cs @@ -644,10 +644,7 @@ private static void InsertSemanticValueToDictionary(SemanticValue semanticValue, } while (semanticValue._dictionary.ContainsKey(key)); semanticValue._dictionary.Add(key, thisSemanticValue); - if (dupItems == null) - { - dupItems = new Collection(); - } + dupItems ??= new Collection(); SemanticValue s = semanticValue._dictionary[key]; dupItems.Add(s); } diff --git a/src/libraries/System.Speech/src/Synthesis/InstalledVoice.cs b/src/libraries/System.Speech/src/Synthesis/InstalledVoice.cs index 3f6fa46904fd6..ebcc74d8cb0f1 100644 --- a/src/libraries/System.Speech/src/Synthesis/InstalledVoice.cs +++ b/src/libraries/System.Speech/src/Synthesis/InstalledVoice.cs @@ -88,10 +88,7 @@ internal static InstalledVoice FirstEnabled(List list, CultureIn { return ti; } - if (voiceFirst == null) - { - voiceFirst = ti; - } + voiceFirst ??= ti; } } return voiceFirst; diff --git a/src/libraries/System.Speech/src/Synthesis/PromptBuilder.cs b/src/libraries/System.Speech/src/Synthesis/PromptBuilder.cs index 4c7c1d19881b8..9dc8222992f00 100644 --- a/src/libraries/System.Speech/src/Synthesis/PromptBuilder.cs +++ b/src/libraries/System.Speech/src/Synthesis/PromptBuilder.cs @@ -236,10 +236,7 @@ public void StartStyle(PromptStyle style) sVolumeLevel = style.Volume.ToString().ToLowerInvariant(); break; } - if (prosodyElement._attributes == null) - { - prosodyElement._attributes = new Collection(); - } + prosodyElement._attributes ??= new Collection(); prosodyElement._attributes.Add(new AttributeItem("volume", sVolumeLevel)); } diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DBCSCodePageEncoding.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DBCSCodePageEncoding.cs index bdfe2aaba74ec..17a20883ae014 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DBCSCodePageEncoding.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DBCSCodePageEncoding.cs @@ -1171,8 +1171,7 @@ public DBCSDecoder(DBCSCodePageEncoding encoding) : base(encoding) public override void Reset() { bLeftOver = 0; - if (m_fallbackBuffer != null) - m_fallbackBuffer.Reset(); + m_fallbackBuffer?.Reset(); } // Anything left in our decoder? diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/GB18030Encoding.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/GB18030Encoding.cs index d4d9f5284e8b8..9ba6211d80b53 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/GB18030Encoding.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/GB18030Encoding.cs @@ -801,8 +801,7 @@ public override void Reset() bLeftOver2 = -1; bLeftOver3 = -1; bLeftOver4 = -1; - if (m_fallbackBuffer != null) - m_fallbackBuffer.Reset(); + m_fallbackBuffer?.Reset(); } // Anything left in our decoder? diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/ISCIIEncoding.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/ISCIIEncoding.cs index 57e3e78079b59..65c4ab496906e 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/ISCIIEncoding.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/ISCIIEncoding.cs @@ -714,8 +714,7 @@ public override void Reset() { bLastVirama = false; charLeftOver = (char)0; - if (m_fallbackBuffer != null) - m_fallbackBuffer.Reset(); + m_fallbackBuffer?.Reset(); } // Anything left in our encoder? @@ -754,8 +753,7 @@ public override void Reset() bLastDevenagariStressAbbr = false; cLastCharForNextNukta = '\0'; cLastCharForNoNextNukta = '\0'; - if (m_fallbackBuffer != null) - m_fallbackBuffer.Reset(); + m_fallbackBuffer?.Reset(); } // Anything left in our decoder? diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/ISO2022Encoding.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/ISO2022Encoding.cs index 566f570115ef0..a914a57eb4450 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/ISO2022Encoding.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/ISO2022Encoding.cs @@ -1803,8 +1803,7 @@ public override void Reset() currentMode = ISO2022Modes.ModeASCII; shiftInOutMode = ISO2022Modes.ModeASCII; charLeftOver = (char)0; - if (m_fallbackBuffer != null) - m_fallbackBuffer.Reset(); + m_fallbackBuffer?.Reset(); } // Anything left in our encoder? @@ -1838,8 +1837,7 @@ public override void Reset() bytesLeftOver = new byte[4]; currentMode = ISO2022Modes.ModeASCII; shiftInOutMode = ISO2022Modes.ModeASCII; - if (m_fallbackBuffer != null) - m_fallbackBuffer.Reset(); + m_fallbackBuffer?.Reset(); } // Anything left in our decoder? 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 6ea733160e139..1143d89c0cd86 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 @@ -21,10 +21,7 @@ public sealed partial class JsonArray : JsonNode, IList /// public void Add(JsonNode? item) { - if (item != null) - { - item.AssignParent(this); - } + item?.AssignParent(this); List.Add(item); } 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 4681944426d72..898e68f3c6369 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 @@ -138,10 +138,7 @@ internal override void GetPath(List path, JsonNode? child) } } - if (Parent != null) - { - Parent.GetPath(path, this); - } + Parent?.GetPath(path, this); } internal void SetItem(string propertyName, JsonNode? value) diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValue.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValue.cs index 9458841277f3a..1853aad3e0f6c 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValue.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValue.cs @@ -92,10 +92,7 @@ internal override void GetPath(List path, JsonNode? child) { Debug.Assert(child == null); - if (Parent != null) - { - Parent.GetPath(path, this); - } + Parent?.GetPath(path, this); } /// diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectWithParameterizedConstructorConverter.Small.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectWithParameterizedConstructorConverter.Small.cs index a16958ec19be2..f206adba75f2d 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectWithParameterizedConstructorConverter.Small.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectWithParameterizedConstructorConverter.Small.cs @@ -78,11 +78,8 @@ protected override void InitializeConstructorArgumentCaches(ref ReadStack state, { JsonTypeInfo typeInfo = state.Current.JsonTypeInfo; - if (typeInfo.CreateObjectWithArgs == null) - { - typeInfo.CreateObjectWithArgs = - options.MemberAccessorStrategy.CreateParameterizedConstructor(ConstructorInfo!); - } + typeInfo.CreateObjectWithArgs ??= + options.MemberAccessorStrategy.CreateParameterizedConstructor(ConstructorInfo!); var arguments = new Arguments(); 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 33eb11b76bb28..1fd7d2c452bb2 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 @@ -576,27 +576,18 @@ public ReferenceHandler? ReferenceHandler // Workaround https://github.com/dotnet/linker/issues/2715 [UnconditionalSuppressMessage("AotAnalysis", "IL3050:RequiresDynamicCode", Justification = "Dynamic path is guarded by the runtime feature switch.")] - internal MemberAccessor MemberAccessorStrategy - { - get - { - if (_memberAccessorStrategy == null) - { + internal MemberAccessor MemberAccessorStrategy => + _memberAccessorStrategy ??= #if NETCOREAPP - // if dynamic code isn't supported, fallback to reflection - _memberAccessorStrategy = RuntimeFeature.IsDynamicCodeSupported ? - new ReflectionEmitCachingMemberAccessor() : - new ReflectionMemberAccessor(); + // if dynamic code isn't supported, fallback to reflection + RuntimeFeature.IsDynamicCodeSupported ? + new ReflectionEmitCachingMemberAccessor() : + new ReflectionMemberAccessor(); #elif NETFRAMEWORK - _memberAccessorStrategy = new ReflectionEmitCachingMemberAccessor(); + new ReflectionEmitCachingMemberAccessor(); #else - _memberAccessorStrategy = new ReflectionMemberAccessor(); + new ReflectionMemberAccessor(); #endif - } - - return _memberAccessorStrategy; - } - } internal bool IsLockedInstance { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/WriteStack.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/WriteStack.cs index f1e6c02461085..d435f5a90c901 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/WriteStack.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/WriteStack.cs @@ -406,13 +406,10 @@ public string PropertyPath() static void AppendStackFrame(StringBuilder sb, ref WriteStackFrame frame) { - // Append the property name. - string? propertyName = frame.JsonPropertyInfo?.MemberName; - if (propertyName == null) - { - // Attempt to get the JSON property name from the property name specified in re-entry. - propertyName = frame.JsonPropertyNameAsString; - } + // Append the property name. Or attempt to get the JSON property name from the property name specified in re-entry. + string? propertyName = + frame.JsonPropertyInfo?.MemberName ?? + frame.JsonPropertyNameAsString; AppendPropertyName(sb, propertyName); } diff --git a/src/libraries/System.Threading.Tasks.Dataflow/src/Base/DataflowBlock.cs b/src/libraries/System.Threading.Tasks.Dataflow/src/Base/DataflowBlock.cs index 439de068d588b..fc3ea8c088ed8 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Base/DataflowBlock.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Base/DataflowBlock.cs @@ -1113,7 +1113,7 @@ private static Task ReceiveCoreByLinking(ISourceBlock if (Volatile.Read(ref target._cleanupReserved)) { IDisposable? disposableUnlink = Interlocked.CompareExchange(ref target._unlink, null, unlink); - if (disposableUnlink != null) disposableUnlink.Dispose(); + disposableUnlink?.Dispose(); } } catch (Exception exception) @@ -1283,7 +1283,7 @@ private void CleanupAndComplete(ReceiveCoreByLinkingCleanupReason reason) // Cleanup the timer. (Even if we're here because of the timer firing, we still // want to aggressively dispose of the timer.) - if (_timer != null) _timer.Dispose(); + _timer?.Dispose(); // Cancel the token everyone is listening to. We also want to unlink // from the user-provided cancellation token to prevent a leak. @@ -2537,19 +2537,16 @@ internal ObserversState(SourceObservable observable) // When the source completes, complete the target. Then when the target completes, // send completion messages to any observers still registered. Task? sourceCompletionTask = Common.GetPotentiallyNotSupportedCompletionTask(Observable._source); - if (sourceCompletionTask != null) + sourceCompletionTask?.ContinueWith((_1, state1) => { - sourceCompletionTask.ContinueWith((_1, state1) => - { - var ti = (ObserversState)state1!; - ti.Target.Complete(); - ti.Target.Completion.ContinueWith( - (_2, state2) => ((ObserversState)state2!).NotifyObserversOfCompletion(), state1, - CancellationToken.None, - Common.GetContinuationOptions(TaskContinuationOptions.NotOnFaulted | TaskContinuationOptions.ExecuteSynchronously), - TaskScheduler.Default); - }, this, Canceler.Token, Common.GetContinuationOptions(TaskContinuationOptions.ExecuteSynchronously), TaskScheduler.Default); - } + var ti = (ObserversState)state1!; + ti.Target.Complete(); + ti.Target.Completion.ContinueWith( + (_2, state2) => ((ObserversState)state2!).NotifyObserversOfCompletion(), state1, + CancellationToken.None, + Common.GetContinuationOptions(TaskContinuationOptions.NotOnFaulted | TaskContinuationOptions.ExecuteSynchronously), + TaskScheduler.Default); + }, this, Canceler.Token, Common.GetContinuationOptions(TaskContinuationOptions.ExecuteSynchronously), TaskScheduler.Default); } /// Forwards an item to all currently subscribed observers. diff --git a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/JoinBlock.cs b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/JoinBlock.cs index a56bcda831d3c..7cb8ff839eb83 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/JoinBlock.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/JoinBlock.cs @@ -795,7 +795,7 @@ internal override void CompleteOncePossible() lock (_sharedResources.IncomingLock) { _decliningPermanently = true; - if (_messages != null) _messages.Clear(); + _messages?.Clear(); } // Release any postponed messages diff --git a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/TransformBlock.cs b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/TransformBlock.cs index fb5bbe50bd3b6..bdb9c44a7469a 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/TransformBlock.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/TransformBlock.cs @@ -248,7 +248,7 @@ private void ProcessMessageWithTask(Func> transform, KeyVa } // If there's a reordering buffer, notify it that this message is done. - if (_reorderingBuffer != null) _reorderingBuffer.IgnoreItem(messageWithId.Value); + _reorderingBuffer?.IgnoreItem(messageWithId.Value); // Signal that we're done this async operation, and remove the bounding // count for the input item that didn't yield any output. 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 e222fa37f9506..a64f09a25ff31 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 @@ -3061,10 +3061,7 @@ private static ParallelLoopResult PartitionerForEachWorker( d = partitionerSource as IDisposable; } - if (d != null) - { - d.Dispose(); - } + d?.Dispose(); // ETW event for Parallel For End if (ParallelEtwProvider.Log.IsEnabled()) diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/Enlistment.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/Enlistment.cs index 71bdc979f2ffc..e19dae454de15 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/Enlistment.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/Enlistment.cs @@ -147,31 +147,13 @@ internal EnlistmentState State internal Enlistment Enlistment => _enlistment; - internal PreparingEnlistment PreparingEnlistment - { - get - { - if (_preparingEnlistment == null) - { - // If there is a race here one of the objects would simply be garbage collected. - _preparingEnlistment = new PreparingEnlistment(this); - } - return _preparingEnlistment; - } - } + internal PreparingEnlistment PreparingEnlistment => + // If there is a race here one of the objects would simply be garbage collected. + _preparingEnlistment ??= new PreparingEnlistment(this); - internal SinglePhaseEnlistment SinglePhaseEnlistment - { - get - { - if (_singlePhaseEnlistment == null) - { - // If there is a race here one of the objects would simply be garbage collected. - _singlePhaseEnlistment = new SinglePhaseEnlistment(this); - } - return _singlePhaseEnlistment; - } - } + internal SinglePhaseEnlistment SinglePhaseEnlistment => + // If there is a race here one of the objects would simply be garbage collected. + _singlePhaseEnlistment ??= new SinglePhaseEnlistment(this); internal InternalTransaction Transaction => _transaction; diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/InternalTransaction.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/InternalTransaction.cs index 6503d9ea412a9..581c9552a60a5 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/InternalTransaction.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/InternalTransaction.cs @@ -336,10 +336,7 @@ internal static void DistributedTransactionOutcome(InternalTransaction tx, Trans fo = tx._finalizedObject; } - if (null != fo) - { - fo.Dispose(); - } + fo?.Dispose(); } #region Outcome Events @@ -347,10 +344,7 @@ internal static void DistributedTransactionOutcome(InternalTransaction tx, Trans // Signal Waiters anyone waiting for transaction outcome. internal void SignalAsyncCompletion() { - if (_asyncResultEvent != null) - { - _asyncResultEvent.Set(); - } + _asyncResultEvent?.Set(); if (_asyncCallback != null) { diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionScope.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionScope.cs index e945a20a05c4b..938a4c0735beb 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionScope.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionScope.cs @@ -809,10 +809,7 @@ private void InternalDispose() } finally { - if (null != _scopeTimer) - { - _scopeTimer.Dispose(); - } + _scopeTimer?.Dispose(); if (null != _committableTransaction) { @@ -824,10 +821,7 @@ private void InternalDispose() _expectedCurrent.Dispose(); } - if (null != _dependentTransaction) - { - _dependentTransaction.Dispose(); - } + _dependentTransaction?.Dispose(); } } 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 995ea8c004e34..f6a99cb47d940 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionState.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionState.cs @@ -1393,10 +1393,7 @@ internal override void EnterState(InternalTransaction tx) } // Notify the durable enlistment - if (tx._durableEnlistment != null) - { - tx._durableEnlistment.State.InternalAborted(tx._durableEnlistment); - } + tx._durableEnlistment?.State.InternalAborted(tx._durableEnlistment); // Remove this from the timeout list TransactionTable.Remove(tx); @@ -4030,10 +4027,7 @@ internal override void EnterState(InternalTransaction tx) } // Notify the durable enlistment - if (tx._durableEnlistment != null) - { - tx._durableEnlistment.State.InternalAborted(tx._durableEnlistment); - } + tx._durableEnlistment?.State.InternalAborted(tx._durableEnlistment); // Fire Completion for anyone listening tx.FireCompletion();