Use null coalescing assignment operator in more places
authorStephen Toub <stoub@microsoft.com>
Thu, 5 Sep 2019 14:12:31 +0000 (10:12 -0400)
committerStephen Toub <stoub@microsoft.com>
Fri, 6 Sep 2019 13:09:03 +0000 (09:09 -0400)
There's currently no auto-fix for this, so the fixes were done manually.

Commit migrated from https://github.com/dotnet/coreclr/commit/208d864733c86e00499b15b310fe661a9aacc7ba

76 files changed:
src/coreclr/src/System.Private.CoreLib/Common/System/SR.cs
src/coreclr/src/System.Private.CoreLib/Tools/GenUnicodeProp/DataTable.cs
src/coreclr/src/System.Private.CoreLib/src/System/Attribute.CoreCLR.cs
src/coreclr/src/System.Private.CoreLib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs
src/coreclr/src/System.Private.CoreLib/src/System/OleAutBinder.cs
src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Associates.cs
src/coreclr/src/System.Private.CoreLib/src/System/Reflection/CustomAttribute.cs
src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/DynamicILGenerator.cs
src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/ILGenerator.cs
src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/MethodBuilder.cs
src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/SignatureHelper.cs
src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.cs
src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs
src/coreclr/src/System.Private.CoreLib/src/System/Reflection/MdFieldInfo.cs
src/coreclr/src/System.Private.CoreLib/src/System/Reflection/MethodBase.CoreCLR.cs
src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RtFieldInfo.cs
src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeAssembly.cs
src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeConstructorInfo.cs
src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeEventInfo.cs
src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeMethodInfo.cs
src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeModule.cs
src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeParameterInfo.cs
src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimePropertyInfo.cs
src/coreclr/src/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs
src/coreclr/src/System.Private.CoreLib/src/System/TypeLoadException.CoreCLR.cs
src/coreclr/src/System.Private.CoreLib/src/System/__ComObject.cs
src/libraries/System.Private.CoreLib/src/System/AggregateException.cs
src/libraries/System.Private.CoreLib/src/System/Array.cs
src/libraries/System.Private.CoreLib/src/System/BadImageFormatException.cs
src/libraries/System.Private.CoreLib/src/System/Collections/ArrayList.cs
src/libraries/System.Private.CoreLib/src/System/Collections/Generic/ArraySortHelper.cs
src/libraries/System.Private.CoreLib/src/System/Collections/Generic/Dictionary.cs
src/libraries/System.Private.CoreLib/src/System/Collections/Hashtable.cs
src/libraries/System.Private.CoreLib/src/System/CurrentSystemTimeZone.cs
src/libraries/System.Private.CoreLib/src/System/Diagnostics/Contracts/Contracts.cs
src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/ActivityTracker.cs
src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventProvider.cs
src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs
src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/FrameworkEventSource.cs
src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingTypeInfo.cs
src/libraries/System.Private.CoreLib/src/System/Exception.cs
src/libraries/System.Private.CoreLib/src/System/Globalization/CalendarData.cs
src/libraries/System.Private.CoreLib/src/System/Globalization/CultureData.Windows.cs
src/libraries/System.Private.CoreLib/src/System/Globalization/CultureData.cs
src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormatInfo.cs
src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormatInfoScanner.cs
src/libraries/System.Private.CoreLib/src/System/Globalization/GregorianCalendar.cs
src/libraries/System.Private.CoreLib/src/System/Globalization/JapaneseCalendar.cs
src/libraries/System.Private.CoreLib/src/System/Globalization/TaiwanCalendar.cs
src/libraries/System.Private.CoreLib/src/System/Globalization/TextInfo.cs
src/libraries/System.Private.CoreLib/src/System/IO/BinaryReader.cs
src/libraries/System.Private.CoreLib/src/System/IO/FileLoadException.cs
src/libraries/System.Private.CoreLib/src/System/IO/FileNotFoundException.cs
src/libraries/System.Private.CoreLib/src/System/IO/FileStreamCompletionSource.Win32.cs
src/libraries/System.Private.CoreLib/src/System/IO/Stream.cs
src/libraries/System.Private.CoreLib/src/System/IO/StreamReader.cs
src/libraries/System.Private.CoreLib/src/System/MemoryExtensions.Fast.cs
src/libraries/System.Private.CoreLib/src/System/Reflection/AssemblyName.cs
src/libraries/System.Private.CoreLib/src/System/Resources/ResourceManager.Uap.cs
src/libraries/System.Private.CoreLib/src/System/Resources/ResourceManager.cs
src/libraries/System.Private.CoreLib/src/System/Resources/RuntimeResourceSet.cs
src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/ContractHelper.cs
src/libraries/System.Private.CoreLib/src/System/Runtime/Serialization/SerializationInfo.cs
src/libraries/System.Private.CoreLib/src/System/RuntimeType.cs
src/libraries/System.Private.CoreLib/src/System/Security/SecurityElement.cs
src/libraries/System.Private.CoreLib/src/System/String.Manipulation.cs
src/libraries/System.Private.CoreLib/src/System/Text/DecoderBestFitFallback.cs
src/libraries/System.Private.CoreLib/src/System/Text/EncoderBestFitFallback.cs
src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs
src/libraries/System.Private.CoreLib/src/System/Threading/CancellationTokenSource.cs
src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs
src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs
src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskContinuation.cs
src/libraries/System.Private.CoreLib/src/System/Threading/TimerQueue.Portable.cs
src/libraries/System.Private.CoreLib/src/System/TimeZone.cs
src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.Unix.cs

index 83d1beb..da2ded7 100644 (file)
@@ -96,8 +96,8 @@ namespace System
                     string message = $"Infinite recursion during resource lookup within {System.CoreLib.Name}.  This may be a bug in {System.CoreLib.Name}, or potentially in certain extensibility points such as assembly resolve events or CultureInfo names.  Resource name: {key}";
                     Environment.FailFast(message);
                 }
-                if (_currentlyLoading == null)
-                    _currentlyLoading = new List<string>();
+
+                _currentlyLoading ??= new List<string>();
 
                 // Call class constructors preemptively, so that we cannot get into an infinite
                 // loop constructing a TypeInitializationException.  If this were omitted,
index 89fc8e1..d2bc253 100644 (file)
@@ -67,8 +67,10 @@ namespace GenUnicodeProp
             var level3RowData = new byte[level3block];
             var level2RowData = new ushort[level2block];
 
-            if (cutOff && level1Index == null)
-                level1Index = new List<byte>();
+            if (cutOff)
+            {
+                level1Index ??= new List<byte>();
+            }
 
             // Process plan 0 ~ 16.
             var ch = 0u;
index 1a475e7..d93e592 100644 (file)
@@ -84,10 +84,7 @@ namespace System
 
             // for the current property get the base class of the getter and the setter, they might be different
             // note that this only works for RuntimeMethodInfo
-            MethodInfo? propAccessor = property.GetGetMethod(true);
-
-            if (propAccessor == null)
-                propAccessor = property.GetSetMethod(true);
+            MethodInfo? propAccessor = property.GetGetMethod(true) ?? property.GetSetMethod(true);
 
             RuntimeMethodInfo? rtPropAccessor = propAccessor as RuntimeMethodInfo;
 
@@ -238,8 +235,7 @@ namespace System
             List<Type> disAllowMultiple = new List<Type>();
             object?[] objAttr;
 
-            if (type == null)
-                type = typeof(Attribute);
+            type ??= typeof(Attribute);
 
             objAttr = param.GetCustomAttributes(type, false);
 
index f493578..2399af2 100644 (file)
@@ -38,29 +38,9 @@ namespace System.Collections.ObjectModel
 
         protected IDictionary<TKey, TValue> Dictionary => m_dictionary;
 
-        public KeyCollection Keys
-        {
-            get
-            {
-                if (m_keys == null)
-                {
-                    m_keys = new KeyCollection(m_dictionary.Keys);
-                }
-                return m_keys;
-            }
-        }
+        public KeyCollection Keys => m_keys ??= new KeyCollection(m_dictionary.Keys);
 
-        public ValueCollection Values
-        {
-            get
-            {
-                if (m_values == null)
-                {
-                    m_values = new ValueCollection(m_dictionary.Values);
-                }
-                return m_values;
-            }
-        }
+        public ValueCollection Values => m_values ??= new ValueCollection(m_dictionary.Values);
 
         #region IDictionary<TKey, TValue> Members
 
index faf2985..0f40504 100644 (file)
@@ -20,8 +20,7 @@ namespace System
         public override object ChangeType(object value, Type type, CultureInfo? cultureInfo)
         {
             Variant myValue = new Variant(value);
-            if (cultureInfo == null)
-                cultureInfo = CultureInfo.CurrentCulture;
+            cultureInfo ??= CultureInfo.CurrentCulture;
 
 #if DISPLAY_DEBUG_INFO
             Console.WriteLine("In OleAutBinder::ChangeType converting variant of type: {0} to type: {1}", myValue.VariantType, type.Name);
index 92db219..485d1ab 100644 (file)
@@ -99,10 +99,7 @@ namespace System.Reflection
                 RuntimeType.GetMethodBase(reflectedType, associateMethodHandle) as RuntimeMethodInfo;
 
             // suppose a property was mapped to a method not in the derivation hierarchy of the reflectedTypeHandle
-            if (associateMethod == null)
-                associateMethod = reflectedType.Module.ResolveMethod(tkMethod, null, null) as RuntimeMethodInfo;
-
-            return associateMethod;
+            return associateMethod ?? reflectedType.Module.ResolveMethod(tkMethod, null, null) as RuntimeMethodInfo;
         }
 
         internal static void AssignAssociates(
@@ -188,8 +185,7 @@ namespace System.Reflection
                     removeOn = associateMethod;
                 else
                 {
-                    if (otherList is null)
-                        otherList = new List<MethodInfo>(cAssociates);
+                    otherList ??= new List<MethodInfo>(cAssociates);
                     otherList.Add(associateMethod);
                 }
             }
index 2157375..86ddefb 100644 (file)
@@ -1415,7 +1415,7 @@ namespace System.Reflection
 
             if (mustBeInheritable)
             {
-                attributeUsageAttribute = CustomAttribute.GetAttributeUsage(attributeType);
+                attributeUsageAttribute = GetAttributeUsage(attributeType);
 
                 if (!attributeUsageAttribute.Inherited)
                     return false;
@@ -1429,9 +1429,7 @@ namespace System.Reflection
             {
                 if (derivedAttributes[i].GetType() == attributeType)
                 {
-                    if (attributeUsageAttribute == null)
-                        attributeUsageAttribute = CustomAttribute.GetAttributeUsage(attributeType);
-
+                    attributeUsageAttribute ??= GetAttributeUsage(attributeType);
                     return attributeUsageAttribute.AllowMultiple;
                 }
             }
index d80d2d1..0a60131 100644 (file)
@@ -877,16 +877,7 @@ namespace System.Reflection.Emit
                 module, m_method.Name, (byte[])m_scope[m_methodSignature]!, new DynamicResolver(this));
         }
 
