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,
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;
// 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;
List<Type> disAllowMultiple = new List<Type>();
object?[] objAttr;
- if (type == null)
- type = typeof(Attribute);
+ type ??= typeof(Attribute);
objAttr = param.GetCustomAttributes(type, false);
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
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);
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(
removeOn = associateMethod;
else
{
- if (otherList is null)
- otherList = new List<MethodInfo>(cAssociates);
+ otherList ??= new List<MethodInfo>(cAssociates);
otherList.Add(associateMethod);
}
}
if (mustBeInheritable)
{
- attributeUsageAttribute = CustomAttribute.GetAttributeUsage(attributeType);
+ attributeUsageAttribute = GetAttributeUsage(attributeType);
if (!attributeUsageAttribute.Inherited)
return false;
{
if (derivedAttributes[i].GetType() == attributeType)
{
- if (attributeUsageAttribute == null)
- attributeUsageAttribute = CustomAttribute.GetAttributeUsage(attributeType);
-
+ attributeUsageAttribute ??= GetAttributeUsage(attributeType);
return attributeUsageAttribute.AllowMultiple;
}
}
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;
// 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)
{
// 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)
{
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)
}
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)
{
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,
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)
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()
SignatureHelper sigHelp;
MdSigCallingConvention intCall;
- if (returnType == null)
- returnType = typeof(void);
+ returnType ??= typeof(void);
if (unmanagedCallConv == CallingConvention.Cdecl)
{
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
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;
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++)
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)
#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(); }
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!;
#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;
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";
#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();
// 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()
{
#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;
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;
#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
{
#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()
{
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
{
get
{
- unsafe
- {
- Guid mvid;
- MetadataImport.GetScopeProps(out mvid);
- return mvid;
- }
+ MetadataImport.GetScopeProps(out Guid mvid);
+ return mvid;
}
}
// 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
{
#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);
#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
{
MemberInfoCache<T> newCache = new MemberInfoCache<T>(this);
existingCache = Interlocked.CompareExchange(ref m_cache, newCache, null);
- if (existingCache == null)
- existingCache = newCache;
+ existingCache ??= newCache;
}
return existingCache;
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
RuntimeType[]? methodInstantiation = null;
- if (reflectedType == null)
- reflectedType = declaredType as RuntimeType;
+ reflectedType ??= declaredType as RuntimeType;
if (reflectedType != declaredType && !reflectedType.IsSubclassOf(declaredType))
{
}
}
- if (binder == null)
- binder = DefaultBinder;
-
+ binder ??= DefaultBinder;
return binder.SelectMethod(bindingAttr, candidates.ToArray(), types, modifiers) as MethodInfo;
}
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;
}
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);
}
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)
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
int argCnt = (providedArgs != null) ? providedArgs.Length : 0;
- if (binder == null)
- binder = DefaultBinder;
-
+ binder ??= DefaultBinder;
bool bDefaultBinder = (binder == DefaultBinder);
// Delegate to Activator.CreateInstance
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); }
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
_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) });
}
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
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));
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)
// 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]);
}
}
if (array.Rank != 1)
ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported);
- if (comparer == null) comparer = Comparer.Default;
+ comparer ??= Comparer.Default;
#if CORECLR
if (comparer == Comparer.Default)
{
if (_fusionLog != null)
{
- if (s == null)
- s = " ";
+ s ??= " ";
s += Environment.NewLine;
s += Environment.NewLine;
s += _fusionLog;
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;
// 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)
{
try
{
- if (comparer == null)
- {
- comparer = Comparer<T>.Default;
- }
-
+ comparer ??= Comparer<T>.Default;
return InternalBinarySearch(array, index, length, value, comparer);
}
catch (Exception e)
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]
{
// 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
// 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
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)
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)
}
}
- if (probablyNotRewritten == null)
- probablyNotRewritten = thisAssembly;
+ probablyNotRewritten ??= thisAssembly;
string? simpleName = probablyNotRewritten.GetName().Name;
ContractHelper.TriggerFailure(kind, SR.Format(SR.MustUseCCRewrite, contractKind, simpleName), null, null, null);
}
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
{
// 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;
if (val > 1)
return;
- if (sessionList == null)
- sessionList = new List<SessionInfo>(8);
+ sessionList ??= new List<SessionInfo>(8);
if (val == 1)
{
{
if (m_eventSourceEnabled)
{
- if (arg1 == null) arg1 = "";
+ arg1 ??= "";
fixed (char* string1Bytes = arg1)
{
EventSource.EventData* descrs = stackalloc EventSource.EventData[1];
{
if (m_eventSourceEnabled)
{
- if (arg1 == null) arg1 = "";
- if (arg2 == null) arg2 = "";
+ arg1 ??= "";
+ arg2 ??= "";
fixed (char* string1Bytes = arg1)
fixed (char* string2Bytes = arg2)
{
{
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)
{
if (m_eventSourceEnabled)
{
- if (arg1 == null) arg1 = "";
+ arg1 ??= "";
fixed (char* string1Bytes = arg1)
{
EventSource.EventData* descrs = stackalloc EventSource.EventData[2];
{
if (m_eventSourceEnabled)
{
- if (arg1 == null) arg1 = "";
+ arg1 ??= "";
fixed (char* string1Bytes = arg1)
{
EventSource.EventData* descrs = stackalloc EventSource.EventData[3];
{
if (m_eventSourceEnabled)
{
- if (arg1 == null) arg1 = "";
+ arg1 ??= "";
fixed (char* string1Bytes = arg1)
{
EventSource.EventData* descrs = stackalloc EventSource.EventData[2];
{
if (m_eventSourceEnabled)
{
- if (arg2 == null) arg2 = "";
+ arg2 ??= "";
fixed (char* string2Bytes = arg2)
{
EventSource.EventData* descrs = stackalloc EventSource.EventData[2];
{
if (m_eventSourceEnabled)
{
- if (arg2 == null) arg2 = "";
+ arg2 ??= "";
fixed (char* string2Bytes = arg2)
{
EventSource.EventData* descrs = stackalloc EventSource.EventData[2];
/// {
/// if (IsEnabled())
/// {
- /// if (arg2 == null) arg2 = "";
+ /// arg2 ??= "";
/// fixed (char* string2Bytes = arg2)
/// {
/// EventSource.EventData* descrs = stackalloc EventSource.EventData[2];
/// {
/// if (IsEnabled())
/// {
- /// if (arg2 == null) arg2 = "";
+ /// arg2 ??= "";
/// fixed (char* string2Bytes = arg2)
/// {
/// EventSource.EventData* descrs = stackalloc EventSource.EventData[2];
}
catch (Exception e)
{
- if (m_constructionException == null)
- m_constructionException = e;
+ m_constructionException ??= e;
ReportOutOfBandMessage("ERROR: Exception during construction of EventSource " + Name + ": " + e.Message, true);
}
/// </summary>
public void Start()
{
- if (this.w == null)
- {
- this.w = new uint[85];
- }
+ this.w ??= new uint[85];
this.length = 0;
this.pos = 0;
{
// 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.
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)
{
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
// throw new WarningException(SR.EventSource_EventNameDoesNotEqualTaskPlusOpcode);
// }
- if (eventsByName == null)
- eventsByName = new Dictionary<string, string>();
+ eventsByName ??= new Dictionary<string, string>();
if (eventsByName.ContainsKey(evtName))
{
{
lock (EventListenersLock)
{
- if (s_EventSources == null)
- s_EventSources = new List<WeakReference>(2);
+ s_EventSources ??= new List<WeakReference>(2);
if (!s_EventSourceShutdownRegistered)
{
ManifestError(SR.Format(SR.EventSource_OpcodeCollision, name, prevName, value));
}
}
+
opcodeTab[value] = name;
}
+
public void AddTask(string name, int value)
{
if ((flags & EventManifestOptions.Strict) != 0)
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?
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;
}
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 };
}
{
// 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
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
}
{
// 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);
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("\"");
// 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)
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)
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;
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);
}
{
if (IsEnabled())
{
- if (arg3 == null) arg3 = "";
+ arg3 ??= "";
fixed (char* string3Bytes = arg3)
{
EventSource.EventData* descrs = stackalloc EventSource.EventData[6];
{
if (IsEnabled())
{
- if (arg3 == null) arg3 = "";
+ arg3 ??= "";
fixed (char* string3Bytes = arg3)
{
EventSource.EventData* descrs = stackalloc EventSource.EventData[3];
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;
public virtual string? Source
{
- get => _source ?? (_source = CreateSourceName());
+ get => _source ??= CreateSourceName();
set => _source = value;
}
// 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
}
{
// 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("\\'");
{
// 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("\\\\");
}
// 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
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)
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)
{
}
break;
default:
- if (result != null)
- {
- result.Append(str[i]);
- }
+ result?.Append(str[i]);
break;
}
}
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.
// 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
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.
/// 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)
{
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()
{
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);
/// </summary>
public virtual string ListSeparator
{
- get => _listSeparator ?? (_listSeparator = _cultureData.ListSeparator);
+ get => _listSeparator ??= _cultureData.ListSeparator;
set
{
if (value == null)
posSav = _stream.Position;
}
- if (_charBytes == null)
- {
- _charBytes = new byte[MaxCharBytesSize];
- }
+ _charBytes ??= new byte[MaxCharBytesSize];
Span<char> singleChar = stackalloc char[1];
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
}
else
{
- if (_charBytes == null)
- {
- _charBytes = new byte[MaxCharBytesSize];
- }
+ _charBytes ??= new byte[MaxCharBytesSize];
if (numBytes > MaxCharBytesSize)
{
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; }
if (FusionLog != null)
{
- if (s == null)
- s = " ";
+ s ??= " ";
s += Environment.NewLine;
s += Environment.NewLine;
s += FusionLog;
if (FusionLog != null)
{
- if (s == null)
- s = " ";
+ s ??= " ";
s += Environment.NewLine;
s += Environment.NewLine;
s += FusionLog;
// 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);
{
_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);
}
}
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();
} 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);
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)
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)
// 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)
{
// 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
}
#endif
- if (culture == null)
- {
- culture = CultureInfo.CurrentUICulture;
- }
+ culture ??= CultureInfo.CurrentUICulture;
ResourceSet? last = GetFirstResourceSet(culture);
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)
if (eventArgs.Unwind)
{
// unwind
- if (innerException == null) { innerException = eventArgs.thrownDuringHandler; }
+ innerException ??= eventArgs.thrownDuringHandler;
throw new ContractException(failureKind, displayMessage, userMessage, conditionText, innerException);
}
}
[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
members = GetMember(defaultMemberName);
}
- if (members == null)
- members = Array.Empty<MemberInfo>();
-
- return members;
+ return members ?? Array.Empty<MemberInfo>();
}
public override Type GetElementType() => RuntimeTypeHandle.GetElementType(this);
if (child == null)
throw new ArgumentNullException(nameof(child));
- if (_children == null)
- _children = new ArrayList(ChildrenTypical);
+ _children ??= new ArrayList(ChildrenTypical);
_children.Add(child);
}
}
else
{
- if (sb == null)
- sb = new StringBuilder();
+ sb ??= new StringBuilder();
sb.Append(str, newIndex, index - newIndex);
sb.Append(GetEscapeSequence(str[index]));
}
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
// 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();
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);
lock (InternalSyncObject)
{
// Double check before we do it again.
- if (_oFallback._arrayBestFit == null)
- _oFallback._arrayBestFit = fallback._encoding.GetBestFitBytesToUnicodeData();
+ _oFallback._arrayBestFit ??= fallback._encoding.GetBestFitBytesToUnicodeData();
}
}
}
lock (InternalSyncObject)
{
// Double check before we do it again.
- if (_oFallback._arrayBestFit == null)
- _oFallback._arrayBestFit = fallback._encoding.GetBestFitUnicodeToBytesData();
+ _oFallback._arrayBestFit ??= fallback._encoding.GetBestFitUnicodeToBytesData();
}
}
}
// 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);
}
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)
// 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
{
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;
}
/// 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
/// <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);
}
// 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);
}
}
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
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
{
/// 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>
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;
{
lock (InternalSyncObject)
{
- if (currentTimeZone == null)
- {
- currentTimeZone = new CurrentSystemTimeZone();
- }
+ currentTimeZone ??= new CurrentSystemTimeZone();
tz = currentTimeZone;
}
}
- return (tz);
+
+ return tz;
}
}
// we're returning directories.
if (isDir)
{
- if (toExplore == null)
- {
- toExplore = new List<string>();
- }
+ toExplore ??= new List<string>();
toExplore.Add(fullPath);
}
else if (condition(fullPath))