-        internal byte[] LocalSignature
-        {
-            get
-            {
-                if (m_localSignature == null)
-                    m_localSignature = SignatureHelper.GetLocalVarSigHelper().InternalGetSignatureArray();
-
-                return m_localSignature;
-            }
-        }
+        internal byte[] LocalSignature => m_localSignature ??= SignatureHelper.GetLocalVarSigHelper().InternalGetSignatureArray();
         internal byte[] Exceptions => m_exceptions;
         internal byte[] Code => m_code;
         internal int MaxStackSize => m_maxStackSize;
index 13413ff..44a14ed 100644 (file)
@@ -851,15 +851,8 @@ namespace System.Reflection.Emit
             // EndExceptionBlock
 
             // Delay init
-            if (m_exceptions == null)
-            {
-                m_exceptions = new __ExceptionInfo[DefaultExceptionArraySize];
-            }
-
-            if (m_currExcStack == null)
-            {
-                m_currExcStack = new __ExceptionInfo[DefaultExceptionArraySize];
-            }
+            m_exceptions ??= new __ExceptionInfo[DefaultExceptionArraySize];
+            m_currExcStack ??= new __ExceptionInfo[DefaultExceptionArraySize];
 
             if (m_exceptionCount >= m_exceptions.Length)
             {
@@ -1024,10 +1017,7 @@ namespace System.Reflection.Emit
             // Mark Label.
 
             // Delay init the lable array in case we dont use it
-            if (m_labelList == null)
-            {
-                m_labelList = new int[DefaultLabelArraySize];
-            }
+            m_labelList ??= new int[DefaultLabelArraySize];
 
             if (m_labelCount >= m_labelList.Length)
             {
@@ -1560,21 +1550,14 @@ namespace System.Reflection.Emit
             int endOffset)
         {
             int i = GetCurrentActiveScopeIndex();
-            if (m_localSymInfos[i] == null)
-            {
-                m_localSymInfos[i] = new LocalSymInfo();
-            }
+            m_localSymInfos[i] ??= new LocalSymInfo();
             m_localSymInfos[i]!.AddLocalSymInfo(strName, signature, slot, startOffset, endOffset); // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644)
         }
 
-        internal void AddUsingNamespaceToCurrentScope(
-            string strNamespace)
+        internal void AddUsingNamespaceToCurrentScope(string strNamespace)
         {
             int i = GetCurrentActiveScopeIndex();
-            if (m_localSymInfos[i] == null)
-            {
-                m_localSymInfos[i] = new LocalSymInfo();
-            }
+            m_localSymInfos[i] ??= new LocalSymInfo();
             m_localSymInfos[i]!.AddUsingNamespace(strNamespace); // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644)
         }
 
index 3a2d85a..08754ef 100644 (file)
@@ -305,13 +305,7 @@ namespace System.Reflection.Emit
             m_exceptions = null;
         }
 
-        internal override Type[] GetParameterTypes()
-        {
-            if (m_parameterTypes == null)
-                m_parameterTypes = Array.Empty<Type>();
-
-            return m_parameterTypes;
-        }
+        internal override Type[] GetParameterTypes() => m_parameterTypes ??= Array.Empty<Type>();
 
         internal static Type? GetMethodBaseReturnType(MethodBase? method)
         {
@@ -349,8 +343,7 @@ namespace System.Reflection.Emit
 
         internal SignatureHelper GetMethodSignature()
         {
-            if (m_parameterTypes == null)
-                m_parameterTypes = Array.Empty<Type>();
+            m_parameterTypes ??= Array.Empty<Type>();
 
             m_signature = SignatureHelper.GetMethodSigHelper(m_module, m_callingConvention, m_inst != null ? m_inst.Length : 0,
                 m_returnType, m_returnTypeRequiredCustomModifiers, m_returnTypeOptionalCustomModifiers,
@@ -779,9 +772,7 @@ namespace System.Reflection.Emit
             ThrowIfGeneric();
             ThrowIfShouldNotHaveBody();
 
-            if (m_ilGenerator == null)
-                m_ilGenerator = new ILGenerator(this);
-            return m_ilGenerator;
+            return m_ilGenerator ??= new ILGenerator(this);
         }
 
         public ILGenerator GetILGenerator(int size)
@@ -789,9 +780,7 @@ namespace System.Reflection.Emit
             ThrowIfGeneric();
             ThrowIfShouldNotHaveBody();
 
-            if (m_ilGenerator == null)
-                m_ilGenerator = new ILGenerator(this, size);
-            return m_ilGenerator;
+            return m_ilGenerator ??= new ILGenerator(this, size);
         }
 
         private void ThrowIfShouldNotHaveBody()
index 986f45e..5900d91 100644 (file)
@@ -87,8 +87,7 @@ namespace System.Reflection.Emit
             SignatureHelper sigHelp;
             MdSigCallingConvention intCall;
 
-            if (returnType == null)
-                returnType = typeof(void);
+            returnType ??= typeof(void);
 
             if (unmanagedCallConv == CallingConvention.Cdecl)
             {
index 0eb2894..39a560d 100644 (file)
@@ -697,9 +697,7 @@ namespace System.Reflection.Emit
 
         private void SetGenParamCustomAttributeNoLock(CustAttr ca)
         {
-            if (m_ca == null)
-                m_ca = new List<TypeBuilder.CustAttr>();
-
+            m_ca ??= new List<TypeBuilder.CustAttr>();
             m_ca.Add(ca);
         }
         #endregion
@@ -752,16 +750,7 @@ namespace System.Reflection.Emit
 
         public override RuntimeTypeHandle TypeHandle => throw new NotSupportedException(SR.NotSupported_DynamicModule);
 
-        public override string? FullName
-        {
-            get
-            {
-                if (m_strFullQualName == null)
-                    m_strFullQualName = TypeNameBuilder.ToString(this, TypeNameBuilder.Format.FullName);
-
-                return m_strFullQualName;
-            }
-        }
+        public override string? FullName => m_strFullQualName ??= TypeNameBuilder.ToString(this, TypeNameBuilder.Format.FullName);
 
         public override string? Namespace => m_strNameSpace;
 
@@ -1892,8 +1881,7 @@ namespace System.Reflection.Emit
             if (IsCreated())
                 return m_bakedRuntimeType;
 
-            if (m_typeInterfaces == null)
-                m_typeInterfaces = new List<Type>();
+            m_typeInterfaces ??= new List<Type>();
 
             int[] interfaceTokens = new int[m_typeInterfaces.Count];
             for (int i = 0; i < m_typeInterfaces.Count; i++)
index cd5aaf8..b0ba8bf 100644 (file)
@@ -100,15 +100,7 @@ namespace System.Reflection.Emit
         public override object InvokeMember(string name, BindingFlags invokeAttr, Binder? binder, object? target, object?[]? args, ParameterModifier[]? modifiers, CultureInfo? culture, string[]? namedParameters) { throw new NotSupportedException(); }
         public override Assembly Assembly => m_type.Assembly;
         public override RuntimeTypeHandle TypeHandle => throw new NotSupportedException();
-        public override string? FullName
-        {
-            get
-            {
-                if (m_strFullQualName == null)
-                    m_strFullQualName = TypeNameBuilder.ToString(this, TypeNameBuilder.Format.FullName);
-                return m_strFullQualName;
-            }
-        }
+        public override string? FullName => m_strFullQualName ??= TypeNameBuilder.ToString(this, TypeNameBuilder.Format.FullName);
         public override string? Namespace => m_type.Namespace;
         public override string? AssemblyQualifiedName => TypeNameBuilder.ToString(this, TypeNameBuilder.Format.AssemblyQualifiedName);
         private Type Substitute(Type[] substitutes)
index 5c501d6..16da29b 100644 (file)
@@ -40,16 +40,7 @@ namespace System.Reflection
         #endregion
 
         #region MemberInfo Overrides
-        public override string Name
-        {
-            get
-            {
-                if (m_name == null)
-                    m_name = GetRuntimeModule().MetadataImport.GetName(m_tkField).ToString();
-
-                return m_name;
-            }
-        }
+        public override string Name => m_name ??= GetRuntimeModule().MetadataImport.GetName(m_tkField).ToString();
 
         public override int MetadataToken => m_tkField;
         internal override RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); }
index 34dc255..c67016d 100644 (file)
@@ -78,8 +78,7 @@ namespace System.Reflection
 
                 if (arg == Type.Missing)
                 {
-                    if (p == null)
-                        p = GetParametersNoCopy();
+                    p ??= GetParametersNoCopy();
                     if (p[i].DefaultValue == System.DBNull.Value)
                         throw new ArgumentException(SR.Arg_VarMissNull, nameof(parameters));
                     arg = p[i].DefaultValue!;
index cad61f8..b7cae57 100644 (file)
@@ -107,16 +107,7 @@ namespace System.Reflection
         #endregion
 
         #region MemberInfo Overrides
-        public override string Name
-        {
-            get
-            {
-                if (m_name == null)
-                    m_name = RuntimeFieldHandle.GetName(this);
-
-                return m_name;
-            }
-        }
+        public override string Name => m_name ??= RuntimeFieldHandle.GetName(this);
 
         internal string FullName => DeclaringType!.FullName + "." + Name;
 
index c95ee4d..403bbac 100644 (file)
@@ -604,16 +604,10 @@ namespace System.Reflection
                                                        Version? version,
                                                        bool throwOnFileNotFound)
         {
-            AssemblyName an = new AssemblyName();
-
+            var an = new AssemblyName();
             an.SetPublicKey(GetPublicKey());
             an.Flags = GetFlags() | AssemblyNameFlags.PublicKey;
-
-            if (version == null)
-                an.Version = GetVersion();
-            else
-                an.Version = version;
-
+            an.Version = version ?? GetVersion();
             an.CultureInfo = culture;
             an.Name = GetSimpleName() + ".resources";
 
index 58dadce..48cfc0c 100644 (file)
@@ -89,21 +89,10 @@ namespace System.Reflection
         #region NonPublic Methods
         RuntimeMethodHandleInternal IRuntimeMethodInfo.Value => new RuntimeMethodHandleInternal(m_handle);
 
-        internal override bool CacheEquals(object? o)
-        {
-            return o is RuntimeConstructorInfo m && m.m_handle == m_handle;
-        }
+        internal override bool CacheEquals(object? o) =>
+            o is RuntimeConstructorInfo m && m.m_handle == m_handle;
 
-        private Signature Signature
-        {
-            get
-            {
-                if (m_signature == null)
-                    m_signature = new Signature(this, m_declaringType);
-
-                return m_signature;
-            }
-        }
+        private Signature Signature => m_signature ??= new Signature(this, m_declaringType);
 
         private RuntimeType ReflectedTypeInternal => m_reflectedTypeCache.GetRuntimeType();
 
@@ -209,13 +198,8 @@ namespace System.Reflection
         // This seems to always returns System.Void.
         internal override Type GetReturnType() { return Signature.ReturnType; }
 
-        internal override ParameterInfo[] GetParametersNoCopy()
-        {
-            if (m_parameters == null)
-                m_parameters = RuntimeParameterInfo.GetParameters(this, this, Signature);
-
-            return m_parameters;
-        }
+        internal override ParameterInfo[] GetParametersNoCopy() =>
+            m_parameters ??= RuntimeParameterInfo.GetParameters(this, this, Signature);
 
         public override ParameterInfo[] GetParameters()
         {
index fca31ce..0b24a02 100644 (file)
@@ -115,16 +115,7 @@ namespace System.Reflection
 
         #region MemberInfo Overrides
         public override MemberTypes MemberType => MemberTypes.Event;
-        public override string Name
-        {
-            get
-            {
-                if (m_name == null)
-                    m_name = new MdUtf8String(m_utf8name).ToString();
-
-                return m_name;
-            }
-        }
+        public override string Name => m_name ??= new MdUtf8String(m_utf8name).ToString();
         public override Type? DeclaringType => m_declaringType;
         public sealed override bool HasSameMetadataDefinitionAs(MemberInfo other) => HasSameMetadataDefinitionAsCore<RuntimeEventInfo>(other);
         public override Type? ReflectedType => ReflectedTypeInternal;
index 40835e0..88d94bd 100644 (file)
@@ -95,39 +95,18 @@ namespace System.Reflection
 
         private RuntimeType ReflectedTypeInternal => m_reflectedTypeCache.GetRuntimeType();
 
-        private ParameterInfo[] FetchNonReturnParameters()
-        {
-            if (m_parameters == null)
-                m_parameters = RuntimeParameterInfo.GetParameters(this, this, Signature);
-
-            return m_parameters;
-        }
-
-        private ParameterInfo FetchReturnParameter()
-        {
-            if (m_returnParameter == null)
-                m_returnParameter = RuntimeParameterInfo.GetReturnParameter(this, this, Signature);
+        private ParameterInfo[] FetchNonReturnParameters() =>
+            m_parameters ??= RuntimeParameterInfo.GetParameters(this, this, Signature);
 
-            return m_returnParameter;
-        }
+        private ParameterInfo FetchReturnParameter() =>
+            m_returnParameter ??= RuntimeParameterInfo.GetReturnParameter(this, this, Signature);
         #endregion
 
         #region Internal Members
-        internal override bool CacheEquals(object? o)
-        {
-            return o is RuntimeMethodInfo m && m.m_handle == m_handle;
-        }
-
-        internal Signature Signature
-        {
-            get
-            {
-                if (m_signature == null)
-                    m_signature = new Signature(this, m_declaringType);
+        internal override bool CacheEquals(object? o) =>
+            o is RuntimeMethodInfo m && m.m_handle == m_handle;
 
-                return m_signature;
-            }
-        }
+        internal Signature Signature => m_signature ??= new Signature(this, m_declaringType);
 
         internal BindingFlags BindingFlags => m_bindingFlags;
 
@@ -273,16 +252,7 @@ namespace System.Reflection
         #endregion
 
         #region MemberInfo Overrides
-        public override string Name
-        {
-            get
-            {
-                if (m_name == null)
-                    m_name = RuntimeMethodHandle.GetName(this);
-
-                return m_name;
-            }
-        }
+        public override string Name => m_name ??= RuntimeMethodHandle.GetName(this);
 
         public override Type? DeclaringType
         {
index affb124..0aab769 100644 (file)
@@ -365,16 +365,7 @@ namespace System.Reflection
         #endregion
 
         #region Internal Members
-        internal RuntimeType RuntimeType
-        {
-            get
-            {
-                if (m_runtimeType == null)
-                    m_runtimeType = ModuleHandle.GetModuleType(this);
-
-                return m_runtimeType;
-            }
-        }
+        internal RuntimeType RuntimeType => m_runtimeType ??= ModuleHandle.GetModuleType(this);
 
         internal bool IsTransientInternal()
         {
@@ -382,16 +373,7 @@ namespace System.Reflection
             return RuntimeModule.nIsTransientInternal(JitHelpers.GetQCallModuleOnStack(ref thisAsLocal));
         }
 
-        internal MetadataImport MetadataImport
-        {
-            get
-            {
-                unsafe
-                {
-                    return ModuleHandle.GetMetadataImport(this);
-                }
-            }
-        }
+        internal MetadataImport MetadataImport => ModuleHandle.GetMetadataImport(this);
         #endregion
 
         #region ICustomAttributeProvider Members
@@ -475,12 +457,8 @@ namespace System.Reflection
         {
             get
             {
-                unsafe
-                {
-                    Guid mvid;
-                    MetadataImport.GetScopeProps(out mvid);
-                    return mvid;
-                }
+                MetadataImport.GetScopeProps(out Guid mvid);
+                return mvid;
             }
         }
 
index 7d1662d..cf30f95 100644 (file)
@@ -87,10 +87,7 @@ namespace System.Reflection
             // Fill in empty ParameterInfos for those without tokens
             if (fetchReturnParameter)
             {
-                if (returnParameter == null)
-                {
-                    returnParameter = new RuntimeParameterInfo(sig, MetadataImport.EmptyImport, 0, -1, (ParameterAttributes)0, member);
-                }
+                returnParameter ??= new RuntimeParameterInfo(sig, MetadataImport.EmptyImport, 0, -1, (ParameterAttributes)0, member);
             }
             else
             {
index eb30ca1..44d660c 100644 (file)
@@ -173,16 +173,7 @@ namespace System.Reflection
 
         #region MemberInfo Overrides
         public override MemberTypes MemberType => MemberTypes.Property;
-        public override string Name
-        {
-            get
-            {
-                if (m_name == null)
-                    m_name = new MdUtf8String(m_utf8name).ToString();
-
-                return m_name;
-            }
-        }
+        public override string Name => m_name ??= new MdUtf8String(m_utf8name).ToString();
         public override Type? DeclaringType => m_declaringType;
 
         public sealed override bool HasSameMetadataDefinitionAs(MemberInfo other) => HasSameMetadataDefinitionAsCore<RuntimePropertyInfo>(other);
index e93bbc1..f0e433e 100644 (file)
@@ -1434,14 +1434,8 @@ namespace System
             #endregion
 
             #region Private Members
-            private string ConstructName([NotNull] ref string? name, TypeNameFormatFlags formatFlags)
-            {
-                if (name == null)
-                {
-                    name = new RuntimeTypeHandle(m_runtimeType).ConstructName(formatFlags);
-                }
-                return name;
-            }
+            private string ConstructName([NotNull] ref string? name, TypeNameFormatFlags formatFlags) =>
+                name ??= new RuntimeTypeHandle(m_runtimeType).ConstructName(formatFlags);
 
             private T[] GetMemberList<T>(ref MemberInfoCache<T>? m_cache, MemberListType listType, string? name, CacheType cacheType)
                 where T : MemberInfo
@@ -1459,8 +1453,7 @@ namespace System
                 {
                     MemberInfoCache<T> newCache = new MemberInfoCache<T>(this);
                     existingCache = Interlocked.CompareExchange(ref m_cache, newCache, null);
-                    if (existingCache == null)
-                        existingCache = newCache;
+                    existingCache ??= newCache;
                 }
 
                 return existingCache;
@@ -1581,10 +1574,7 @@ namespace System
                 return m_defaultMemberName;
             }
 
-            internal object[] GetEmptyArray()
-            {
-                return _emptyArray ?? (_emptyArray = (object[])Array.CreateInstance(m_runtimeType, 0));
-            }
+            internal object[] GetEmptyArray() => _emptyArray ??= (object[])Array.CreateInstance(m_runtimeType, 0);
             #endregion
 
             #region Caches Accessors
@@ -1749,8 +1739,7 @@ namespace System
 
             RuntimeType[]? methodInstantiation = null;
 
-            if (reflectedType == null)
-                reflectedType = declaredType as RuntimeType;
+            reflectedType ??= declaredType as RuntimeType;
 
             if (reflectedType != declaredType && !reflectedType.IsSubclassOf(declaredType))
             {
@@ -2775,9 +2764,7 @@ namespace System
                 }
             }
 
-            if (binder == null)
-                binder = DefaultBinder;
-
+            binder ??= DefaultBinder;
             return binder.SelectMethod(bindingAttr, candidates.ToArray(), types, modifiers) as MethodInfo;
         }
 
@@ -2805,9 +2792,7 @@ namespace System
             if ((bindingAttr & BindingFlags.ExactBinding) != 0)
                 return System.DefaultBinder.ExactBinding(candidates.ToArray(), types, modifiers) as ConstructorInfo;
 
-            if (binder == null)
-                binder = DefaultBinder;
-
+            binder ??= DefaultBinder;
             return binder.SelectMethod(bindingAttr, candidates.ToArray(), types, modifiers) as ConstructorInfo;
         }
 
@@ -2845,9 +2830,7 @@ namespace System
             if ((bindingAttr & BindingFlags.ExactBinding) != 0)
                 return System.DefaultBinder.ExactPropertyBinding(candidates.ToArray(), returnType, types, modifiers);
 
-            if (binder == null)
-                binder = DefaultBinder;
-
+            binder ??= DefaultBinder;
             return binder.SelectProperty(bindingAttr, candidates.ToArray(), returnType, types, modifiers);
         }
 
@@ -3243,11 +3226,7 @@ namespace System
         public override Type[] GetGenericArguments()
         {
             Type[] types = GetRootElementType().GetTypeHandleInternal().GetInstantiationPublic();
-
-            if (types == null)
-                types = Array.Empty<Type>();
-
-            return types;
+            return types ?? Array.Empty<Type>();
         }
 
         public override Type MakeGenericType(Type[] instantiation)
@@ -3332,11 +3311,7 @@ namespace System
                 throw new InvalidOperationException(SR.Arg_NotGenericParameter);
 
             Type[] constraints = new RuntimeTypeHandle(this).GetConstraints();
-
-            if (constraints == null)
-                constraints = Array.Empty<Type>();
-
-            return constraints;
+            return constraints ?? Array.Empty<Type>();
         }
         #endregion
 
@@ -3564,9 +3539,7 @@ namespace System
 
             int argCnt = (providedArgs != null) ? providedArgs.Length : 0;
 
-            if (binder == null)
-                binder = DefaultBinder;
-
+            binder ??= DefaultBinder;
             bool bDefaultBinder = (binder == DefaultBinder);
 
             // Delegate to Activator.CreateInstance
@@ -3826,15 +3799,9 @@ namespace System
                     return finalist.Invoke(target, bindingFlags, binder, providedArgs, culture);
                 }
 
-                if (finalists == null)
-                    finalists = new MethodInfo[] { finalist };
-
-                if (providedArgs == null)
-                    providedArgs = Array.Empty<object>();
-
+                finalists ??= new MethodInfo[] { finalist };
+                providedArgs ??= Array.Empty<object>();
                 object? state = null;
-
-
                 MethodBase? invokeMethod = null;
 
                 try { invokeMethod = binder.BindToMethod(bindingFlags, finalists, ref providedArgs!, modifiers, culture, namedParams, out state); }
@@ -3897,12 +3864,10 @@ namespace System
 
             object server;
 
-            if (args is null)
-                args = Array.Empty<object>();
+            args ??= Array.Empty<object>();
 
             // Without a binder we need to do use the default binder...
-            if (binder is null)
-                binder = DefaultBinder;
+            binder ??= DefaultBinder;
 
             // deal with the __COMObject case first. It is very special because from a reflection point of view it has no ctors
             // so a call to GetMemberCons would fail
@@ -4003,7 +3968,7 @@ namespace System
                     _ctorAttributes = RuntimeMethodHandle.GetAttributes(_hCtorMethodHandle);
 
                     // The default ctor path is optimized for reference types only
-                    ConstructorInfo delegateCtorInfo = s_delegateCtorInfo ?? (s_delegateCtorInfo = typeof(CtorDelegate).GetConstructor(new Type[] { typeof(object), typeof(IntPtr) })!);
+                    ConstructorInfo delegateCtorInfo = s_delegateCtorInfo ??= typeof(CtorDelegate).GetConstructor(new Type[] { typeof(object), typeof(IntPtr) })!;
 
                     // No synchronization needed here. In the worst case we create extra garbage
                     _ctor = (CtorDelegate)delegateCtorInfo.Invoke(new object?[] { null, RuntimeMethodHandle.GetFunctionPointer(_hCtorMethodHandle) });
@@ -4297,10 +4262,7 @@ namespace System
         }
 
         private static OleAutBinder? s_ForwardCallBinder;
-        private OleAutBinder ForwardCallBinder
-        {
-            get => s_ForwardCallBinder ?? (s_ForwardCallBinder = new OleAutBinder());
-        }
+        private OleAutBinder ForwardCallBinder => s_ForwardCallBinder ??= new OleAutBinder();
 
         [Flags]
         private enum DispatchWrapperType : int
index 3982628..4b6ffc5 100644 (file)
@@ -32,13 +32,13 @@ namespace System
             if (_message == null)
             {
                 if (_className == null && _resourceId == 0)
+                {
                     _message = SR.Arg_TypeLoadException;
+                }
                 else
                 {
-                    if (_assemblyName == null)
-                        _assemblyName = SR.IO_UnknownFileName;
-                    if (_className == null)
-                        _className = SR.IO_UnknownFileName;
+                    _assemblyName ??= SR.IO_UnknownFileName;
+                    _className ??= SR.IO_UnknownFileName;
 
                     string? format = null;
                     GetTypeLoadExceptionMessage(_resourceId, JitHelpers.GetStringHandleOnStack(ref format));
index 26de7bf..d49e228 100644 (file)
@@ -77,10 +77,7 @@ namespace System
             lock (this)
             {
                 // If the map hasn't been allocated yet, allocate it.
-                if (m_ObjectToDataMap == null)
-                {
-                    m_ObjectToDataMap = new Hashtable();
-                }
+                m_ObjectToDataMap ??= new Hashtable();
 
                 // If there isn't already data in the map then add it.
                 if (m_ObjectToDataMap[key] == null)
index e24ad19..3486a4f 100644 (file)
@@ -339,11 +339,7 @@ namespace System
                 // exceptions (to be rethrown later) and add it.
                 if (!predicate(m_innerExceptions[i]))
                 {
-                    if (unhandledExceptions == null)
-                    {
-                        unhandledExceptions = new List<Exception>();
-                    }
-
+                    unhandledExceptions ??= new List<Exception>();
                     unhandledExceptions.Add(m_innerExceptions[i]);
                 }
             }
index d2b9aca..606cf89 100644 (file)
@@ -477,7 +477,7 @@ namespace System
             if (array.Rank != 1)
                 ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported);
 
-            if (comparer == null) comparer = Comparer.Default;
+            comparer ??= Comparer.Default;
 #if CORECLR
             if (comparer == Comparer.Default)
             {
index f9072e9..e3edaeb 100644 (file)
@@ -107,8 +107,7 @@ namespace System
 
             if (_fusionLog != null)
             {
-                if (s == null)
-                    s = " ";
+                s ??= " ";
                 s += Environment.NewLine;
                 s += Environment.NewLine;
                 s += _fusionLog;
index 71965b3..7607145 100644 (file)
@@ -811,8 +811,7 @@ namespace System.Collections
                 if (Count - index < count)
                     throw new ArgumentException(SR.Argument_InvalidOffLen);
 
-                if (comparer == null)
-                    comparer = Comparer.Default;
+                comparer ??= Comparer.Default;
 
                 int lo = index;
                 int hi = index + count - 1;
index 4234a3a..888b976 100644 (file)
@@ -58,11 +58,7 @@ namespace System.Collections.Generic
             // underlying IComparables, etc) that are bogus.
             try
             {
-                if (comparer == null)
-                {
-                    comparer = Comparer<T>.Default;
-                }
-
+                comparer ??= Comparer<T>.Default;
                 IntrospectiveSort(keys, index, length, comparer.Compare);
             }
             catch (IndexOutOfRangeException)
@@ -79,11 +75,7 @@ namespace System.Collections.Generic
         {
             try
             {
-                if (comparer == null)
-                {
-                    comparer = Comparer<T>.Default;
-                }
-
+                comparer ??= Comparer<T>.Default;
                 return InternalBinarySearch(array, index, length, value, comparer);
             }
             catch (Exception e)
index 7253577..8a19f04 100644 (file)
@@ -152,59 +152,17 @@ namespace System.Collections.Generic
 
         public int Count => _count - _freeCount;
 
-        public KeyCollection Keys
-        {
-            get
-            {
-                if (_keys == null) _keys = new KeyCollection(this);
-                return _keys;
-            }
-        }
+        public KeyCollection Keys => _keys ??= new KeyCollection(this);
 
-        ICollection<TKey> IDictionary<TKey, TValue>.Keys
-        {
-            get
-            {
-                if (_keys == null) _keys = new KeyCollection(this);
-                return _keys;
-            }
-        }
+        ICollection<TKey> IDictionary<TKey, TValue>.Keys => _keys ??= new KeyCollection(this);
 
-        IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys
-        {
-            get
-            {
-                if (_keys == null) _keys = new KeyCollection(this);
-                return _keys;
-            }
-        }
+        IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys => _keys ??= new KeyCollection(this);
 
-        public ValueCollection Values
-        {
-            get
-            {
-                if (_values == null) _values = new ValueCollection(this);
-                return _values;
-            }
-        }
+        public ValueCollection Values => _values ??= new ValueCollection(this);
 
-        ICollection<TValue> IDictionary<TKey, TValue>.Values
-        {
-            get
-            {
-                if (_values == null) _values = new ValueCollection(this);
-                return _values;
-            }
-        }
+        ICollection<TValue> IDictionary<TKey, TValue>.Values => _values ??= new ValueCollection(this);
 
-        IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values
-        {
-            get
-            {
-                if (_values == null) _values = new ValueCollection(this);
-                return _values;
-            }
-        }
+        IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values => _values ??= new ValueCollection(this);
 
         public TValue this[TKey key]
         {
index 119d768..6314f5f 100644 (file)
@@ -830,15 +830,7 @@ namespace System.Collections
         // to the hash table are reflected in this collection.  It is not
         // a static copy of all the keys in the hash table.
         //
-        public virtual ICollection Keys
-        {
-            get
-            {
-                if (_keys == null)
-                    _keys = new KeyCollection(this);
-                return _keys;
-            }
-        }
+        public virtual ICollection Keys => _keys ??= new KeyCollection(this);
 
         // Returns a collection representing the values of this hashtable. The
         // order in which the returned collection represents the values is
@@ -850,15 +842,7 @@ namespace System.Collections
         // to the hash table are reflected in this collection.  It is not
         // a static copy of all the keys in the hash table.
         //
-        public virtual ICollection Values
-        {
-            get
-            {
-                if (_values == null)
-                    _values = new ValueCollection(this);
-                return _values;
-            }
-        }
+        public virtual ICollection Values => _values ??= new ValueCollection(this);
 
         // Inserts an entry into this hashtable. This method is called from the Set
         // and Add methods. If the add parameter is true and the given key already
index 2df6333..01a9493 100644 (file)
@@ -136,14 +136,12 @@ namespace System
 
         private static DaylightTime CreateDaylightChanges(int year)
         {
-            DaylightTime? currentDaylightChanges = null;
+            DateTime start = DateTime.MinValue;
+            DateTime end = DateTime.MinValue;
+            TimeSpan delta = TimeSpan.Zero;
 
             if (TimeZoneInfo.Local.SupportsDaylightSavingTime)
             {
-                DateTime start;
-                DateTime end;
-                TimeSpan delta;
-
                 foreach (TimeZoneInfo.AdjustmentRule rule in TimeZoneInfo.Local.GetAdjustmentRules())
                 {
                     if (rule.DateStart.Year <= year && rule.DateEnd.Year >= year && rule.DaylightDelta != TimeSpan.Zero)
@@ -151,19 +149,12 @@ namespace System
                         start = TimeZoneInfo.TransitionTimeToDateTime(year, rule.DaylightTransitionStart);
                         end = TimeZoneInfo.TransitionTimeToDateTime(year, rule.DaylightTransitionEnd);
                         delta = rule.DaylightDelta;
-
-                        currentDaylightChanges = new DaylightTime(start, end, delta);
                         break;
                     }
                 }
             }
 
-            if (currentDaylightChanges == null)
-            {
-                currentDaylightChanges = new DaylightTime(DateTime.MinValue, DateTime.MinValue, TimeSpan.Zero);
-            }
-
-            return currentDaylightChanges;
+            return new DaylightTime(start, end, delta);
         }
 
         public override TimeSpan GetUtcOffset(DateTime time)
index c424fc1..6b9707f 100644 (file)
@@ -640,8 +640,7 @@ namespace System.Diagnostics.Contracts
                 }
             }
 
-            if (probablyNotRewritten == null)
-                probablyNotRewritten = thisAssembly;
+            probablyNotRewritten ??= thisAssembly;
             string? simpleName = probablyNotRewritten.GetName().Name;
             ContractHelper.TriggerFailure(kind, SR.Format(SR.MustUseCCRewrite, contractKind, simpleName), null, null, null);
         }
index 0f47691..00e080d 100644 (file)
@@ -184,8 +184,7 @@ namespace System.Diagnostics.Tracing
                     if (orphan.CanBeOrphan())
                     {
                         // We can't pop anything after we see a valid orphan, remember this for later when we update m_current.
-                        if (newCurrentActivity == null)
-                            newCurrentActivity = orphan;
+                        newCurrentActivity ??= orphan;
                     }
                     else
                     {
@@ -201,8 +200,7 @@ namespace System.Diagnostics.Tracing
                     // I succeeded stopping this activity. Now we update our m_current pointer
 
                     // If I haven't yet determined the new current activity, it is my creator.
-                    if (newCurrentActivity == null)
-                        newCurrentActivity = activityToStop.m_creator;
+                    newCurrentActivity ??= activityToStop.m_creator;
 
                     m_current.Value = newCurrentActivity;
 
index 41d6198..a805605 100644 (file)
@@ -434,8 +434,7 @@ namespace System.Diagnostics.Tracing
             if (val > 1)
                 return;
 
-            if (sessionList == null)
-                sessionList = new List<SessionInfo>(8);
+            sessionList ??= new List<SessionInfo>(8);
 
             if (val == 1)
             {
index cfd2173..c8e718c 100644 (file)
@@ -842,7 +842,7 @@ namespace System.Diagnostics.Tracing
         {
             if (m_eventSourceEnabled)
             {
-                if (arg1 == null) arg1 = "";
+                arg1 ??= "";
                 fixed (char* string1Bytes = arg1)
                 {
                     EventSource.EventData* descrs = stackalloc EventSource.EventData[1];
@@ -858,8 +858,8 @@ namespace System.Diagnostics.Tracing
         {
             if (m_eventSourceEnabled)
             {
-                if (arg1 == null) arg1 = "";
-                if (arg2 == null) arg2 = "";
+                arg1 ??= "";
+                arg2 ??= "";
                 fixed (char* string1Bytes = arg1)
                 fixed (char* string2Bytes = arg2)
                 {
@@ -879,9 +879,9 @@ namespace System.Diagnostics.Tracing
         {
             if (m_eventSourceEnabled)
             {
-                if (arg1 == null) arg1 = "";
-                if (arg2 == null) arg2 = "";
-                if (arg3 == null) arg3 = "";
+                arg1 ??= "";
+                arg2 ??= "";
+                arg3 ??= "";
                 fixed (char* string1Bytes = arg1)
                 fixed (char* string2Bytes = arg2)
                 fixed (char* string3Bytes = arg3)
@@ -906,7 +906,7 @@ namespace System.Diagnostics.Tracing
         {
             if (m_eventSourceEnabled)
             {
-                if (arg1 == null) arg1 = "";
+                arg1 ??= "";
                 fixed (char* string1Bytes = arg1)
                 {
                     EventSource.EventData* descrs = stackalloc EventSource.EventData[2];
@@ -925,7 +925,7 @@ namespace System.Diagnostics.Tracing
         {
             if (m_eventSourceEnabled)
             {
-                if (arg1 == null) arg1 = "";
+                arg1 ??= "";
                 fixed (char* string1Bytes = arg1)
                 {
                     EventSource.EventData* descrs = stackalloc EventSource.EventData[3];
@@ -948,7 +948,7 @@ namespace System.Diagnostics.Tracing
         {
             if (m_eventSourceEnabled)
             {
-                if (arg1 == null) arg1 = "";
+                arg1 ??= "";
                 fixed (char* string1Bytes = arg1)
                 {
                     EventSource.EventData* descrs = stackalloc EventSource.EventData[2];
@@ -968,7 +968,7 @@ namespace System.Diagnostics.Tracing
         {
             if (m_eventSourceEnabled)
             {
-                if (arg2 == null) arg2 = "";
+                arg2 ??= "";
                 fixed (char* string2Bytes = arg2)
                 {
                     EventSource.EventData* descrs = stackalloc EventSource.EventData[2];
@@ -988,7 +988,7 @@ namespace System.Diagnostics.Tracing
         {
             if (m_eventSourceEnabled)
             {
-                if (arg2 == null) arg2 = "";
+                arg2 ??= "";
                 fixed (char* string2Bytes = arg2)
                 {
                     EventSource.EventData* descrs = stackalloc EventSource.EventData[2];
@@ -1143,7 +1143,7 @@ namespace System.Diagnostics.Tracing
         ///    {
         ///        if (IsEnabled())
         ///        {
-        ///            if (arg2 == null) arg2 = "";
+        ///            arg2 ??= "";
         ///            fixed (char* string2Bytes = arg2)
         ///            {
         ///                EventSource.EventData* descrs = stackalloc EventSource.EventData[2];
@@ -1176,7 +1176,7 @@ namespace System.Diagnostics.Tracing
         ///    {
         ///        if (IsEnabled())
         ///        {
-        ///            if (arg2 == null) arg2 = "";
+        ///            arg2 ??= "";
         ///            fixed (char* string2Bytes = arg2)
         ///            {
         ///                EventSource.EventData* descrs = stackalloc EventSource.EventData[2];
@@ -1505,8 +1505,7 @@ namespace System.Diagnostics.Tracing
             }
             catch (Exception e)
             {
-                if (m_constructionException == null)
-                    m_constructionException = e;
+                m_constructionException ??= e;
                 ReportOutOfBandMessage("ERROR: Exception during construction of EventSource " + Name + ": " + e.Message, true);
             }
 
@@ -1555,10 +1554,7 @@ namespace System.Diagnostics.Tracing
             /// </summary>
             public void Start()
             {
-                if (this.w == null)
-                {
-                    this.w = new uint[85];
-                }
+                this.w ??= new uint[85];
 
                 this.length = 0;
                 this.pos = 0;
@@ -2635,7 +2631,9 @@ namespace System.Diagnostics.Tracing
                 {
                     // We can't do the command, simply remember it and we do it when we are fully constructed.
                     if (m_deferredCommands == null)
+                    {
                         m_deferredCommands = commandArgs;       // create the first entry
+                    }
                     else
                     {
                         // We have one or more entries, find the last one and add it to that.
@@ -2683,8 +2681,7 @@ namespace System.Diagnostics.Tracing
                     throw new ArgumentException(SR.EventSource_ListenerNotFound);
                 }
 
-                if (commandArgs.Arguments == null)
-                    commandArgs.Arguments = new Dictionary<string, string?>();
+                commandArgs.Arguments ??= new Dictionary<string, string?>();
 
                 if (commandArgs.Command == EventCommand.Update)
                 {
@@ -2921,8 +2918,7 @@ namespace System.Diagnostics.Tracing
                 EventDispatcher? dispatcher = m_Dispatchers;
                 while (dispatcher != null)
                 {
-                    if (dispatcher.m_EventEnabled == null)
-                        dispatcher.m_EventEnabled = new bool[m_eventData.Length];
+                    dispatcher.m_EventEnabled ??= new bool[m_eventData.Length];
                     dispatcher = dispatcher.m_Next;
                 }
 #if FEATURE_PERFTRACING
@@ -3660,8 +3656,7 @@ namespace System.Diagnostics.Tracing
             //     throw new WarningException(SR.EventSource_EventNameDoesNotEqualTaskPlusOpcode);
             // }
 
-            if (eventsByName == null)
-                eventsByName = new Dictionary<string, string>();
+            eventsByName ??= new Dictionary<string, string>();
 
             if (eventsByName.ContainsKey(evtName))
             {
@@ -4237,8 +4232,7 @@ namespace System.Diagnostics.Tracing
         {
             lock (EventListenersLock)
             {
-                if (s_EventSources == null)
-                    s_EventSources = new List<WeakReference>(2);
+                s_EventSources ??= new List<WeakReference>(2);
 
                 if (!s_EventSourceShutdownRegistered)
                 {
@@ -5354,8 +5348,10 @@ namespace System.Diagnostics.Tracing
                     ManifestError(SR.Format(SR.EventSource_OpcodeCollision, name, prevName, value));
                 }
             }
+
             opcodeTab[value] = name;
         }
+
         public void AddTask(string name, int value)
         {
             if ((flags & EventManifestOptions.Strict) != 0)
@@ -5370,10 +5366,11 @@ namespace System.Diagnostics.Tracing
                     ManifestError(SR.Format(SR.EventSource_TaskCollision, name, prevName, value));
                 }
             }
-            if (taskTab == null)
-                taskTab = new Dictionary<int, string>();
+
+            taskTab ??= new Dictionary<int, string>();
             taskTab[value] = name;
         }
+
         public void AddKeyword(string name, ulong value)
         {
             if ((value & (value - 1)) != 0)   // Is it a power of 2?
@@ -5392,8 +5389,8 @@ namespace System.Diagnostics.Tracing
                     ManifestError(SR.Format(SR.EventSource_KeywordCollision, name, prevName, "0x" + value.ToString("x", CultureInfo.CurrentCulture)));
                 }
             }
-            if (keywordTab == null)
-                keywordTab = new Dictionary<ulong, string>();
+
+            keywordTab ??= new Dictionary<ulong, string>();
             keywordTab[value] = name;
         }
 
@@ -5419,8 +5416,7 @@ namespace System.Diagnostics.Tracing
 
             ulong kwd = GetChannelKeyword(chValue);
 
-            if (channelTab == null)
-                channelTab = new Dictionary<int, ChannelInfo>(4);
+            channelTab ??= new Dictionary<int, ChannelInfo>(4);
             channelTab[value] = new ChannelInfo { Name = name, Keywords = kwd, Attribs = channelAttribute };
         }
 
@@ -5509,8 +5505,7 @@ namespace System.Diagnostics.Tracing
             {
                 // mark this index as "extraneous" (it has no parallel in the managed signature)
                 // we use these values in TranslateToManifestConvention()
-                if (byteArrArgIndices == null)
-                    byteArrArgIndices = new List<int>(4);
+                byteArrArgIndices ??= new List<int>(4);
                 byteArrArgIndices.Add(numParams);
 
                 // add an extra field to the template representing the length of the binary blob
@@ -5530,8 +5525,7 @@ namespace System.Diagnostics.Tracing
             if (type.IsEnum() && Enum.GetUnderlyingType(type) != typeof(ulong) && Enum.GetUnderlyingType(type) != typeof(long))
             {
                 templates.Append(" map=\"").Append(type.Name).Append("\"");
-                if (mapsTab == null)
-                    mapsTab = new Dictionary<string, Type>();
+                mapsTab ??= new Dictionary<string, Type>();
                 if (!mapsTab.ContainsKey(type.Name))
                     mapsTab.Add(type.Name, type);        // Remember that we need to dump the type enumeration
             }
@@ -5580,10 +5574,7 @@ namespace System.Diagnostics.Tracing
         {
             // strip off any non-channel keywords, since we are only interested in channels here.
             channelKeyword &= ValidPredefinedChannelKeywords;
-            if (channelTab == null)
-            {
-                channelTab = new Dictionary<int, ChannelInfo>(4);
-            }
+            channelTab ??= new Dictionary<int, ChannelInfo>(4);
 
             if (channelTab.Count == MaxCountChannels)
                 ManifestError(SR.EventSource_MaxChannelExceeded);
@@ -5671,8 +5662,8 @@ namespace System.Diagnostics.Tracing
                         access = attribs.Access;
 #endif
                     }
-                    if (fullName == null)
-                        fullName = providerName + "/" + channelInfo.Name;
+
+                    fullName ??= providerName + "/" + channelInfo.Name;
 
                     sb.Append("  <").Append(elementName);
                     sb.Append(" chid=\"").Append(channelInfo.Name).Append("\"");
@@ -5923,8 +5914,7 @@ namespace System.Diagnostics.Tracing
 
                 // allow channels to be auto-defined.  The well known ones get their well known names, and the
                 // rest get names Channel<N>.  This allows users to modify the Manifest if they want more advanced features.
-                if (channelTab == null)
-                    channelTab = new Dictionary<int, ChannelInfo>(4);
+                channelTab ??= new Dictionary<int, ChannelInfo>(4);
 
                 string channelName = channel.ToString();        // For well know channels this is a nice name, otherwise a number
                 if (EventChannel.Debug < channel)
@@ -5935,8 +5925,8 @@ namespace System.Diagnostics.Tracing
                     ManifestError(SR.Format(SR.EventSource_UndefinedChannel, channel, eventName));
             }
             // events that specify admin channels *must* have non-null "Message" attributes
-            if (resources != null && eventMessage == null)
-                eventMessage = resources.GetString("event_" + eventName, CultureInfo.InvariantCulture);
+            if (resources != null)
+                eventMessage ??= resources.GetString("event_" + eventName, CultureInfo.InvariantCulture);
 
             Debug.Assert(info!.Attribs != null);
             if (info.Attribs.EventChannelType == EventChannelType.Admin && eventMessage == null)
@@ -5950,8 +5940,7 @@ namespace System.Diagnostics.Tracing
                 return "";
 
             string? ret;
-            if (taskTab == null)
-                taskTab = new Dictionary<int, string>();
+            taskTab ??= new Dictionary<int, string>();
             if (!taskTab.TryGetValue((int)task, out ret))
                 ret = taskTab[(int)task] = eventName;
             return ret;
@@ -6082,8 +6071,7 @@ namespace System.Diagnostics.Tracing
 
         private static void UpdateStringBuilder([NotNull] ref StringBuilder? stringBuilder, string eventMessage, int startIndex, int count)
         {
-            if (stringBuilder == null)
-                stringBuilder = new StringBuilder();
+            stringBuilder ??= new StringBuilder();
             stringBuilder.Append(eventMessage, startIndex, count);
         }
 
index 3ef69b0..321ae81 100644 (file)
@@ -37,7 +37,7 @@ namespace System.Diagnostics.Tracing
         {
             if (IsEnabled())
             {
-                if (arg3 == null) arg3 = "";
+                arg3 ??= "";
                 fixed (char* string3Bytes = arg3)
                 {
                     EventSource.EventData* descrs = stackalloc EventSource.EventData[6];
@@ -70,7 +70,7 @@ namespace System.Diagnostics.Tracing
         {
             if (IsEnabled())
             {
-                if (arg3 == null) arg3 = "";
+                arg3 ??= "";
                 fixed (char* string3Bytes = arg3)
                 {
                     EventSource.EventData* descrs = stackalloc EventSource.EventData[3];
index a34675f..a5de123 100644 (file)
@@ -162,13 +162,12 @@ namespace System.Diagnostics.Tracing
 
         public static TraceLoggingTypeInfo GetInstance(Type type, List<Type>? recursionCheck)
         {
-            Dictionary<Type, TraceLoggingTypeInfo> cache = threadCache ?? (threadCache = new Dictionary<Type, TraceLoggingTypeInfo>());
+            Dictionary<Type, TraceLoggingTypeInfo> cache = threadCache ??= new Dictionary<Type, TraceLoggingTypeInfo>();
 
             TraceLoggingTypeInfo? instance;
             if (!cache.TryGetValue(type, out instance))
             {
-                if (recursionCheck == null)
-                    recursionCheck = new List<Type>();
+                recursionCheck ??= new List<Type>();
                 int recursionCheckCount = recursionCheck.Count;
                 instance = Statics.CreateDefaultTypeInfo(type, recursionCheck);
                 cache[type] = instance;
index 0fe895c..5e4f078 100644 (file)
@@ -87,7 +87,7 @@ namespace System
 
         public virtual string? Source
         {
-            get => _source ?? (_source = CreateSourceName());
+            get => _source ??= CreateSourceName();
             set => _source = value;
         }
 
index 88e47ba..997cfb4 100644 (file)
@@ -112,23 +112,23 @@ namespace System.Globalization
 
                 // Something failed, try invariant for missing parts
                 // This is really not good, but we don't want the callers to crash.
-                if (this.sNativeName == null) this.sNativeName = string.Empty;           // Calendar Name for the locale.
+                this.sNativeName ??= string.Empty;           // Calendar Name for the locale.
 
                 // Formats
-                if (this.saShortDates == null) this.saShortDates = Invariant.saShortDates; // Short Data format, default first
-                if (this.saYearMonths == null) this.saYearMonths = Invariant.saYearMonths; // Year/Month Data format, default first
-                if (this.saLongDates == null) this.saLongDates = Invariant.saLongDates;  // Long Data format, default first
-                if (this.sMonthDay == null) this.sMonthDay = Invariant.sMonthDay;    // Month/Day format
+                this.saShortDates ??= Invariant.saShortDates; // Short Data format, default first
+                this.saYearMonths ??= Invariant.saYearMonths; // Year/Month Data format, default first
+                this.saLongDates ??= Invariant.saLongDates;  // Long Data format, default first
+                this.sMonthDay ??= Invariant.sMonthDay;    // Month/Day format
 
                 // Calendar Parts Names
-                if (this.saEraNames == null) this.saEraNames = Invariant.saEraNames;              // Names of Eras
-                if (this.saAbbrevEraNames == null) this.saAbbrevEraNames = Invariant.saAbbrevEraNames;        // Abbreviated Era Names
-                if (this.saAbbrevEnglishEraNames == null) this.saAbbrevEnglishEraNames = Invariant.saAbbrevEnglishEraNames; // Abbreviated Era Names in English
-                if (this.saDayNames == null) this.saDayNames = Invariant.saDayNames;              // Day Names, null to use locale data, starts on Sunday
-                if (this.saAbbrevDayNames == null) this.saAbbrevDayNames = Invariant.saAbbrevDayNames;        // Abbrev Day Names, null to use locale data, starts on Sunday
-                if (this.saSuperShortDayNames == null) this.saSuperShortDayNames = Invariant.saSuperShortDayNames;    // Super short Day of week names
-                if (this.saMonthNames == null) this.saMonthNames = Invariant.saMonthNames;            // Month Names (13)
-                if (this.saAbbrevMonthNames == null) this.saAbbrevMonthNames = Invariant.saAbbrevMonthNames;      // Abbrev Month Names (13)
+                this.saEraNames ??= Invariant.saEraNames;              // Names of Eras
+                this.saAbbrevEraNames ??= Invariant.saAbbrevEraNames;        // Abbreviated Era Names
+                this.saAbbrevEnglishEraNames ??= Invariant.saAbbrevEnglishEraNames; // Abbreviated Era Names in English
+                this.saDayNames ??= Invariant.saDayNames;              // Day Names, null to use locale data, starts on Sunday
+                this.saAbbrevDayNames ??= Invariant.saAbbrevDayNames;        // Abbrev Day Names, null to use locale data, starts on Sunday
+                this.saSuperShortDayNames ??= Invariant.saSuperShortDayNames;    // Super short Day of week names
+                this.saMonthNames ??= Invariant.saMonthNames;            // Month Names (13)
+                this.saAbbrevMonthNames ??= Invariant.saAbbrevMonthNames;      // Abbrev Month Names (13)
                 // Genitive and Leap names can follow the fallback below
             }
 
index b8cb91b..6c1902c 100644 (file)
@@ -379,8 +379,7 @@ namespace System.Globalization
                         {
                             // Found another ', so we have ''.  Need to add \' instead.
                             // 1st make sure we have our stringbuilder
-                            if (result == null)
-                                result = new StringBuilder(str, 0, i, str.Length * 2);
+                            result ??= new StringBuilder(str, 0, i, str.Length * 2);
 
                             // Append a \' and keep going (so we don't turn off quote mode)
                             result.Append("\\'");
@@ -402,8 +401,7 @@ namespace System.Globalization
                 {
                     // Found a \, need to change it to \\
                     // 1st make sure we have our stringbuilder
-                    if (result == null)
-                        result = new StringBuilder(str, 0, i, str.Length * 2);
+                    result ??= new StringBuilder(str, 0, i, str.Length * 2);
 
                     // Append our \\ to the string & continue
                     result.Append("\\\\");
@@ -411,8 +409,7 @@ namespace System.Globalization
                 }
 
                 // If we have a builder we need to add our character
-                if (result != null)
-                    result.Append(str[i]);
+                result?.Append(str[i]);
             }
 
             // Unchanged string? , just return input string
index 7963d84..de6f326 100644 (file)
@@ -1880,10 +1880,7 @@ namespace System.Globalization
             int calendarIndex = (int)calendarId - 1;
 
             // Have to have calendars
-            if (_calendars == null)
-            {
-                _calendars = new CalendarData[CalendarData.MAX_CALENDARS];
-            }
+            _calendars ??= new CalendarData[CalendarData.MAX_CALENDARS];
 
             // we need the following local variable to avoid returning null
             // when another thread creates a new array of CalendarData (above)
@@ -2157,16 +2154,10 @@ namespace System.Globalization
                 switch (str[i])
                 {
                     case '\'':
-                        if (result == null)
-                        {
-                            result = new StringBuilder(str, start, i - start, str.Length);
-                        }
+                        result ??= new StringBuilder(str, start, i - start, str.Length);
                         break;
                     case '\\':
-                        if (result == null)
-                        {
-                            result = new StringBuilder(str, start, i - start, str.Length);
-                        }
+                        result ??= new StringBuilder(str, start, i - start, str.Length);
                         ++i;
                         if (i < str.Length)
                         {
@@ -2174,10 +2165,7 @@ namespace System.Globalization
                         }
                         break;
                     default:
-                        if (result != null)
-                        {
-                            result.Append(str[i]);
-                        }
+                        result?.Append(str[i]);
                         break;
                 }
             }
index 430b1bf..3330264 100644 (file)
@@ -150,31 +150,11 @@ namespace System.Globalization
 
         private DateTimeFormatFlags formatFlags = DateTimeFormatFlags.NotInitialized;
 
-        private string CultureName => _name ?? (_name = _cultureData.CultureName);
+        private string CultureName => _name ??= _cultureData.CultureName;
 
-        private CultureInfo Culture
-        {
-            get
-            {
-                if (_cultureInfo == null)
-                {
-                    _cultureInfo = CultureInfo.GetCultureInfo(CultureName);
-                }
-                return _cultureInfo;
-            }
-        }
+        private CultureInfo Culture => _cultureInfo ??= CultureInfo.GetCultureInfo(CultureName);
 
-        private string LanguageName
-        {
-            get
-            {
-                if (_langName == null)
-                {
-                    _langName = _cultureData.TwoLetterISOLanguageName;
-                }
-                return _langName;
-            }
-        }
+        private string LanguageName => _langName ??= _cultureData.TwoLetterISOLanguageName;
 
         /// <summary>
         /// Create an array of string which contains the abbreviated day names.
@@ -1898,62 +1878,25 @@ namespace System.Globalization
 
         // Decimal separator used by positive TimeSpan pattern
         private string? _decimalSeparator;
-        internal string DecimalSeparator
-        {
-            get
-            {
-                if (_decimalSeparator == null)
-                {
-                    CultureData? cultureDataWithoutUserOverrides = _cultureData.UseUserOverride ?
-                        CultureData.GetCultureData(_cultureData.CultureName, false) :
-                        _cultureData;
-                    _decimalSeparator = new NumberFormatInfo(cultureDataWithoutUserOverrides).NumberDecimalSeparator;
-                }
-                return _decimalSeparator;
-            }
-        }
+        internal string DecimalSeparator =>
+            _decimalSeparator ??=
+            new NumberFormatInfo(_cultureData.UseUserOverride ? CultureData.GetCultureData(_cultureData.CultureName, false) : _cultureData).NumberDecimalSeparator;
 
         // Positive TimeSpan Pattern
         private string? _fullTimeSpanPositivePattern;
-        internal string FullTimeSpanPositivePattern
-        {
-            get
-            {
-                if (_fullTimeSpanPositivePattern == null)
-                {
-                    _fullTimeSpanPositivePattern = "d':'h':'mm':'ss'" + DecimalSeparator + "'FFFFFFF";
-                }
-                return _fullTimeSpanPositivePattern;
-            }
-        }
+        internal string FullTimeSpanPositivePattern =>
+            _fullTimeSpanPositivePattern ??= "d':'h':'mm':'ss'" + DecimalSeparator + "'FFFFFFF";
 
         // Negative TimeSpan Pattern
         private string? _fullTimeSpanNegativePattern;
-        internal string FullTimeSpanNegativePattern
-        {
-            get
-            {
-                if (_fullTimeSpanNegativePattern == null)
-                    _fullTimeSpanNegativePattern = "'-'" + FullTimeSpanPositivePattern;
-                return _fullTimeSpanNegativePattern;
-            }
-        }
+        internal string FullTimeSpanNegativePattern =>
+            _fullTimeSpanNegativePattern ??= "'-'" + FullTimeSpanPositivePattern;
 
         // Get suitable CompareInfo from current DTFI object.
-        internal CompareInfo CompareInfo
-        {
-            get
-            {
-                if (_compareInfo == null)
-                {
-                    // We use the regular GetCompareInfo here to make sure the created CompareInfo object is stored in the
-                    // CompareInfo cache. otherwise we would just create CompareInfo using _cultureData.
-                    _compareInfo = CompareInfo.GetCompareInfo(_cultureData.SortName);
-                }
-
-                return _compareInfo;
-            }
-        }
+        internal CompareInfo CompareInfo =>
+            // We use the regular GetCompareInfo here to make sure the created CompareInfo object is stored in the
+            // CompareInfo cache. otherwise we would just create CompareInfo using _cultureData.
+            _compareInfo ??= CompareInfo.GetCompareInfo(_cultureData.SortName);
 
         internal const DateTimeStyles InvalidDateTimeStyles = ~(DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite
                                                                | DateTimeStyles.AllowInnerWhite | DateTimeStyles.NoCurrentDateDefault
index 269d087..e93ad3d 100644 (file)
@@ -214,10 +214,8 @@ namespace System.Globalization
 
                 if (KnownWords.TryGetValue(str, out _) == false)
                 {
-                    if (m_dateWords == null)
-                    {
-                        m_dateWords = new List<string>();
-                    }
+                    m_dateWords ??= new List<string>();
+
                     if (formatPostfix == "MMMM")
                     {
                         // Add the word into the ArrayList as "\xfffe" + real month postfix.
index 57a38d5..11c552a 100644 (file)
@@ -39,10 +39,7 @@ namespace System.Globalization
         /// Internal method to provide a default intance of GregorianCalendar.
         /// Used by NLS+ implementation
         /// </summary>
-        internal static Calendar GetDefaultInstance()
-        {
-            return s_defaultInstance ?? (s_defaultInstance = new GregorianCalendar());
-        }
+        internal static Calendar GetDefaultInstance() => s_defaultInstance ??= new GregorianCalendar();
 
         public GregorianCalendar() : this(GregorianCalendarTypes.Localized)
         {
index fcc2302..02b15af 100644 (file)
@@ -84,10 +84,7 @@ namespace System.Globalization
         internal static volatile Calendar? s_defaultInstance;
         internal GregorianCalendarHelper _helper;
 
-        internal static Calendar GetDefaultInstance()
-        {
-            return s_defaultInstance ?? (s_defaultInstance = new JapaneseCalendar());
-        }
+        internal static Calendar GetDefaultInstance() => s_defaultInstance ??= new JapaneseCalendar();
 
         public JapaneseCalendar()
         {
index edd599b..0300382 100644 (file)
@@ -32,10 +32,7 @@ namespace System.Globalization
 
         private readonly GregorianCalendarHelper _helper;
 
-        internal static Calendar GetDefaultInstance()
-        {
-            return s_defaultInstance ?? (s_defaultInstance = new TaiwanCalendar());
-        }
+        internal static Calendar GetDefaultInstance() => s_defaultInstance ??= new TaiwanCalendar();
 
         private static readonly DateTime s_calendarMinValue = new DateTime(1912, 1, 1);
 
index 7fe69d6..4187c0d 100644 (file)
@@ -126,7 +126,7 @@ namespace System.Globalization
         /// </summary>
         public virtual string ListSeparator
         {
-            get => _listSeparator ?? (_listSeparator = _cultureData.ListSeparator);
+            get => _listSeparator ??= _cultureData.ListSeparator;
             set
             {
                 if (value == null)
index c33a740..2b213fe 100644 (file)
@@ -148,10 +148,7 @@ namespace System.IO
                 posSav = _stream.Position;
             }
 
-            if (_charBytes == null)
-            {
-                _charBytes = new byte[MaxCharBytesSize];
-            }
+            _charBytes ??= new byte[MaxCharBytesSize];
 
             Span<char> singleChar = stackalloc char[1];
 
@@ -289,15 +286,8 @@ namespace System.IO
                 return string.Empty;
             }
 
-            if (_charBytes == null)
-            {
-                _charBytes = new byte[MaxCharBytesSize];
-            }
-
-            if (_charBuffer == null)
-            {
-                _charBuffer = new char[_maxCharsSize];
-            }
+            _charBytes ??= new byte[MaxCharBytesSize];
+            _charBuffer ??= new char[_maxCharsSize];
 
             StringBuilder? sb = null;
             do
@@ -409,10 +399,7 @@ namespace System.IO
                 }
                 else
                 {
-                    if (_charBytes == null)
-                    {
-                        _charBytes = new byte[MaxCharBytesSize];
-                    }
+                    _charBytes ??= new byte[MaxCharBytesSize];
 
                     if (numBytes > MaxCharBytesSize)
                     {
index 30f0278..cbecd39 100644 (file)
@@ -41,17 +41,7 @@ namespace System.IO
             FileName = fileName;
         }
 
-        public override string Message
-        {
-            get
-            {
-                if (_message == null)
-                {
-                    _message = FormatFileLoadExceptionMessage(FileName, HResult);
-                }
-                return _message;
-            }
-        }
+        public override string Message => _message ??= FormatFileLoadExceptionMessage(FileName, HResult);
 
         public string? FileName { get; }
         public string? FusionLog { get; }
@@ -71,8 +61,7 @@ namespace System.IO
 
             if (FusionLog != null)
             {
-                if (s == null)
-                    s = " ";
+                s ??= " ";
                 s += Environment.NewLine;
                 s += Environment.NewLine;
                 s += FusionLog;
index dd152be..a4d6e44 100644 (file)
@@ -85,8 +85,7 @@ namespace System.IO
 
             if (FusionLog != null)
             {
-                if (s == null)
-                    s = " ";
+                s ??= " ";
                 s += Environment.NewLine;
                 s += Environment.NewLine;
                 s += FusionLog;
index db2cf4c..9de86d1 100644 (file)
@@ -77,8 +77,7 @@ namespace System.IO
                 // Quick check to make sure the IO hasn't completed
                 if (_overlapped != null)
                 {
-                    Action<object?>? cancelCallback = s_cancelCallback;
-                    if (cancelCallback == null) s_cancelCallback = cancelCallback = Cancel;
+                    Action<object?>? cancelCallback = s_cancelCallback ??= Cancel;
 
                     // Register the cancellation only if the IO hasn't completed
                     long packedResult = Interlocked.CompareExchange(ref _result, RegisteringCancellation, NoResult);
index e53fc9f..f9e2ecb 100644 (file)
@@ -645,8 +645,7 @@ namespace System.IO
                 {
                     _context = null;
 
-                    ContextCallback? invokeAsyncCallback = s_invokeAsyncCallback;
-                    if (invokeAsyncCallback == null) s_invokeAsyncCallback = invokeAsyncCallback = InvokeAsyncCallback; // benign race condition
+                    ContextCallback? invokeAsyncCallback = s_invokeAsyncCallback ??= InvokeAsyncCallback;
 
                     ExecutionContext.RunInternal(context, invokeAsyncCallback, this);
                 }
index 393d224..3fdfe77 100644 (file)
@@ -812,11 +812,9 @@ namespace System.IO
                     }
                     i++;
                 } while (i < _charLen);
+
                 i = _charLen - _charPos;
-                if (sb == null)
-                {
-                    sb = new StringBuilder(i + 80);
-                }
+                sb ??= new StringBuilder(i + 80);
                 sb.Append(_charBuffer, _charPos, i);
             } while (ReadBuffer() > 0);
             return sb.ToString();
@@ -896,10 +894,7 @@ namespace System.IO
                 } while (i < tmpCharLen);
 
                 i = tmpCharLen - tmpCharPos;
-                if (sb == null)
-                {
-                    sb = new StringBuilder(i + 80);
-                }
+                sb ??= new StringBuilder(i + 80);
                 sb.Append(tmpCharBuffer, tmpCharPos, i);
             } while (await ReadBufferAsync().ConfigureAwait(false) > 0);
 
index 801c87f..a0286dc 100644 (file)
@@ -227,8 +227,7 @@ namespace System
             if (source.Overlaps(destination))
                 throw new InvalidOperationException(SR.InvalidOperation_SpanOverlappedOperation);
 
-            if (culture == null)
-                culture = CultureInfo.CurrentCulture;
+            culture ??= CultureInfo.CurrentCulture;
 
             // Assuming that changing case does not affect length
             if (destination.Length < source.Length)
@@ -280,8 +279,7 @@ namespace System
             if (source.Overlaps(destination))
                 throw new InvalidOperationException(SR.InvalidOperation_SpanOverlappedOperation);
 
-            if (culture == null)
-                culture = CultureInfo.CurrentCulture;
+            culture ??= CultureInfo.CurrentCulture;
 
             // Assuming that changing case does not affect length
             if (destination.Length < source.Length)
index 690c3b0..32e9a07 100644 (file)
@@ -165,12 +165,7 @@ namespace System.Reflection
 
         // The compressed version of the public key formed from a truncated hash.
         // Will throw a SecurityException if _publicKey is invalid
-        public byte[]? GetPublicKeyToken()
-        {
-            if (_publicKeyToken == null)
-                _publicKeyToken = ComputePublicKeyToken();
-            return _publicKeyToken;
-        }
+        public byte[]? GetPublicKeyToken() => _publicKeyToken ??= ComputePublicKeyToken();
 
         public void SetPublicKeyToken(byte[]? publicKeyToken)
         {
index be4d7dd..4c22982 100644 (file)
@@ -154,8 +154,7 @@ namespace System.Resources
             // an empty string. We may in fact fail earlier for another reason, but otherwise we will
             // throw a MissingManifestResourceException when GetString is called indicating that a
             // resW filename called "" could not be found.
-            if (reswFilename == null)
-                reswFilename = string.Empty;
+            reswFilename ??= string.Empty;
 
             // At this point it is important NOT to set _useUapResourceManagement to false
             // if the PRI file does not exist because we are now certain we need to load PRI
index 7f486b3..8d98b57 100644 (file)
@@ -608,10 +608,7 @@ namespace System.Resources
             }
 #endif
 
-            if (culture == null)
-            {
-                culture = CultureInfo.CurrentUICulture;
-            }
+            culture ??= CultureInfo.CurrentUICulture;
 
             ResourceSet? last = GetFirstResourceSet(culture);
 
index 2a9e2c5..76d1d4a 100644 (file)
@@ -370,9 +370,9 @@ namespace System.Resources
                 if (!_haveReadFromReader)
                 {
                     // If necessary, init our case insensitive hash table.
-                    if (ignoreCase && _caseInsensitiveTable == null)
+                    if (ignoreCase)
                     {
-                        _caseInsensitiveTable = new Dictionary<string, ResourceLocator>(StringComparer.OrdinalIgnoreCase);
+                        _caseInsensitiveTable ??= new Dictionary<string, ResourceLocator>(StringComparer.OrdinalIgnoreCase);
                     }
 
                     if (_defaultReader == null)
index f75ca12..5adf447 100644 (file)
@@ -61,7 +61,7 @@ namespace System.Runtime.CompilerServices
                     if (eventArgs.Unwind)
                     {
                         // unwind
-                        if (innerException == null) { innerException = eventArgs.thrownDuringHandler; }
+                        innerException ??= eventArgs.thrownDuringHandler;
                         throw new ContractException(failureKind, displayMessage, userMessage, conditionText, innerException);
                     }
                 }
index 83c27fb..200a4be 100644 (file)
@@ -34,15 +34,8 @@ namespace System.Runtime.Serialization
         [ThreadStatic]
         private static DeserializationTracker? t_deserializationTracker;
 
-        private static DeserializationTracker GetThreadDeserializationTracker()
-        {
-            if (t_deserializationTracker == null)
-            {
-                t_deserializationTracker = new DeserializationTracker();
-            }
-
-            return t_deserializationTracker;
-        }
+        private static DeserializationTracker GetThreadDeserializationTracker() =>
+            t_deserializationTracker ??= new DeserializationTracker();
 #endif // !CORECLR
 
         // Returns true if deserialization is currently in progress
index 81cb7e7..70cd615 100644 (file)
@@ -82,10 +82,7 @@ namespace System
                 members = GetMember(defaultMemberName);
             }
 
-            if (members == null)
-                members = Array.Empty<MemberInfo>();
-
-            return members;
+            return members ?? Array.Empty<MemberInfo>();
         }
 
         public override Type GetElementType() => RuntimeTypeHandle.GetElementType(this);
index 93d5056..3ebf724 100644 (file)
@@ -245,8 +245,7 @@ namespace System.Security
             if (child == null)
                 throw new ArgumentNullException(nameof(child));
 
-            if (_children == null)
-                _children = new ArrayList(ChildrenTypical);
+            _children ??= new ArrayList(ChildrenTypical);
 
             _children.Add(child);
         }
@@ -405,8 +404,7 @@ namespace System.Security
                 }
                 else
                 {
-                    if (sb == null)
-                        sb = new StringBuilder();
+                    sb ??= new StringBuilder();
 
                     sb.Append(str, newIndex, index - newIndex);
                     sb.Append(GetEscapeSequence(str[index]));
@@ -470,8 +468,7 @@ namespace System.Security
                 }
                 else
                 {
-                    if (sb == null)
-                        sb = new StringBuilder();
+                    sb ??= new StringBuilder();
 
                     sb.Append(str, newIndex, index - newIndex);
                     sb.Append(GetUnescapeSequence(str, index, out newIndex)); // updates the newIndex too
index 7944df5..0c79ce3 100644 (file)
@@ -1000,8 +1000,7 @@ namespace System
 
             // If they asked to replace oldValue with a null, replace all occurrences
             // with the empty string.
-            if (newValue == null)
-                newValue = string.Empty;
+            newValue ??= string.Empty;
 
             CultureInfo referenceCulture = culture ?? CultureInfo.CurrentCulture;
             StringBuilder result = StringBuilderCache.Acquire();
@@ -1119,8 +1118,7 @@ namespace System
                 throw new ArgumentException(SR.Argument_StringZeroLength, nameof(oldValue));
 
             // Api behavior: if newValue is null, instances of oldValue are to be removed.
-            if (newValue == null)
-                newValue = string.Empty;
+            newValue ??= string.Empty;
 
             Span<int> initialSpan = stackalloc int[StackallocIntBufferSizeLimit];
             var replacementIndices = new ValueListBuilder<int>(initialSpan);
index 7991419..ad47a58 100644 (file)
@@ -71,8 +71,7 @@ namespace System.Text
                 lock (InternalSyncObject)
                 {
                     // Double check before we do it again.
-                    if (_oFallback._arrayBestFit == null)
-                        _oFallback._arrayBestFit = fallback._encoding.GetBestFitBytesToUnicodeData();
+                    _oFallback._arrayBestFit ??= fallback._encoding.GetBestFitBytesToUnicodeData();
                 }
             }
         }
index 33df140..d3b24e1 100644 (file)
@@ -71,8 +71,7 @@ namespace System.Text
                 lock (InternalSyncObject)
                 {
                     // Double check before we do it again.
-                    if (_oFallback._arrayBestFit == null)
-                        _oFallback._arrayBestFit = fallback._encoding.GetBestFitUnicodeToBytesData();
+                    _oFallback._arrayBestFit ??= fallback._encoding.GetBestFitUnicodeToBytesData();
                 }
             }
         }
index 1300f16..becf7e1 100644 (file)
@@ -1781,9 +1781,9 @@ namespace System.Text
                     // Otherwise, fallback to trying IFormattable or calling ToString.
                     if (arg is IFormattable formattableArg)
                     {
-                        if (itemFormatSpan.Length != 0 && itemFormat == null)
+                        if (itemFormatSpan.Length != 0)
                         {
-                            itemFormat = new string(itemFormatSpan);
+                            itemFormat ??= new string(itemFormatSpan);
                         }
                         s = formattableArg.ToString(itemFormat, provider);
                     }
index dec0eab..1ed5c02 100644 (file)
@@ -697,7 +697,7 @@ namespace System.Threading
                         catch (Exception ex) when (!throwOnFirstException)
                         {
                             // Store the exception and continue
-                            (exceptionList ?? (exceptionList = new List<Exception>())).Add(ex);
+                            (exceptionList ??= new List<Exception>()).Add(ex);
                         }
 
                         // Drop the node. While we could add it to the free list, doing so has cost (we'd need to take the lock again)
index 1389949..abbdc13 100644 (file)
@@ -226,7 +226,7 @@ namespace System.Threading.Tasks
 
             // Store the faulted task's exceptions
             CompletionState cs = EnsureCompletionStateInitialized();
-            if (cs.m_exceptions == null) cs.m_exceptions = new List<Exception>();
+            cs.m_exceptions ??= new List<Exception>();
             cs.m_exceptions.AddRange(faultedTask.Exception.InnerExceptions);
 
             // Now that we're doomed, request completion
@@ -339,7 +339,7 @@ namespace System.Threading.Tasks
         {
             if (TaskScheduler.Default == m_underlyingTaskScheduler)
             {
-                IThreadPoolWorkItem workItem = m_threadPoolWorkItem ?? (m_threadPoolWorkItem = new SchedulerWorkItem(this));
+                IThreadPoolWorkItem workItem = m_threadPoolWorkItem ??= new SchedulerWorkItem(this);
                 ThreadPool.UnsafeQueueUserWorkItemInternal(workItem, preferLocal: !fairly);
                 return true;
             }
index 8b6632c..1cd1254 100644 (file)
@@ -1333,10 +1333,8 @@ namespace System.Threading.Tasks
         /// ASSUMES THAT m_stateFlags IS ALREADY SET!
         /// </summary>
         /// <returns>The initialized contingent properties object.</returns>
-        internal ContingentProperties EnsureContingentPropertiesInitializedUnsafe()
-        {
-            return m_contingentProperties ?? (m_contingentProperties = new ContingentProperties());
-        }
+        internal ContingentProperties EnsureContingentPropertiesInitializedUnsafe() =>
+            m_contingentProperties ??= new ContingentProperties();
 
         /// <summary>
         /// This internal property provides access to the CancellationToken that was set on the task
@@ -4777,7 +4775,7 @@ namespace System.Threading.Tasks
         /// <param name="initSize">The size to which to initialize the list if the list is null.</param>
         private static void AddToList<T>(T item, ref List<T>? list, int initSize)
         {
-            if (list == null) list = new List<T>(initSize);
+            list ??= new List<T>(initSize);
             list.Add(item);
         }
 
@@ -4863,11 +4861,7 @@ namespace System.Threading.Tasks
                 // this will make sure it won't throw again in the implicit wait
                 t.UpdateExceptionObservedStatus();
 
-                if (exceptions == null)
-                {
-                    exceptions = new List<Exception>(ex.InnerExceptions.Count);
-                }
-
+                exceptions ??= new List<Exception>(ex.InnerExceptions.Count);
                 exceptions.AddRange(ex.InnerExceptions);
             }
         }
@@ -5690,12 +5684,12 @@ namespace System.Threading.Tasks
 
                         if (task.IsFaulted)
                         {
-                            if (observedExceptions == null) observedExceptions = new List<ExceptionDispatchInfo>();
+                            observedExceptions ??= new List<ExceptionDispatchInfo>();
                             observedExceptions.AddRange(task.GetExceptionDispatchInfos());
                         }
                         else if (task.IsCanceled)
                         {
-                            if (canceledTask == null) canceledTask = task; // use the first task that's canceled
+                            canceledTask ??= task; // use the first task that's canceled
                         }
 
                         // Regardless of completion state, if the task has its debug bit set, transfer it to the
@@ -5924,12 +5918,12 @@ namespace System.Threading.Tasks
 
                         if (task.IsFaulted)
                         {
-                            if (observedExceptions == null) observedExceptions = new List<ExceptionDispatchInfo>();
+                            observedExceptions ??= new List<ExceptionDispatchInfo>();
                             observedExceptions.AddRange(task.GetExceptionDispatchInfos());
                         }
                         else if (task.IsCanceled)
                         {
-                            if (canceledTask == null) canceledTask = task; // use the first task that's canceled
+                            canceledTask ??= task; // use the first task that's canceled
                         }
                         else
                         {
index 9853577..684d2bf 100644 (file)
@@ -437,12 +437,7 @@ namespace System.Threading.Tasks
         /// to be passed as state.
         /// </returns>
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        private static ContextCallback GetPostActionCallback()
-        {
-            ContextCallback? callback = s_postActionCallback;
-            if (callback == null) { s_postActionCallback = callback = PostAction; } // lazily initialize SecurityCritical delegate
-            return callback;
-        }
+        private static ContextCallback GetPostActionCallback() => s_postActionCallback ??= PostAction;
     }
 
     /// <summary>Task continuation for awaiting with a task scheduler.</summary>
index 587eaca..2e47b71 100644 (file)
@@ -33,10 +33,7 @@ namespace System.Threading
             Debug.Assert(s_scheduledTimers == null);
 
             var timers = new List<TimerQueue>(Instances.Length);
-            if (s_scheduledTimersToFire == null)
-            {
-                s_scheduledTimersToFire = new List<TimerQueue>(Instances.Length);
-            }
+            s_scheduledTimersToFire ??= new List<TimerQueue>(Instances.Length);
 
             Thread timerThread = new Thread(TimerThread);
             timerThread.IsBackground = true;
index c9b0c32..c58f325 100644 (file)
@@ -59,14 +59,12 @@ namespace System
                 {
                     lock (InternalSyncObject)
                     {
-                        if (currentTimeZone == null)
-                        {
-                            currentTimeZone = new CurrentSystemTimeZone();
-                        }
+                        currentTimeZone ??= new CurrentSystemTimeZone();
                         tz = currentTimeZone;
                     }
                 }
-                return (tz);
+
+                return tz;
             }
         }
 
index 1321fe7..584db1d 100644 (file)
@@ -488,10 +488,7 @@ namespace System
                                 // we're returning directories.
                                 if (isDir)
                                 {
-                                    if (toExplore == null)
-                                    {
-                                        toExplore = new List<string>();
-                                    }
+                                    toExplore ??= new List<string>();
                                     toExplore.Add(fullPath);
                                 }
                                 else if (condition(fullPath))