internal virtual void RecordTokenFixup()
{
if (m_RelocFixupList == null)
+ {
m_RelocFixupList = new int[DefaultFixupArraySize];
+ }
else if (m_RelocFixupList.Length <= m_RelocFixupCount)
+ {
m_RelocFixupList = EnlargeArray(m_RelocFixupList);
+ }
m_RelocFixupList[m_RelocFixupCount++] = m_length;
}
SignatureHelper sigHelp;
MdSigCallingConvention intCall;
- if (returnType == null)
- {
- returnType = typeof(void);
- }
+ returnType ??= typeof(void);
intCall = MdSigCallingConvention.Default;
{
SignatureHelper sigHelp;
- if (returnType == null)
- {
- returnType = typeof(void);
- }
+ returnType ??= typeof(void);
MdSigCallingConvention intCall = MdSigCallingConvention.Property;
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, EmptyTypes, null);
}
- if (con == null)
- {
- con = m_typeParent!.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, EmptyTypes, null);
- }
+ con ??= m_typeParent!.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, EmptyTypes, null);
if (con == null)
throw new NotSupportedException(SR.NotSupported_NoParentDefaultConstructor);
return ArrayElementType.TypeArguments;
}
- if (_typeArguments == null)
- {
- _typeArguments = new CodeTypeReferenceCollection();
- }
-
- return _typeArguments;
+ return _typeArguments ??= new CodeTypeReferenceCollection();
}
}
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "starting capture");
- if (cachedContext == null)
- {
- cachedContext = ExecutionContext.Capture();
- }
+ cachedContext ??= ExecutionContext.Capture();
if (cachedContext != null)
{
if (first && (token == CookieToken.NameValuePair || token == CookieToken.Attribute))
{
- if (cookie == null)
- {
- cookie = new Cookie();
- }
+ cookie ??= new Cookie();
InternalSetNameMethod(cookie, _tokenizer.Name);
cookie.Value = _tokenizer.Value;
}
{
if (Log.IsEnabled())
{
- if (arg1 == null) arg1 = "";
- if (arg2 == null) arg2 = "";
- if (arg3 == null) arg3 = "";
- if (arg4 == null) arg4 = "";
+ arg1 ??= "";
+ arg2 ??= "";
+ arg3 ??= "";
+ arg4 ??= "";
fixed (char* string1Bytes = arg1)
fixed (char* string2Bytes = arg2)
{
if (Log.IsEnabled())
{
- if (arg1 == null) arg1 = "";
- if (arg2 == null) arg2 = "";
- if (arg3 == null) arg3 = Array.Empty<byte>();
+ arg1 ??= "";
+ arg2 ??= "";
+ arg3 ??= Array.Empty<byte>();
fixed (char* arg1Ptr = arg1)
fixed (char* arg2Ptr = arg2)
{
if (Log.IsEnabled())
{
- if (arg1 == null) arg1 = "";
+ arg1 ??= "";
fixed (char* arg1Ptr = arg1)
{
{
if (Log.IsEnabled())
{
- if (arg1 == null) arg1 = "";
- if (arg3 == null) arg3 = "";
+ arg1 ??= "";
+ arg3 ??= "";
fixed (char* arg1Ptr = arg1)
fixed (char* arg3Ptr = arg3)
{
if (Log.IsEnabled())
{
- if (arg1 == null) arg1 = "";
- if (arg2 == null) arg2 = "";
+ arg1 ??= "";
+ arg2 ??= "";
fixed (char* arg1Ptr = arg1)
fixed (char* arg2Ptr = arg2)
{
if (Log.IsEnabled())
{
- if (arg1 == null) arg1 = "";
- if (arg2 == null) arg2 = "";
- if (arg3 == null) arg3 = "";
+ arg1 ??= "";
+ arg2 ??= "";
+ arg3 ??= "";
fixed (char* arg1Ptr = arg1)
fixed (char* arg2Ptr = arg2)
{
if (Log.IsEnabled())
{
- if (arg1 == null) arg1 = "";
+ arg1 ??= "";
fixed (char* arg1Ptr = arg1)
{
{
if (Log.IsEnabled())
{
- if (arg1 == null) arg1 = "";
- if (arg2 == null) arg2 = "";
+ arg1 ??= "";
+ arg2 ??= "";
fixed (char* arg1Ptr = arg1)
fixed (char* arg2Ptr = arg2)
// True indicates this instance is for Server and will use AcceptSecurityContext SSPI API.
internal bool IsServer => _isServer;
- internal string? ClientSpecifiedSpn
- {
- get
- {
- if (_clientSpecifiedSpn == null)
- {
- _clientSpecifiedSpn = GetClientSpecifiedSpn();
- }
-
- return _clientSpecifiedSpn;
- }
- }
+ internal string? ClientSpecifiedSpn => _clientSpecifiedSpn ??= GetClientSpecifiedSpn();
internal string ProtocolName
{
ref byte[] resultBlob,
ref ContextFlagsPal contextFlags)
{
- if (securityContext == null)
- {
- securityContext = new SafeDeleteNegoContext((SafeFreeNegoCredentials)credentialsHandle!);
- }
+ securityContext ??= new SafeDeleteNegoContext((SafeFreeNegoCredentials)credentialsHandle!);
SafeDeleteNegoContext negoContext = (SafeDeleteNegoContext)securityContext;
try
// Check for duplicate resources whose names vary only by case.
_caseInsensitiveDups.Add(name, null);
- if (_preserializedData == null)
- _preserializedData = new Dictionary<string, PrecannedResource>(FastResourceComparer.Default);
+ _preserializedData ??= new Dictionary<string, PrecannedResource>(FastResourceComparer.Default);
_preserializedData.Add(name, new PrecannedResource(typeName, data));
}
&& pi.ParameterType.HasElementType
&& pi.ParameterType.GetElementType()!.IsEnum)
{
- if (targetTypes == null)
- {
- targetTypes = new Type?[_expectedParamsCount];
- }
+ targetTypes ??= new Type?[_expectedParamsCount];
targetTypes[i] = pi.ParameterType.GetElementType();
}
return (int)charCount;
}
- public override string EncodingName
- {
- get
- {
- if (_encodingName == null)
- {
- _encodingName = "Codepage - " + _codePage.ToString();
- }
- return _encodingName;
- }
- }
+ public override string EncodingName => _encodingName ??= $"Codepage - {_codePage}";
public override string WebName
{
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
public void AddHandler(int dispid, object func)
{
- ComEventsMethod method = FindMethod(dispid);
- if (method == null)
- {
- method = AddMethod(dispid);
- }
+ ComEventsMethod method = FindMethod(dispid) ?? AddMethod(dispid);
if (func is Delegate d)
{
get { return EnsureVariable(ref _propertyPutDispId, typeof(int), "propertyPutDispId"); }
}
- private ParameterExpression ParamVariantsVariable
- {
- get
- {
- if (_paramVariants == null)
- {
- _paramVariants = Expression.Variable(VariantArray.GetStructType(_args.Length), "paramVariants");
- }
- return _paramVariants;
- }
- }
+ private ParameterExpression ParamVariantsVariable => _paramVariants ??= Expression.Variable(VariantArray.GetStructType(_args.Length), "paramVariants");
private static ParameterExpression EnsureVariable(ref ParameterExpression var, Type type, string name)
{
if (isByRef)
{
// Null just means that null was supplied.
- if (marshalType == null)
- {
- marshalType = mo.Expression.Type;
- }
+ marshalType ??= mo.Expression.Type;
marshalType = marshalType.MakeByRefType();
}
return marshalType;
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
public object CreateInstance()
{
- if (_typeObj == null)
- {
- _typeObj = Type.GetTypeFromCLSID(Guid);
- }
+ _typeObj ??= Type.GetTypeFromCLSID(Guid);
return Activator.CreateInstance(Type.GetTypeFromCLSID(Guid));
}
if (isSourceItf)
{
- if (_sourceItfs == null)
- {
- _sourceItfs = new LinkedList<string>();
- }
+ _sourceItfs ??= new LinkedList<string>();
_sourceItfs.AddLast(itfName);
}
else
{
- if (_itfs == null)
- {
- _itfs = new LinkedList<string>();
- }
-
+ _itfs ??= new LinkedList<string>();
_itfs.AddLast(itfName);
}
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
internal override IList<KeyValuePair<string, object>> GetMembers(IEnumerable<string> names)
{
- if (names == null)
- {
- names = GetMemberNames(true);
- }
+ names ??= GetMemberNames(true);
Type comType = RuntimeCallableWrapper.GetType();
Debug.Assert(args != null);
// Create a CallSite and invoke it.
- if (_site == null)
- {
- _site = CallSite<Func<CallSite, object, object[], object>>.Create(SplatInvokeBinder.Instance);
- }
+ _site ??= CallSite<Func<CallSite, object, object[], object>>.Create(SplatInvokeBinder.Instance);
return _site.Target(_site, _callable, args);
}
// try lifted conversion
if (nnExprType != convertFrom || nnConvType != convertToType)
{
- method = FindConversionOperator(eMethods, nnExprType, nnConvType, implicitOnly);
- if (method == null)
- {
- method = FindConversionOperator(cMethods, nnExprType, nnConvType, implicitOnly);
- }
+ method =
+ FindConversionOperator(eMethods, nnExprType, nnConvType, implicitOnly) ??
+ FindConversionOperator(cMethods, nnExprType, nnConvType, implicitOnly);
if (method != null)
{
return method;
private void BeginString()
{
Debug.Assert(_strBuilder == null || _strBuilder.Length == 0);
- if (_strBuilder == null)
- {
- _strBuilder = new StringBuilder();
- }
+ _strBuilder ??= new StringBuilder();
}
private string EndString()
Name name = named.Name;
if (!methprop.ParameterNames.Contains(name))
{
- if (_pInvalidSpecifiedName == null)
- {
- _pInvalidSpecifiedName = name;
- }
+ _pInvalidSpecifiedName ??= name;
return false;
}
else if (!currentPosition.Contains(name))
{
- if (_pNameUsedInPositionalArgument == null)
- {
- _pNameUsedInPositionalArgument = name;
- }
+ _pNameUsedInPositionalArgument ??= name;
return false;
}
if (!names.Add(name))
{
- if (_pDuplicateSpecifiedName == null)
- {
- _pDuplicateSpecifiedName = name;
- }
+ _pDuplicateSpecifiedName ??= name;
return false;
}
}
AggregateType typeCur = typeStart;
int itypeNext = 0;
- if (typeCur == null)
- {
- typeCur = (AggregateType)types[itypeNext++];
- }
+ typeCur ??= (AggregateType)types[itypeNext++];
Debug.Assert(typeCur != null);
// Loop through the interfaces.
}
// Try the conversion - if it fails, do a cast without user defined casts.
- Expr arg = tryConvert(pArgument, uofs.GetType());
- if (arg == null)
- {
- arg = mustCast(pArgument, uofs.GetType(), CONVERTTYPE.NOUDC);
- }
+ Expr arg =
+ tryConvert(pArgument, uofs.GetType()) ??
+ mustCast(pArgument, uofs.GetType(), CONVERTTYPE.NOUDC);
return uofs.pfn(this, ek, flags, arg);
}
public static PropertySymbol GetProperty(PREDEFPROP property)
{
Debug.Assert(property >= 0 && property < PREDEFPROP.PP_COUNT);
- return _properties[(int)property] ?? (_properties[(int)property] = LoadProperty(property));
+ return _properties[(int)property] ??= LoadProperty(property);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
public static MethodSymbol GetMethod(PREDEFMETH method)
{
Debug.Assert(method >= 0 && method < PREDEFMETH.PM_COUNT);
- return _methods[(int)method] ?? (_methods[(int)method] = LoadMethod(method));
+ return _methods[(int)method] ??= LoadMethod(method);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
public static AggregateSymbol GetPredefinedAggregate(PredefinedType pt) =>
- s_predefSymbols[(int)pt] ?? (s_predefSymbols[(int)pt] = DelayLoadPredefSym(pt));
+ s_predefSymbols[(int)pt] ??= DelayLoadPredefSym(pt);
////////////////////////////////////////////////////////////////////////////////
// Some of the predefined types have built-in names, like "int" or "string" or
{
Debug.Assert(atsOuter == null || atsOuter.OwningAggregate == agg.Parent, "");
- if (typeArgs == null)
- {
- typeArgs = TypeArray.Empty;
- }
+ typeArgs ??= TypeArray.Empty;
Debug.Assert(agg.GetTypeVars().Count == typeArgs.Count);
AggregateType pAggregate = TypeTable.LookupAggregate(agg, atsOuter, typeArgs);
foreach (ServiceCallSite parameterCallSite in constructorCallSite.ParameterCallSites)
{
Type? scoped = VisitCallSite(parameterCallSite, state);
- if (result == null)
- {
- result = scoped;
- }
+ result ??= scoped;
}
return result;
}
foreach (ServiceCallSite serviceCallSite in enumerableCallSite.ServiceCallSites)
{
Type? scoped = VisitCallSite(serviceCallSite, state);
- if (result == null)
- {
- result = scoped;
- }
+ result ??= scoped;
}
return result;
}
protected override object? VisitFactory(FactoryCallSite factoryCallSite, ILEmitResolverBuilderContext argument)
{
- if (argument.Factories == null)
- {
- argument.Factories = new List<Func<IServiceProvider, object>>();
- }
+ argument.Factories ??= new List<Func<IServiceProvider, object>>();
// this.Factories[i](ProviderScope)
argument.Generator.Emit(OpCodes.Ldarg_0);
private static void AddConstant(ILEmitResolverBuilderContext argument, object? value)
{
- if (argument.Constants == null)
- {
- argument.Constants = new List<object?>();
- }
+ argument.Constants ??= new List<object?>();
// this.Constants[i]
argument.Generator.Emit(OpCodes.Ldarg_0);
}
}
- if (compilationOptions == null)
- {
- compilationOptions = CompilationOptions.Default;
- }
+ compilationOptions ??= CompilationOptions.Default;
Target? runtimeTarget = SelectRuntimeTarget(targets, runtimeTargetName);
runtimeTargetName = runtimeTarget?.Name;
context = LoadEntryAssemblyContext(reader);
}
- if (context == null)
- {
- context = LoadAssemblyContext(assembly, reader);
- }
+ context ??= LoadAssemblyContext(assembly, reader);
if (context != null)
{
scanSegment = endLiteral + 1;
}
- if (segment == null)
- {
- segment = new WildcardPathSegment(beginsWith, contains, endsWith, ComparisonType);
- }
+ segment ??= new WildcardPathSegment(beginsWith, contains, endsWith, ComparisonType);
}
if (segment is not ParentPathSegment)
{
lock (_cleanupTimerLock)
{
- if (_cleanupTimer == null)
- {
- _cleanupTimer = NonCapturingTimer.Create(_cleanupCallback, this, DefaultCleanupInterval, Timeout.InfiniteTimeSpan);
- }
+ _cleanupTimer ??= NonCapturingTimer.Create(_cleanupCallback, this, DefaultCleanupInterval, Timeout.InfiniteTimeSpan);
}
}
}
catch (Exception ex)
{
- if (exceptions == null)
- {
- exceptions = new List<Exception>();
- }
-
+ exceptions ??= new List<Exception>();
exceptions.Add(ex);
}
}
}
catch (Exception ex)
{
- if (exceptions == null)
- {
- exceptions = new List<Exception>();
- }
-
+ exceptions ??= new List<Exception>();
exceptions.Add(ex);
}
}
catch (Exception ex)
{
- if (exceptions == null)
- {
- exceptions = new List<Exception>();
- }
-
+ exceptions ??= new List<Exception>();
exceptions.Add(ex);
}
}
if (provider is ISupportExternalScope supportsExternalScope)
{
- if (_scopeProvider == null)
- {
- _scopeProvider = new LoggerFactoryScopeProvider(_factoryOptions.ActivityTrackingOptions);
- }
+ _scopeProvider ??= new LoggerFactoryScopeProvider(_factoryOptions.ActivityTrackingOptions);
supportsExternalScope.SetScopeProvider(_scopeProvider);
}
{
get
{
- if (_implementationTypes == null)
- {
- _implementationTypes = new CodeTypeReferenceCollection();
- }
+ _implementationTypes ??= new CodeTypeReferenceCollection();
if ((_populated & ImplTypesCollection) == 0)
{
{
lock (this)
{
- if (_type == null)
- {
- _type = Type.GetType(_codeDomProviderTypeName);
- }
+ _type ??= Type.GetType(_codeDomProviderTypeName);
}
}
if (waitForSemaphoreWasSuccessful == false && millisecondsTimeout != 0)
{
// create the linked token if it is not created yet
- if (linkedTokenSource == null)
- linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken,
- _consumersCancellationTokenSource.Token);
+ linkedTokenSource ??= CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _consumersCancellationTokenSource.Token);
waitForSemaphoreWasSuccessful = _occupiedNodes.Wait(millisecondsTimeout, linkedTokenSource.Token);
}
}
}
// defer allocation to avoid false sharing
- if (_localList == null)
- {
- _localList = new KeyValuePair<long, TSource>[_maxChunkSize];
- }
+ _localList ??= new KeyValuePair<long, TSource>[_maxChunkSize];
// make the actual call to the enumerable that grabs a chunk
return _enumerable.GrabChunk(_localList, requestedChunkSize, ref _currentChunkSize!.Value);
public static void TryAdd(T item)
{
+ Stack<RefAsValueType<T>> localStack =
#if NETCOREAPP
- Stack<RefAsValueType<T>>? localStack = t_stack; // cache in a local to avoid unnecessary TLS hits on repeated accesses
- if (localStack == null)
- {
- t_stack = localStack = new Stack<RefAsValueType<T>>(MaxSize);
- }
+ t_stack ??= new Stack<RefAsValueType<T>>(MaxSize);
#else
- Stack<RefAsValueType<T>> localStack = ThreadLocalStack;
+ ThreadLocalStack;
#endif
// Just in case we're in a scenario where an object is continually requested on one thread
get
{
// Ensure the [ThreadStatic] is initialized to a dictionary
- Dictionary<Type, object>? typesToStacks = AllocFreeConcurrentStack.t_stacks;
- if (typesToStacks == null)
- {
- AllocFreeConcurrentStack.t_stacks = typesToStacks = new Dictionary<Type, object>();
- }
+ Dictionary<Type, object>? typesToStacks = AllocFreeConcurrentStack.t_stacks ??= new Dictionary<Type, object>();
// Get the stack that corresponds to the T
if (!typesToStacks.TryGetValue(s_typeOfT, out object? stackObj))
{
if (match(self.array[i]))
{
- if (removeIndices == null)
- {
- removeIndices = new List<int>();
- }
+ removeIndices ??= new List<int>();
removeIndices.Add(i);
}
// 0 and 1 element arrays don't need to be sorted.
if (count > 1)
{
- if (comparer == null)
- {
- comparer = Comparer<T>.Default;
- }
+ comparer ??= Comparer<T>.Default;
// Avoid copying the entire array when the array is already sorted.
bool outOfOrder = false;
// Creating an instance of ImmutableSortedMap<T> with our root node automatically freezes our tree,
// ensuring that the returned instance is immutable. Any further mutations made to this builder
// will clone (and unfreeze) the spine of modified nodes until the next time this method is invoked.
- if (_immutable == null)
- {
- _immutable = ImmutableDictionary<TKey, TValue>.Wrap(_root, _comparers, _count);
- }
-
- return _immutable;
+ return _immutable ??= ImmutableDictionary<TKey, TValue>.Wrap(_root, _comparers, _count);
}
#endregion
/// Gets a simple debugger-viewable collection.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
- public KeyValuePair<TKey, TValue>[] Contents
- {
- get
- {
- if (_contents == null)
- {
- _contents = _map.ToArray(_map.Count);
- }
-
- return _contents;
- }
- }
+ public KeyValuePair<TKey, TValue>[] Contents => _contents ??= _map.ToArray(_map.Count);
}
}
/// </summary>
public ImmutableDictionary<TKey, TValue> WithComparers(IEqualityComparer<TKey>? keyComparer, IEqualityComparer<TValue>? valueComparer)
{
- if (keyComparer == null)
- {
- keyComparer = EqualityComparer<TKey>.Default;
- }
-
- if (valueComparer == null)
- {
- valueComparer = EqualityComparer<TValue>.Default;
- }
+ keyComparer ??= EqualityComparer<TKey>.Default;
+ valueComparer ??= EqualityComparer<TValue>.Default;
if (this.KeyComparer == keyComparer)
{
{
get
{
- if (_collection == null)
- {
- _collection = _sequence.ToArray();
- }
+ _collection ??= _sequence.ToArray();
return _collection[index];
}
// Creating an instance of ImmutableSortedMap<T> with our root node automatically freezes our tree,
// ensuring that the returned instance is immutable. Any further mutations made to this builder
// will clone (and unfreeze) the spine of modified nodes until the next time this method is invoked.
- if (_immutable == null)
- {
- _immutable = ImmutableHashSet<T>.Wrap(_root, _equalityComparer, _count);
- }
-
- return _immutable;
+ return _immutable ??= ImmutableHashSet<T>.Wrap(_root, _equalityComparer, _count);
}
/// <summary>
/// </summary>
public ImmutableHashSet<T> WithComparer(IEqualityComparer<T>? equalityComparer)
{
- if (equalityComparer == null)
- {
- equalityComparer = EqualityComparer<T>.Default;
- }
+ equalityComparer ??= EqualityComparer<T>.Default;
if (equalityComparer == _equalityComparer)
{
// Creating an instance of ImmutableList<T> with our root node automatically freezes our tree,
// ensuring that the returned instance is immutable. Any further mutations made to this builder
// will clone (and unfreeze) the spine of modified nodes until the next time this method is invoked.
- if (_immutable == null)
- {
- _immutable = ImmutableList<T>.WrapNode(this.Root);
- }
-
- return _immutable;
+ return _immutable ??= ImmutableList<T>.WrapNode(this.Root);
}
#endregion
/// Gets a simple debugger-viewable list.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
- public T[] Contents
- {
- get
- {
- if (_cachedContents == null)
- {
- _cachedContents = _list.ToArray(_list.Count);
- }
-
- return _cachedContents;
- }
- }
+ public T[] Contents => _cachedContents ??= _list.ToArray(_list.Count);
}
}
{
if (match(item))
{
- if (list == null)
- {
- list = new List<T>();
- }
+ list ??= new List<T>();
list.Add(item);
}
// Although this is a lazy-init pattern, no lock is required because
// this instance is immutable otherwise, and a double-assignment from multiple
// threads is harmless.
- if (_backwardsReversed == null)
- {
- _backwardsReversed = _backwards.Reverse();
- }
+ _backwardsReversed ??= _backwards.Reverse();
Debug.Assert(_backwardsReversed != null);
return _backwardsReversed;
// Creating an instance of ImmutableSortedMap<T> with our root node automatically freezes our tree,
// ensuring that the returned instance is immutable. Any further mutations made to this builder
// will clone (and unfreeze) the spine of modified nodes until the next time this method is invoked.
- if (_immutable == null)
- {
- _immutable = Wrap(this.Root, _count, _keyComparer, _valueComparer);
- }
-
- return _immutable;
+ return _immutable ??= Wrap(this.Root, _count, _keyComparer, _valueComparer);
}
#endregion
}
/// Gets a simple debugger-viewable collection.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
- public KeyValuePair<TKey, TValue>[] Contents
- {
- get
- {
- if (_contents == null)
- {
- _contents = _map.ToArray(_map.Count);
- }
-
- return _contents;
- }
- }
+ public KeyValuePair<TKey, TValue>[] Contents => _contents ??= _map.ToArray(_map.Count);
}
}
/// </summary>
public ImmutableSortedDictionary<TKey, TValue> WithComparers(IComparer<TKey>? keyComparer, IEqualityComparer<TValue>? valueComparer)
{
- if (keyComparer == null)
- {
- keyComparer = Comparer<TKey>.Default;
- }
-
- if (valueComparer == null)
- {
- valueComparer = EqualityComparer<TValue>.Default;
- }
+ keyComparer ??= Comparer<TKey>.Default;
+ valueComparer ??= EqualityComparer<TValue>.Default;
if (keyComparer == _keyComparer)
{
// Creating an instance of ImmutableSortedSet<T> with our root node automatically freezes our tree,
// ensuring that the returned instance is immutable. Any further mutations made to this builder
// will clone (and unfreeze) the spine of modified nodes until the next time this method is invoked.
- if (_immutable == null)
- {
- _immutable = ImmutableSortedSet<T>.Wrap(this.Root, _comparer);
- }
-
- return _immutable;
+ return _immutable ??= ImmutableSortedSet<T>.Wrap(this.Root, _comparer);
}
/// <summary>
/// </summary>
public ImmutableSortedSet<T> WithComparer(IComparer<T>? comparer)
{
- if (comparer == null)
- {
- comparer = Comparer<T>.Default;
- }
+ comparer ??= Comparer<T>.Default;
if (comparer == _comparer)
{
return false;
}
- if (comparer == null)
- {
- comparer = EqualityComparer<TBase>.Default;
- }
+ comparer ??= EqualityComparer<TBase>.Default;
for (int i = 0; i < immutableArray.Length; i++)
{
{
Requires.NotNull(items, nameof(items));
- if (comparer == null)
- {
- comparer = EqualityComparer<TBase>.Default;
- }
+ comparer ??= EqualityComparer<TBase>.Default;
int i = 0;
int n = immutableArray.Length;
}
}
- public static CaseInsensitiveComparer DefaultInvariant
- {
- get
- {
- if (s_InvariantCaseInsensitiveComparer == null)
- {
- s_InvariantCaseInsensitiveComparer = new CaseInsensitiveComparer(CultureInfo.InvariantCulture);
- }
- return s_InvariantCaseInsensitiveComparer;
- }
- }
+ public static CaseInsensitiveComparer DefaultInvariant =>
+ s_InvariantCaseInsensitiveComparer ??= new CaseInsensitiveComparer(CultureInfo.InvariantCulture);
// Behaves exactly like Comparer.Default.Compare except that the comparison is case insensitive
// Compares two Objects by calling CompareTo.
{
private Hashtable? _hashtable;
- protected Hashtable InnerHashtable
- {
- get
- {
- if (_hashtable == null)
- _hashtable = new Hashtable();
- return _hashtable;
- }
- }
+ protected Hashtable InnerHashtable => _hashtable ??= new Hashtable();
protected IDictionary Dictionary
{
{
private ArrayList? _list;
- protected ArrayList InnerList
- {
- get
- {
- if (_list == null)
- _list = new ArrayList();
- return _list;
- }
- }
+ protected ArrayList InnerList => _list ??= new ArrayList();
public virtual int Count
{
// Remove and RemoveRange methods or through an enumerator).
// Null is an invalid key value.
//
- public virtual IList GetKeyList()
- {
- if (keyList == null) keyList = new KeyList(this);
- return keyList;
- }
+ public virtual IList GetKeyList() => keyList ??= new KeyList(this);
// Returns an IList representing the values of this sorted list. The
// returned list is an alias for the values of this sorted list, so
// elements (through the Remove, RemoveRange, Set and
// SetRange methods or through an enumerator).
//
- public virtual IList GetValueList()
- {
- if (valueList == null) valueList = new ValueList(this);
- return valueList;
- }
+ public virtual IList GetValueList() => valueList ??= new ValueList(this);
// Returns the value associated with the given key. If an entry with the
// given key is not found, the returned value is null.
}
}
- private ListDictionary List
- {
- get
- {
- if (list == null)
- {
- list = new ListDictionary(caseInsensitive ? StringComparer.OrdinalIgnoreCase : null);
- }
- return list;
- }
- }
+ private ListDictionary List => list ??= new ListDictionary(caseInsensitive ? StringComparer.OrdinalIgnoreCase : null);
private void ChangeOver()
{
{
return hashtable.GetEnumerator();
}
- if (list == null)
- {
- list = new ListDictionary(caseInsensitive ? StringComparer.OrdinalIgnoreCase : null);
- }
+
+ list ??= new ListDictionary(caseInsensitive ? StringComparer.OrdinalIgnoreCase : null);
return list.GetEnumerator();
}
_entriesTable.Add(name, entry);
}
else
- { // null key -- special case -- hashtable doesn't like null keys
- if (_nullKeyEntry == null)
- _nullKeyEntry = entry;
+ {
+ // null key -- special case -- hashtable doesn't like null keys
+ _nullKeyEntry ??= entry;
}
// add entry to the list
/// <para>Returns a <see cref='System.Collections.Specialized.NameObjectCollectionBase.KeysCollection'/> instance containing
/// all the keys in the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para>
/// </devdoc>
- public virtual KeysCollection Keys
- {
- get
- {
- if (_keys == null)
- _keys = new KeysCollection(this);
- return _keys;
- }
- }
+ public virtual KeysCollection Keys => _keys ??= new KeysCollection(this);
//
// Simple entry class to allow substitution of values and indexed access to keys
/// <devdoc>
/// <para>Gets all the keys in the <see cref='System.Collections.Specialized.NameValueCollection'/>. </para>
/// </devdoc>
- public virtual string?[] AllKeys
- {
- get
- {
- if (_allKeys == null)
- _allKeys = BaseGetAllKeys();
- return _allKeys;
- }
- }
+ public virtual string?[] AllKeys => _allKeys ??= BaseGetAllKeys();
}
}
}
}
- 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
{
}
}
- 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
{
public KeyValuePairComparer(IComparer<TKey>? keyComparer)
{
- if (keyComparer == null)
- {
- this.keyComparer = Comparer<TKey>.Default;
- }
- else
- {
- this.keyComparer = keyComparer;
- }
+ this.keyComparer = keyComparer ?? Comparer<TKey>.Default;
}
public override int Compare(KeyValuePair<TKey, TValue> x, KeyValuePair<TKey, TValue> y)
}
}
- private KeyList GetKeyListHelper()
- {
- if (keyList == null)
- keyList = new KeyList(this);
- return keyList;
- }
+ private KeyList GetKeyListHelper() => keyList ??= new KeyList(this);
- private ValueList GetValueListHelper()
- {
- if (valueList == null)
- valueList = new ValueList(this);
- return valueList;
- }
+ private ValueList GetValueListHelper() => valueList ??= new ValueList(this);
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
{
private static volatile IComparer? s_StructuralComparer;
private static volatile IEqualityComparer? s_StructuralEqualityComparer;
- public static IComparer StructuralComparer
- {
- get
- {
- IComparer? comparer = s_StructuralComparer;
- if (comparer == null)
- {
- comparer = new StructuralComparer();
- s_StructuralComparer = comparer;
- }
- return comparer;
- }
- }
+ public static IComparer StructuralComparer => s_StructuralComparer ??= new StructuralComparer();
- public static IEqualityComparer StructuralEqualityComparer
- {
- get
- {
- IEqualityComparer? comparer = s_StructuralEqualityComparer;
- if (comparer == null)
- {
- comparer = new StructuralEqualityComparer();
- s_StructuralEqualityComparer = comparer;
- }
- return comparer;
- }
- }
+ public static IEqualityComparer StructuralEqualityComparer => s_StructuralEqualityComparer ??= new StructuralEqualityComparer();
}
internal sealed class StructuralEqualityComparer : IEqualityComparer
object? otherPropertyValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);
if (!Equals(value, otherPropertyValue))
{
- if (OtherPropertyDisplayName == null)
- {
- OtherPropertyDisplayName = GetDisplayNameForProperty(otherPropertyInfo);
- }
+ OtherPropertyDisplayName ??= GetDisplayNameForProperty(otherPropertyInfo);
string[]? memberNames = validationContext.MemberName != null
? new[] { validationContext.MemberName }
/// <summary>
/// Gets a unique identifier for this attribute.
/// </summary>
- public override object TypeId
- {
- get
- {
- if (_typeId is null)
- {
- _typeId = new Tuple<string, Type>(Method, ValidatorType);
- }
-
- return _typeId;
- }
- }
+ public override object TypeId => _typeId ??= new Tuple<string, Type>(Method, ValidatorType);
/// <summary>
/// Gets the name of the method in <see cref="ValidatorType" /> to invoke to perform validation.
{
lock (_syncRoot)
{
- if (_propertyStoreItems == null)
- {
- _propertyStoreItems = CreatePropertyStoreItems();
- }
+ _propertyStoreItems ??= CreatePropertyStoreItems();
}
}
public ExportBuilder AddMetadata(string name, object value)
{
- if (_metadataItems == null)
- {
- _metadataItems = new List<Tuple<string, object>>();
- }
+ _metadataItems ??= new List<Tuple<string, object>>();
_metadataItems.Add(Tuple.Create(name, value));
return this;
public ExportBuilder AddMetadata(string name, Func<Type, object> itemFunc)
{
- if (_metadataItemFuncs == null)
- {
- _metadataItemFuncs = new List<Tuple<string, Func<Type, object>>>();
- }
+ _metadataItemFuncs ??= new List<Tuple<string, Func<Type, object>>>();
_metadataItemFuncs.Add(Tuple.Create(name, itemFunc));
return this;
internal void BuildAttributes(Type type, ref List<Attribute> attributes)
{
- if (attributes == null)
- {
- attributes = new List<Attribute>();
- }
+ attributes ??= new List<Attribute>();
if (_isInherited)
{
};
}
- if (attributes == null)
- {
- attributes = new List<Attribute>();
- }
+ attributes ??= new List<Attribute>();
attributes.Add(importAttribute);
}
public PartBuilder AddMetadata(string name, object value)
{
- if (_metadataItems == null)
- {
- _metadataItems = new List<Tuple<string, object>>();
- }
+ _metadataItems ??= new List<Tuple<string, object>>();
_metadataItems.Add(Tuple.Create(name, value));
return this;
public PartBuilder AddMetadata(string name, Func<Type, object> itemFunc)
{
- if (_metadataItemFuncs == null)
- {
- _metadataItemFuncs = new List<Tuple<string, Func<Type, object>>>();
- }
+ _metadataItemFuncs ??= new List<Tuple<string, Func<Type, object>>>();
_metadataItemFuncs.Add(Tuple.Create(name, itemFunc));
return this;
private static void ConfigureConstructorAttributes(ConstructorInfo constructorInfo, ref List<Tuple<object, List<Attribute>>> configuredMembers, Action<ParameterInfo, ImportBuilder> configureConstuctorImports)
{
- if (configuredMembers == null)
- {
- configuredMembers = new List<Tuple<object, List<Attribute>>>();
- }
+ configuredMembers ??= new List<Tuple<object, List<Attribute>>>();
// Make its attribute
configuredMembers.Add(Tuple.Create((object)constructorInfo, s_importingConstructorList));
if (attributes != null)
{
- if (configuredMembers == null)
- {
- configuredMembers = new List<Tuple<object, List<Attribute>>>();
- }
+ configuredMembers ??= new List<Tuple<object, List<Attribute>>>();
configuredMembers.Add(Tuple.Create((object)declaredPi, attributes));
}
var lambdaExpression = (LambdaExpression)parameter;
Delegate importDelegate = lambdaExpression.Compile();
- if (_importBuilders == null)
- {
- _importBuilders = new Dictionary<ParameterInfo, Action<ImportBuilder>>();
- }
+ _importBuilders ??= new Dictionary<ParameterInfo, Action<ImportBuilder>>();
_importBuilders.Add(parameterInfos[index], (Action<ImportBuilder>)importDelegate);
++index;
private static List<T> FastAppendToListAllowNulls<T>(this List<T>? source, T value)
{
- if (source == null)
- {
- source = new List<T>();
- }
+ source ??= new List<T>();
source.Add(value);
return source;
{
get
{
- if (_partCreationPolicy == null)
- {
- _partCreationPolicy = _type.GetFirstAttribute<PartCreationPolicyAttribute>() ?? PartCreationPolicyAttribute.Default;
- }
+ _partCreationPolicy ??= _type.GetFirstAttribute<PartCreationPolicyAttribute>() ?? PartCreationPolicyAttribute.Default;
return _partCreationPolicy.CreationPolicy;
}
Requires.NotNull(completeAction, nameof(completeAction));
- if (_completeActionList == null)
- {
- _completeActionList = new List<Action>();
- }
+ _completeActionList ??= new List<Action>();
_completeActionList.Add(completeAction);
}
Requires.NotNull(revertAction, nameof(revertAction));
- if (_revertActionList == null)
- {
- _revertActionList = new List<Action>();
- }
+ _revertActionList ??= new List<Action>();
_revertActionList.Add(revertAction);
}
get { return _factoryExportDefinition; }
}
- protected override object GetExportedValueCore()
- {
- if (_factoryExportPartDefinition == null)
- {
- _factoryExportPartDefinition = new FactoryExportPartDefinition(this);
- }
- return _factoryExportPartDefinition;
- }
+ protected override object GetExportedValueCore() =>
+ _factoryExportPartDefinition ??= new FactoryExportPartDefinition(this);
protected ComposablePartDefinition UnderlyingPartDefinition
{
List<ComposablePart>? partList;
ConditionalWeakTable<object, List<ComposablePart>>? gcRoots = _gcRoots;
- if (gcRoots == null)
- {
- gcRoots = new ConditionalWeakTable<object, List<ComposablePart>>();
- }
+ gcRoots ??= new ConditionalWeakTable<object, List<ComposablePart>>();
if (!gcRoots.TryGetValue(exportedValue, out partList))
{
{
if (parts.Remove(part))
{
- if (partsToRemove == null)
- {
- partsToRemove = new List<ComposablePart>();
- }
+ partsToRemove ??= new List<ComposablePart>();
partsToRemove.Add(part);
}
}
// Default value is ImportSource.Any
if (attributedImport != null && attributedImport.Source != ImportSource.Any)
{
- if (metadata == null)
- {
- metadata = new Dictionary<string, object?>();
- }
+ metadata ??= new Dictionary<string, object?>();
metadata[CompositionConstants.ImportSourceMetadataName] = attributedImport.Source;
}
contractName = AttributedModelServices.GetContractName(type);
}
- if (metadataViewType == null)
- {
- metadataViewType = ExportServices.DefaultMetadataViewType;
- }
+ metadataViewType ??= ExportServices.DefaultMetadataViewType;
if (!MetadataViewProvider.IsViewTypeValid(metadataViewType))
{
exports = null;
}
- if (exports == null)
- {
- exports = Array.Empty<Export>();
- }
+ exports ??= Array.Empty<Export>();
return checkResult;
}
/// A <see cref="IEnumerable{T}"/> of strings representing the contract names of
/// the exports that have changed in the <see cref="CompositionContainer"/>.
/// </value>
- public IEnumerable<string> ChangedContractNames
- {
- get
- {
- if (_changedContractNames == null)
- {
- _changedContractNames = AddedExports
- .Concat(RemovedExports)
- .Select(export => export.ContractName)
- .Distinct()
- .ToArray();
- }
- return _changedContractNames;
- }
- }
+ public IEnumerable<string> ChangedContractNames =>
+ _changedContractNames ??= AddedExports
+ .Concat(RemovedExports)
+ .Select(export => export.ContractName)
+ .Distinct()
+ .ToArray();
/// <summary>
/// Gets the atomicComposition, if any, that this change applies to.
{
if (import.IsImportDependentOnPart(candidateReachablePart, export, part.IsGeneric() != candidateReachablePart.IsGeneric()))
{
- if (reachablePartList == null)
- {
- reachablePartList = new List<ComposablePartDefinition>();
- }
+ reachablePartList ??= new List<ComposablePartDefinition>();
reachablePartList.Add(candidateReachablePart);
}
}
{
if (import.IsImportDependentOnPart(part, export, part.IsGeneric() != candidateReachablePart.IsGeneric()))
{
- if (reachablePartList == null)
- {
- reachablePartList = new List<ComposablePartDefinition>();
- }
+ reachablePartList ??= new List<ComposablePartDefinition>();
reachablePartList.Add(candidateReachablePart);
}
}
return Enumerable.Empty<string>();
}
- if (_importedContractNames == null)
- {
- _importedContractNames = Part.ImportDefinitions.Select(import => import.ContractName ?? ImportDefinition.EmptyContractName).Distinct().ToArray();
- }
- return _importedContractNames;
+ return _importedContractNames ??= Part.ImportDefinitions.Select(import => import.ContractName ?? ImportDefinition.EmptyContractName).Distinct().ToArray();
}
public CompositionResult TrySetImport(ImportDefinition import, Export[] exports)
SetSavedImport(import, savedExports, null));
}
- if (_importCache == null)
- {
- _importCache = new Dictionary<ImportDefinition, Export[]?>();
- }
-
+ _importCache ??= new Dictionary<ImportDefinition, Export[]?>();
_importCache[import] = exports;
}
{
if (export is IDisposable disposableExport)
{
- if (disposableExports == null)
- {
- disposableExports = new List<IDisposable>();
- }
+ disposableExports ??= new List<IDisposable>();
disposableExports.Add(disposableExport);
}
}
// Record the new collection
if (disposableExports != null)
{
- if (_importedDisposableExports == null)
- {
- _importedDisposableExports = new Dictionary<ImportDefinition, List<IDisposable>>();
- }
+ _importedDisposableExports ??= new Dictionary<ImportDefinition, List<IDisposable>>();
_importedDisposableExports[import] = disposableExports;
}
}
/// properties.
/// </para>
/// </remarks>
- public override Expression<Func<ExportDefinition, bool>> Constraint
- {
- get
- {
- if (_constraint == null)
- {
- _constraint = ConstraintServices.CreateConstraint(ContractName, RequiredTypeIdentity, RequiredMetadata, RequiredCreationPolicy);
- }
-
- return _constraint;
- }
- }
+ public override Expression<Func<ExportDefinition, bool>> Constraint =>
+ _constraint ??= ConstraintServices.CreateConstraint(ContractName, RequiredTypeIdentity, RequiredMetadata, RequiredCreationPolicy);
/// <summary>
/// Executes an optimized version of the contraint given by the <see cref="Constraint"/> property
{
Requires.NotNull(exportDefinition, nameof(exportDefinition));
- if (_compiledConstraint == null)
- {
- _compiledConstraint = Constraint.Compile();
- }
+ _compiledConstraint ??= Constraint.Compile();
return _compiledConstraint.Invoke(exportDefinition);
}
Thread.MemoryBarrier();
lock (_lock)
{
- if (_constructor == null)
- {
- _constructor = result;
- }
+ _constructor ??= result;
}
}
}
int exportIndex = reflectionExport.GetIndex();
- if (_exportsCache == null)
- {
- _exportsCache = new Dictionary<int, ExportingMember>();
- }
+ _exportsCache ??= new Dictionary<int, ExportingMember>();
if (!_exportsCache.TryGetValue(exportIndex, out ExportingMember? result))
{
result = GetExportingMember(definition);
ConstructorInfo? constructor = _creationInfo.GetConstructor();
lock (_lock)
{
- if (_constructor == null)
- {
- _constructor = constructor;
- }
+ _constructor ??= constructor;
}
}
ExportDefinition[] exports = _creationInfo.GetExports().ToArray();
lock (_lock)
{
- if (_exports == null)
- {
- _exports = exports;
- }
+ _exports ??= exports;
}
}
return _exports;
ImportDefinition[] imports = _creationInfo.GetImports().ToArray();
lock (_lock)
{
- if (_imports == null)
- {
- _imports = imports;
- }
+ _imports ??= imports;
}
}
return _imports;
IDictionary<string, object?> metadata = _creationInfo.GetMetadata().AsReadOnly();
lock (_lock)
{
- if (_metadata == null)
- {
- _metadata = metadata;
- }
+ _metadata ??= metadata;
}
}
return _metadata;
get { return _member; }
}
- public override IDictionary<string, object?> Metadata
- {
- get
- {
- if (_metadata == null)
- {
- _metadata = _exportDefinition.Metadata.AsReadOnly();
- }
- return _metadata;
- }
- }
+ public override IDictionary<string, object?> Metadata => _metadata ??= _exportDefinition.Metadata.AsReadOnly();
string ICompositionElement.DisplayName
{
{
ArgumentNullException.ThrowIfNull(existing);
- if (newAttributes == null)
- {
- newAttributes = Array.Empty<Attribute>();
- }
+ newAttributes ??= Array.Empty<Attribute>();
Attribute[] newArray = new Attribute[existing.Count + newAttributes.Length];
int actualCount = existing.Count;
// a relatively expensive call and we try to avoid it
// since we rarely encounter derived attribute types
// and this list is usually short.
- if (_foundAttributeTypes == null)
- {
- _foundAttributeTypes = new AttributeEntry[FoundTypesLimit];
- }
+ _foundAttributeTypes ??= new AttributeEntry[FoundTypesLimit];
int ind = 0;
lock (s_internalSyncObject)
{
- if (s_defaultAttributes == null)
- {
- s_defaultAttributes = new Dictionary<Type, Attribute?>();
- }
+ s_defaultAttributes ??= new Dictionary<Type, Attribute?>();
// If we have already encountered this, use what's in the table.
if (s_defaultAttributes.TryGetValue(attributeType, out Attribute? defaultAttribute))
}
else
{
- if (culture == null)
- {
- culture = CultureInfo.CurrentCulture;
- }
+ culture ??= CultureInfo.CurrentCulture;
NumberFormatInfo? formatInfo = (NumberFormatInfo?)culture.GetFormat(typeof(NumberFormatInfo));
return FromString(text, formatInfo);
if (destinationType == typeof(string) && value != null && TargetType.IsInstanceOfType(value))
{
- if (culture == null)
- {
- culture = CultureInfo.CurrentCulture;
- }
+ culture ??= CultureInfo.CurrentCulture;
NumberFormatInfo? formatInfo = (NumberFormatInfo?)culture.GetFormat(typeof(NumberFormatInfo));
return ToString(value, formatInfo);
protected virtual object? AddNewCore()
{
// Allow event handler to supply the new item for us
- object? newItem = FireAddingNew();
-
// If event hander did not supply new item, create one ourselves
- if (newItem == null)
- {
- newItem = Activator.CreateInstance(typeof(T));
- }
+ object? newItem = FireAddingNew() ?? Activator.CreateInstance(typeof(T));
// Add item to end of list. Note: If event handler returned an item not of type T,
// the cast below will trigger an InvalidCastException. This is by design.
// Note: inpc may be null if item is null, so always check.
if (item is INotifyPropertyChanged inpc)
{
- if (_propertyChangedEventHandler == null)
- {
- _propertyChangedEventHandler = new PropertyChangedEventHandler(Child_PropertyChanged);
- }
+ _propertyChangedEventHandler ??= new PropertyChangedEventHandler(Child_PropertyChanged);
inpc.PropertyChanged += _propertyChangedEventHandler;
}
}
ArgumentNullException.ThrowIfNull(value);
ArgumentNullException.ThrowIfNull(objectName);
- if (culture == null)
- {
- culture = CultureInfo.CurrentUICulture;
- }
+ culture ??= CultureInfo.CurrentUICulture;
// The general case here will be to always use the same culture, so optimize for
// that. The resourceSets hashtable uses culture as a key. It's value is
return string.Empty;
}
- if (culture == null)
- {
- culture = CultureInfo.CurrentCulture;
- }
+ culture ??= CultureInfo.CurrentCulture;
DateTimeFormatInfo? formatInfo = (DateTimeFormatInfo?)culture.GetFormat(typeof(DateTimeFormatInfo));
return string.Empty;
}
- if (culture == null)
- {
- culture = CultureInfo.CurrentCulture;
- }
+ culture ??= CultureInfo.CurrentCulture;
DateTimeFormatInfo? formatInfo = (DateTimeFormatInfo?)culture.GetFormat(typeof(DateTimeFormatInfo));
return string.Empty;
}
- if (culture == null)
- {
- culture = CultureInfo.CurrentCulture;
- }
+ culture ??= CultureInfo.CurrentCulture;
DateTimeFormatInfo? formatInfo;
formatInfo = (DateTimeFormatInfo?)culture.GetFormat(typeof(DateTimeFormatInfo));
if (Parent != null)
{
parent!._properties = null;
- if (Parent._children == null)
- {
- Parent._children = new ArrayList(1);
- }
+ Parent._children ??= new ArrayList(1);
Parent._children.Add(this);
}
}
if (_children == null)
{
_service.PopulateOptionCollection(this);
- if (_children == null)
- {
- _children = new ArrayList(1);
- }
+ _children ??= new ArrayList(1);
}
}
{
if (_savedLicenseKeys == null || _savedLicenseKeys[type.AssemblyQualifiedName!] == null)
{
- if (_savedLicenseKeys == null)
- {
- _savedLicenseKeys = new Hashtable();
- }
-
- if (resourceAssembly == null)
- {
- resourceAssembly = Assembly.GetEntryAssembly();
- }
+ _savedLicenseKeys ??= new Hashtable();
+ resourceAssembly ??= Assembly.GetEntryAssembly();
if (resourceAssembly == null)
{
{
ArgumentNullException.ThrowIfNull(context);
- if (_contextStack == null)
- {
- _contextStack = new List<object>();
- }
+ _contextStack ??= new List<object>();
_contextStack.Insert(0, context);
}
{
ArgumentNullException.ThrowIfNull(context);
- if (_contextStack == null)
- {
- _contextStack = new List<object>();
- }
+ _contextStack ??= new List<object>();
_contextStack.Add(context);
}
}
Justification = "GetComponentName is only used to create a nice exception message, and has a fallback when null is returned.")]
private static void ThrowRelationshipNotSupported(MemberRelationship source, MemberRelationship relationship)
{
- string? sourceName = TypeDescriptor.GetComponentName(source.Owner!);
- string? relName = TypeDescriptor.GetComponentName(relationship.Owner!);
- if (sourceName == null)
- {
- sourceName = source.Owner!.ToString();
- }
- if (relName == null)
- {
- relName = relationship.Owner!.ToString();
- }
+ string? sourceName = TypeDescriptor.GetComponentName(source.Owner!) ?? source.Owner!.ToString();
+ string? relName = TypeDescriptor.GetComponentName(relationship.Owner!) ?? relationship.Owner!.ToString();
throw new ArgumentException(SR.Format(SR.MemberRelationshipService_RelationshipNotSupported, sourceName, source.Member.Name, relName, relationship.Member.Name));
}
if (type.Assembly.Location.Length != 0)
{
- if (modulePath == null)
- {
- modulePath = type.Module.FullyQualifiedName;
- }
+ modulePath ??= type.Module.FullyQualifiedName;
string? moduleDir = Path.GetDirectoryName(modulePath);
string licenseFile = moduleDir + "\\" + type.FullName + ".lic";
out License? license,
out string? licenseKey)
{
- if (context == null)
- {
- context = LicenseManager.CurrentContext;
- }
+ context ??= LicenseManager.CurrentContext;
return LicenseManager.ValidateInternalRecursive(
context,
{
lock (s_internalSyncObject)
{
- if (s_context == null)
- {
- s_context = new RuntimeLicenseContext();
- }
+ s_context ??= new RuntimeLicenseContext();
}
}
return s_context;
}
}
- if (culture == null)
- {
- culture = CultureInfo.CurrentCulture;
- }
+ culture ??= CultureInfo.CurrentCulture;
_flagState = default;
}
// Last resort use invariant culture.
- if (Culture == null)
- {
- Culture = CultureInfo.InvariantCulture;
- }
+ Culture ??= CultureInfo.InvariantCulture;
}
else
{
}
}
- if (_converter == null)
- {
- _converter = TypeDescriptor.GetConverter(PropertyType);
- }
+ _converter ??= TypeDescriptor.GetConverter(PropertyType);
}
return _converter;
}
ArgumentNullException.ThrowIfNull(component);
ArgumentNullException.ThrowIfNull(handler);
- if (_valueChangedHandlers == null)
- {
- _valueChangedHandlers = new Dictionary<object, EventHandler?>();
- }
+ _valueChangedHandlers ??= new Dictionary<object, EventHandler?>();
EventHandler? h = _valueChangedHandlers.GetValueOrDefault(component, defaultValue: null);
_valueChangedHandlers[component] = (EventHandler?)Delegate.Combine(h, handler);
name = site.Name;
}
- if (name == null)
- {
- name = component.GetType().FullName;
- }
+ name ??= component.GetType().FullName;
if (t is TargetInvocationException)
{
// If we got here, we return our type-based converter.
if (_converter == null)
{
- if (typeAttr == null)
- {
- typeAttr = (TypeConverterAttribute?)TypeDescriptor.GetAttributes(_type)[typeof(TypeConverterAttribute)];
- }
+ typeAttr ??= (TypeConverterAttribute?)TypeDescriptor.GetAttributes(_type)[typeof(TypeConverterAttribute)];
if (typeAttr != null)
{
t = _type.Assembly.GetType(typeName);
}
- if (t == null)
- {
- t = Type.GetType(typeName);
- }
+ t ??= Type.GetType(typeName);
if (t == null && commaIndex != -1)
{
{
PropertyDescriptor[] propertyArray = ReflectGetExtendedProperties(extenders[idx]);
- if (propertyList == null)
- {
- propertyList = new List<PropertyDescriptor>(propertyArray.Length * extenders.Length);
- }
+ propertyList ??= new List<PropertyDescriptor>(propertyArray.Length * extenders.Length);
for (int propIdx = 0; propIdx < propertyArray.Length; propIdx++)
{
if (td == null && createIfNeeded)
{
td = new ReflectedTypeData(type);
- if (_typeData == null)
- {
- _typeData = new Hashtable();
- }
+ _typeData ??= new Hashtable();
_typeData[type] = td;
}
}
// Interfaces do not derive from object, so we
// must handle the case of no hash entry here.
//
- if (hashEntry == null)
- {
- hashEntry = table[typeof(object)];
- }
+ hashEntry ??= table[typeof(object)];
// If the entry is a type, create an instance of it and then
// replace the entry. This way we only need to create once.
return string.Empty;
}
- if (culture == null)
- {
- culture = CultureInfo.CurrentCulture;
- }
+ culture ??= CultureInfo.CurrentCulture;
- DateTimeFormatInfo? formatInfo = (DateTimeFormatInfo?)culture.GetFormat(typeof(DateTimeFormatInfo));
+ DateTimeFormatInfo formatInfo = (DateTimeFormatInfo)culture.GetFormat(typeof(DateTimeFormatInfo))!;
- return timeOnly.ToString(formatInfo!.ShortTimePattern, CultureInfo.CurrentCulture);
+ return timeOnly.ToString(formatInfo.ShortTimePattern, CultureInfo.CurrentCulture);
}
if (destinationType == typeof(InstanceDescriptor) && value is TimeOnly time)
/// </summary>
public StandardValuesCollection(ICollection? values)
{
- if (values == null)
- {
- values = Array.Empty<object>();
- }
+ values ??= Array.Empty<object>();
if (values is Array a)
{
TypeDescriptionNode? node = (TypeDescriptionNode?)de.Value;
while (node != null && !(node.Provider is ReflectTypeDescriptionProvider))
{
- if (refreshedTypes == null)
- {
- refreshedTypes = new Hashtable();
- }
+ refreshedTypes ??= new Hashtable();
refreshedTypes[nodeType] = nodeType;
node = node.Next;
}
foreach (Type populatedType in populatedTypes)
{
provider.Refresh(populatedType);
- if (refreshedTypes == null)
- {
- refreshedTypes = new Hashtable();
- }
+ refreshedTypes ??= new Hashtable();
refreshedTypes[populatedType] = populatedType;
}
}
[RequiresUnreferencedCode(PropertyDescriptor.PropertyDescriptorPropertyTypeMessage + " " + AttributeCollection.FilterRequiresUnreferencedCodeMessage)]
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[]? attributes)
{
- PropertyDescriptorCollection properties = _primary.GetProperties(attributes);
- if (properties == null)
- {
- properties = _secondary.GetProperties(attributes);
- }
+ PropertyDescriptorCollection properties =
+ _primary.GetProperties(attributes) ??
+ _secondary.GetProperties(attributes);
Debug.Assert(properties != null, "Someone should have handled this");
return properties;
{
if (o is WeakReference wr && !wr.IsAlive)
{
- if (cleanupList == null)
- {
- cleanupList = new List<object>();
- }
-
+ cleanupList ??= new List<object>();
cleanupList.Add(wr);
}
}
return "'" + c.Name + "'";
}
- if (culture == null)
- {
- culture = CultureInfo.CurrentCulture;
- }
+ culture ??= CultureInfo.CurrentCulture;
string sep = culture.TextInfo.ListSeparator + " ";
TypeConverter intConverter = TypeDescriptor.GetConverterTrimUnsafe(typeof(int));
}
// Parse 2 integer values.
- if (culture == null)
- {
- culture = CultureInfo.CurrentCulture;
- }
+ culture ??= CultureInfo.CurrentCulture;
char sep = culture.TextInfo.ListSeparator[0];
string[] tokens = text.Split(sep);
{
if (destinationType == typeof(string))
{
- if (culture == null)
- {
- culture = CultureInfo.CurrentCulture;
- }
+ culture ??= CultureInfo.CurrentCulture;
string sep = culture.TextInfo.ListSeparator + " ";
TypeConverter intConverter = TypeDescriptor.GetConverterTrimUnsafe(typeof(int));
}
// Parse 4 integer values.
- if (culture == null)
- {
- culture = CultureInfo.CurrentCulture;
- }
+ culture ??= CultureInfo.CurrentCulture;
char sep = culture.TextInfo.ListSeparator[0];
string[] tokens = text.Split(sep);
{
if (destinationType == typeof(string))
{
- if (culture == null)
- {
- culture = CultureInfo.CurrentCulture;
- }
+ culture ??= CultureInfo.CurrentCulture;
string sep = culture.TextInfo.ListSeparator + " ";
TypeConverter intConverter = TypeDescriptor.GetConverterTrimUnsafe(typeof(int));
}
// Parse 2 integer values.
- if (culture == null)
- {
- culture = CultureInfo.CurrentCulture;
- }
+ culture ??= CultureInfo.CurrentCulture;
char sep = culture.TextInfo.ListSeparator[0];
string[] tokens = text.Split(sep);
{
if (destinationType == typeof(string))
{
- if (culture == null)
- {
- culture = CultureInfo.CurrentCulture;
- }
+ culture ??= CultureInfo.CurrentCulture;
string sep = culture.TextInfo.ListSeparator + " ";
TypeConverter intConverter = TypeDescriptor.GetConverterTrimUnsafe(typeof(int));
}
// Parse 2 integer values.
- if (culture == null)
- {
- culture = CultureInfo.CurrentCulture;
- }
+ culture ??= CultureInfo.CurrentCulture;
char sep = culture.TextInfo.ListSeparator[0];
string[] tokens = text.Split(sep);
{
if (destinationType == typeof(string))
{
- if (culture == null)
- {
- culture = CultureInfo.CurrentCulture;
- }
+ culture ??= CultureInfo.CurrentCulture;
string sep = culture.TextInfo.ListSeparator + " ";
TypeConverter floatConverter = TypeDescriptor.GetConverterTrimUnsafe(typeof(float));
{
throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(name)), nameof(name));
}
- if (_metadataItems == null)
- {
- _metadataItems = new List<Tuple<string, object>>();
- }
+
+ _metadataItems ??= new List<Tuple<string, object>>();
_metadataItems.Add(Tuple.Create(name, value));
return this;
}
throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(name)), nameof(name));
}
- if (_metadataItemFuncs == null)
- {
- _metadataItemFuncs = new List<Tuple<string, Func<Type, object>>>();
- }
+ _metadataItemFuncs ??= new List<Tuple<string, Func<Type, object>>>();
_metadataItemFuncs.Add(Tuple.Create(name, getValueFromPartType));
return this;
}
internal void BuildAttributes(Type type, ref List<Attribute> attributes)
{
- if (attributes == null)
- {
- attributes = new List<Attribute>();
- }
+ attributes ??= new List<Attribute>();
var contractName = (_getContractNameFromPartType != null) ? _getContractNameFromPartType(type) : _contractName;
attributes.Add(new ExportAttribute(contractName, _contractType));
{
throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(name)), nameof(name));
}
- if (_metadataConstraintItems == null)
- {
- _metadataConstraintItems = new List<Tuple<string, object>>();
- }
+
+ _metadataConstraintItems ??= new List<Tuple<string, object>>();
_metadataConstraintItems.Add(Tuple.Create(name, value));
return this;
}
throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(name)), nameof(name));
}
- if (_metadataConstraintItemFuncs == null)
- {
- _metadataConstraintItemFuncs = new List<Tuple<string, Func<Type, object>>>();
- }
+ _metadataConstraintItemFuncs ??= new List<Tuple<string, Func<Type, object>>>();
_metadataConstraintItemFuncs.Add(Tuple.Create(name, getConstraintValueFromPartType));
return this;
}
{
importAttribute = new ImportManyAttribute(contractName);
}
- if (attributes == null)
- {
- attributes = new List<Attribute>();
- }
- attributes.Add(importAttribute);
+ attributes ??= new List<Attribute>();
+ attributes.Add(importAttribute);
//Add metadata attributes from direct specification
if (_metadataConstraintItems != null)
throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(name)), nameof(name));
}
- if (_metadataItems == null)
- {
- _metadataItems = new List<Tuple<string, object>>();
- }
+ _metadataItems ??= new List<Tuple<string, object>>();
_metadataItems.Add(Tuple.Create(name, value));
return this;
}
throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(name)), nameof(name));
}
- if (_metadataItemFuncs == null)
- {
- _metadataItemFuncs = new List<Tuple<string, Func<Type, object>>>();
- }
+ _metadataItemFuncs ??= new List<Tuple<string, Func<Type, object>>>();
_metadataItemFuncs.Add(Tuple.Create(name, getValueFromPartType));
return this;
}
private static void ConfigureConstructorAttributes(ConstructorInfo constructorInfo, ref List<Tuple<object, List<Attribute>>> configuredMembers, Action<ParameterInfo, ImportConventionBuilder> configureConstuctorImports)
{
- if (configuredMembers == null)
- {
- configuredMembers = new List<Tuple<object, List<Attribute>>>();
- }
+ configuredMembers ??= new List<Tuple<object, List<Attribute>>>();
// Make its attribute
configuredMembers.Add(Tuple.Create((object)constructorInfo, s_importingConstructorList));
// Run through the import specifications see if any match
foreach (Tuple<Predicate<PropertyInfo>, Action<PropertyInfo, ImportConventionBuilder>> importSpecification in _propertyImports)
{
- if (underlyingPi == null)
- {
- underlyingPi = pi.DeclaringType.GetRuntimeProperty(pi.Name);
- }
+ underlyingPi ??= pi.DeclaringType.GetRuntimeProperty(pi.Name);
+
if (importSpecification.Item1 != null && importSpecification.Item1(underlyingPi))
{
var importBuilder = new ImportConventionBuilder();
// Run through the export specifications see if any match
foreach (Tuple<Predicate<PropertyInfo>, Action<PropertyInfo, ExportConventionBuilder>, Type> exportSpecification in _propertyExports)
{
- if (underlyingPi == null)
- {
- underlyingPi = pi.DeclaringType.GetRuntimeProperty(pi.Name);
- }
+ underlyingPi ??= pi.DeclaringType.GetRuntimeProperty(pi.Name);
if (exportSpecification.Item1 != null && exportSpecification.Item1(underlyingPi))
{
if (attributes != null)
{
- if (configuredMembers == null)
- {
- configuredMembers = new List<Tuple<object, List<Attribute>>>();
- }
+ configuredMembers ??= new List<Tuple<object, List<Attribute>>>();
configuredMembers.Add(Tuple.Create((object)pi, attributes));
}
{
var lambdaExpression = (LambdaExpression)parameter;
Delegate importDelegate = lambdaExpression.Compile();
- if (_importBuilders == null)
- {
- _importBuilders = new Dictionary<ParameterInfo, Action<ImportConventionBuilder>>();
- }
+ _importBuilders ??= new Dictionary<ParameterInfo, Action<ImportConventionBuilder>>();
_importBuilders.Add(parameterInfos[index], (Action<ImportConventionBuilder>)importDelegate);
++index;
}
throw new ArgumentNullException(nameof(action));
}
- if (_nonPrerequisiteActions == null)
- _nonPrerequisiteActions = new List<Action>();
+ _nonPrerequisiteActions ??= new List<Action>();
_nonPrerequisiteActions.Add(action);
}
throw new ArgumentNullException(nameof(action));
}
- if (_postCompositionActions == null)
- _postCompositionActions = new List<Action>();
+ _postCompositionActions ??= new List<Action>();
_postCompositionActions.Add(action);
}
public void Add(int index, object value)
{
- if (_elements == null)
- _elements = new Element[ElementsCapacity];
+ _elements ??= new Element[ElementsCapacity];
var newElement = new Element { Index = index, Value = value };
}
}
- if (_overflow == null)
- _overflow = new SmallSparseInitonlyArray();
+ _overflow ??= new SmallSparseInitonlyArray();
_overflow.Add(index, value);
}
_constructor = GetConstructorInfoFromGenericType(_partType);
}
- if (_constructor == null)
- _constructor = _partType.DeclaredConstructors
- .FirstOrDefault(ci => ci.IsPublic && !(ci.IsStatic || ci.GetParameters().Any()));
+ _constructor ??= _partType.DeclaredConstructors.FirstOrDefault(ci => ci.IsPublic && !(ci.IsStatic || ci.GetParameters().Any()));
if (_constructor == null)
{
Type type = GetType();
- if (_context == null)
- {
- _context = new SettingsContext();
- }
+ _context ??= new SettingsContext();
_context["GroupName"] = type.FullName;
_context["SettingsKey"] = SettingsKey;
_context["SettingsClassType"] = type;
PropertyInfo[] properties = SettingsFilter(type.GetProperties(BindingFlags.Instance | BindingFlags.Public));
_classAttributes = type.GetCustomAttributes(false);
- if (_settings == null)
- {
- _settings = new SettingsPropertyCollection();
- }
-
- if (_providers == null)
- {
- _providers = new SettingsProviderCollection();
- }
+ _settings ??= new SettingsPropertyCollection();
+ _providers ??= new SettingsProviderCollection();
for (int i = 0; i < properties.Length; i++)
{
// remove the LocationSectionRecord from the list
_parent._locationSections.RemoveAt(i);
- if (locationSubPathInputs == null) locationSubPathInputs = new ArrayList();
+ locationSubPathInputs ??= new ArrayList();
locationSubPathInputs.Add(locationSectionRecord);
}
// First add all indirect inputs per configKey to a local list.
// We will sort all lists after the while loop.
- if (indirectLocationInputs == null)
- indirectLocationInputs = new Dictionary<string, List<SectionInput>>(1);
+ indirectLocationInputs ??= new Dictionary<string, List<SectionInput>>(1);
string configKey = locationSectionRecord.SectionXmlInfo.ConfigKey;
else
{
// Remove the entire section record
- if (removes == null) removes = new List<SectionRecord>();
+ removes ??= new List<SectionRecord>();
removes.Add(sectionRecord);
}
// Cache the results.
if (cacheResults)
{
- if (sectionRecord == null) sectionRecord = EnsureSectionRecord(configKey, true);
+ sectionRecord ??= EnsureSectionRecord(configKey, true);
sectionRecord.Result = tmpResult;
if (getRuntimeObject) sectionRecord.ResultRuntimeObject = tmpResultRuntimeObject;
}
}
- if (factoryRecord.Factory == null)
- {
- factoryRecord.Factory = rootFactoryRecord.Factory;
- }
+ factoryRecord.Factory ??= rootFactoryRecord.Factory;
isRootDeclaredHere = ReferenceEquals(this, rootConfigRecord);
}
// Check if the definition is allowed
- if (factoryRecord == null)
- factoryRecord = FindFactoryRecord(locationSectionRecord.ConfigKey, true);
+ factoryRecord ??= FindFactoryRecord(locationSectionRecord.ConfigKey, true);
if (factoryRecord.HasErrors) continue;
lock (this)
{
- if (_sectionRecords == null) _sectionRecords = new Hashtable();
- else sectionRecord = GetSectionRecord(configKey, permitErrors);
+ if (_sectionRecords == null)
+ {
+ _sectionRecords = new Hashtable();
+ }
+ else
+ {
+ sectionRecord = GetSectionRecord(configKey, permitErrors);
+ }
if (sectionRecord == null)
{
if (_flags[SupportsChangeNotifications])
{
- if (ConfigStreamInfo.CallbackDelegate == null)
- ConfigStreamInfo.CallbackDelegate = OnStreamChanged;
-
- callbackDelegate = ConfigStreamInfo.CallbackDelegate;
+ callbackDelegate = ConfigStreamInfo.CallbackDelegate ??= OnStreamChanged;
}
}
// Requires the hierarchy lock to be acquired (hl)
internal void HlAddChild(string configName, BaseConfigurationRecord child)
{
- if (_children == null) _children = new Hashtable(StringComparer.OrdinalIgnoreCase);
+ _children ??= new Hashtable(StringComparer.OrdinalIgnoreCase);
_children.Add(configName, child);
}
// (e.g. if we're in machine.config)
if (!_parent.IsRootConfig) return;
- if (factoryList == null) factoryList = EnsureFactories();
+ factoryList ??= EnsureFactories();
// Look to see if we already have a factory for "configProtectedData"
FactoryRecord factoryRecord = (FactoryRecord)factoryList[ReservedSectionProtectedConfiguration];
if (string.IsNullOrEmpty(ProductName) && (mainType != null)) ProductName = mainType.Name.Trim();
// give up, return empty string
- if (ProductName == null) ProductName = string.Empty;
+ ProductName ??= string.Empty;
}
if (string.IsNullOrEmpty(_companyName))
}
}
- internal static IInternalConfigConfigurationFactory ConfigFactory
- {
- get
- {
- if (s_configFactory == null)
- {
- s_configFactory = TypeUtil.CreateInstance<IInternalConfigConfigurationFactory>(InternalConfigConfigurationFactoryTypeName);
- }
- return s_configFactory;
- }
- }
+ internal static IInternalConfigConfigurationFactory ConfigFactory =>
+ s_configFactory ??= TypeUtil.CreateInstance<IInternalConfigConfigurationFactory>(InternalConfigConfigurationFactoryTypeName);
private ClientSettingsConfigurationHost() { }
if (source._lockedAttributesList != null)
{
// Mark entry as from the parent - read only
- if (_lockedAttributesList == null)
- {
- _lockedAttributesList = new ConfigurationLockCollection(this,
- ConfigurationLockCollectionType.LockedAttributes);
- }
+ _lockedAttributesList ??= new ConfigurationLockCollection(this,
+ ConfigurationLockCollectionType.LockedAttributes);
foreach (string key in source._lockedAttributesList)
_lockedAttributesList.Add(key, ConfigurationValueFlags.Inherited);
if (source._lockedAllExceptAttributesList != null)
{
- if (_lockedAllExceptAttributesList == null)
- {
- _lockedAllExceptAttributesList = new ConfigurationLockCollection(this,
- ConfigurationLockCollectionType.LockedExceptionList, string.Empty,
- source._lockedAllExceptAttributesList);
- }
+ _lockedAllExceptAttributesList ??= new ConfigurationLockCollection(this,
+ ConfigurationLockCollectionType.LockedExceptionList, string.Empty,
+ source._lockedAllExceptAttributesList);
StringCollection intersectionCollection = IntersectLockCollections(_lockedAllExceptAttributesList,
source._lockedAllExceptAttributesList);
if (source._lockedElementsList != null)
{
- if (_lockedElementsList == null)
- {
- _lockedElementsList = new ConfigurationLockCollection(this,
- ConfigurationLockCollectionType.LockedElements);
- }
+ _lockedElementsList ??= new ConfigurationLockCollection(this,
+ ConfigurationLockCollectionType.LockedElements);
ConfigurationElementCollection collection = null;
if (Properties.DefaultCollectionProperty != null)
// Default collections don't know their tag name
collection.InternalElementTagName = source.ElementTagName;
//point to the same instance of the collection from parent
- if (collection._lockedElementsList == null)
- collection._lockedElementsList = _lockedElementsList;
+ collection._lockedElementsList ??= _lockedElementsList;
}
}
{
collection.InternalElementTagName = parentElement.ElementTagName;
// Default collections don't know there tag name
- if (collection._lockedElementsList == null)
- collection._lockedElementsList = _lockedElementsList;
+ collection._lockedElementsList ??= _lockedElementsList;
}
}
// NOTE[ Thread Safety ]: Non-guarded access to static variable - since this code is called only from CreatePropertyBagFromType
// which in turn is done onle once per type and is guarded by the s_propertyBag.SyncRoot then this call is thread safe as well
- if (s_perTypeValidators == null) s_perTypeValidators = new Dictionary<Type, ConfigurationValidatorBase>();
+ s_perTypeValidators ??= new Dictionary<Type, ConfigurationValidatorBase>();
// A type validator should be cached only once. If it isn't then attribute parsing is done more then once which should be avoided
Debug.Assert(!s_perTypeValidators.ContainsKey(type));
if (lockedAttributesList != null)
{
- if (_lockedAttributesList == null)
- {
- _lockedAttributesList = new ConfigurationLockCollection(this,
- ConfigurationLockCollectionType.LockedAttributes);
- }
+ _lockedAttributesList ??= new ConfigurationLockCollection(this,
+ ConfigurationLockCollectionType.LockedAttributes);
+
foreach (
string key in
ParseLockedAttributes(lockedAttributesList, ConfigurationLockCollectionType.LockedAttributes))
if (lockedElementList != null)
{
- if (_lockedElementsList == null)
- {
- _lockedElementsList = new ConfigurationLockCollection(this,
- ConfigurationLockCollectionType.LockedElements);
- }
+ _lockedElementsList ??= new ConfigurationLockCollection(this,
+ ConfigurationLockCollectionType.LockedElements);
ConfigurationLockCollection localLockedElementList = ParseLockedAttributes(lockedElementList,
ConfigurationLockCollectionType.LockedElements);
if (defaultCollectionProperty != null)
{
defaultCollection = (ConfigurationElement)this[defaultCollectionProperty];
- if (_lockedElementsList == null)
- {
- _lockedElementsList = new ConfigurationLockCollection(this,
- ConfigurationLockCollectionType.LockedElements);
- }
+ _lockedElementsList ??= new ConfigurationLockCollection(this,
+ ConfigurationLockCollectionType.LockedElements);
+
defaultCollection._lockedElementsList = _lockedElementsList;
if (_lockedAllExceptElementsList == null)
{
{
private static volatile IConfigurationManagerInternal s_instance;
- internal static IConfigurationManagerInternal Instance
- {
- get
- {
- if (s_instance == null)
- {
- s_instance = new ConfigurationManagerInternal();
- }
-
- return s_instance;
- }
- }
+ internal static IConfigurationManagerInternal Instance => s_instance ??= new ConfigurationManagerInternal();
}
}
{
HandlerBase.CheckForChildNodes(child);
string key = HandlerBase.RemoveRequiredAttribute(child, KeyAttributeName);
- string value;
- if (ValueRequired)
- value = HandlerBase.RemoveRequiredAttribute(child, ValueAttributeName);
- else
- value = HandlerBase.RemoveAttribute(child, ValueAttributeName);
+ string value = ValueRequired ?
+ HandlerBase.RemoveRequiredAttribute(child, ValueAttributeName) :
+ HandlerBase.RemoveAttribute(child, ValueAttributeName);
HandlerBase.CheckForUnrecognizedAttributes(child);
- if (value == null)
- value = "";
-
- res[key] = value;
+ res[key] = value ?? "";
}
else if (child.Name == "remove")
{
Debug.Assert(e != null, "e != null");
// Create on demand
- if (errors == null) errors = new List<ConfigurationException>();
+ errors ??= new List<ConfigurationException>();
ConfigurationErrorsException ce = e as ConfigurationErrorsException;
if (ce == null) errors.Add(e);
}
}
- private XmlEscaper Escaper
- {
- get
- {
- if (_escaper == null)
- {
- _escaper = new XmlEscaper();
- }
-
- return _escaper;
- }
- }
+ private XmlEscaper Escaper => _escaper ??= new XmlEscaper();
/// <summary>
/// We maintain a single instance of the ClientSettingsStore per instance of provider.
}
}
- if (serializedValue == null)
- {
- serializedValue = string.Empty;
- }
+ serializedValue ??= string.Empty;
// We need to escape string serialized values
if (setting.SerializeAs == SettingsSerializeAs.String)
// Record all location tags in the config file, even if they are empty.
protected override void AddLocation(string locationSubPath)
{
- if (_locationTags == null) _locationTags = new Hashtable(StringComparer.OrdinalIgnoreCase);
+ _locationTags ??= new Hashtable(StringComparer.OrdinalIgnoreCase);
_locationTags[locationSubPath] = locationSubPath;
}
if (addToConfigSourceUpdates)
{
- if (configSourceUpdates == null) configSourceUpdates = new ArrayList();
+ configSourceUpdates ??= new ArrayList();
configSourceUpdates.Add(definitionUpdate);
}
}
if ((prop.Name != "name") && (prop.Name != "type"))
{
if (_propertyNameCollection.Get(prop.Name) != null) continue;
- if (removeList == null)
- removeList = new ArrayList();
+ removeList ??= new ArrayList();
if ((Values.GetConfigValue(prop.Name).ValueFlags & ConfigurationValueFlags.Locked) != 0)
continue;
private XmlNode _valueXml;
private bool _isModified;
- protected internal override ConfigurationPropertyCollection Properties
- {
- get
- {
- if (_properties == null)
- {
- _properties = new ConfigurationPropertyCollection();
- }
-
- return _properties;
- }
- }
+ protected internal override ConfigurationPropertyCollection Properties =>
+ _properties ??= new ConfigurationPropertyCollection();
public XmlNode ValueXml
{
}
}
- if (type == null)
- {
- type = GetImplicitType(typeString);
- }
-
- return type;
+ return type ?? GetImplicitType(typeString);
}
// Ask the host to get the type specified by typeString. If it fails, try to retrieve it
}
}
- if (type == null)
- {
- type = GetImplicitType(typeString);
- }
-
- return type;
+ return type ?? GetImplicitType(typeString);
}
internal static T CreateInstance<T>(string typeString)
if (!alwaysIntercept && StringUtil.EqualsIgnoreCase(oldStreamname, newStreamname)) return;
- if (_streams == null) _streams = new HybridDictionary(true);
+ _streams ??= new HybridDictionary(true);
_streams[oldStreamname] = new StreamUpdate(newStreamname);
}
private void ResetCachedStringWriter()
{
if (_cachedStringWriter == null)
+ {
_cachedStringWriter = new StringWriter(new StringBuilder(64), CultureInfo.InvariantCulture);
- else _cachedStringWriter.GetStringBuilder().Length = 0;
+ }
+ else
+ {
+ _cachedStringWriter.GetStringBuilder().Length = 0;
+ }
}
// Copy a configuration section to a string, and advance the reader.
if (ConsolePal.TryGetCursorPosition(out int left, out int top, reinitializeForRead: true) &&
left == 0 && top > 0)
{
- if (s_clearToEol == null)
- {
- s_clearToEol = ConsolePal.TerminalFormatStrings.Instance.ClrEol ?? string.Empty;
- }
+ s_clearToEol ??= ConsolePal.TerminalFormatStrings.Instance.ClrEol ?? string.Empty;
// Move to end of previous line
ConsolePal.SetCursorPosition(ConsolePal.WindowWidth - 1, top - 1);
/// <returns>The formatted string.</returns>
public static string Evaluate(string format, FormatParam arg)
{
- FormatParam[]? args = t_cachedOneElementArgsArray;
- if (args == null)
- {
- t_cachedOneElementArgsArray = args = new FormatParam[1];
- }
+ FormatParam[] args = t_cachedOneElementArgsArray ??= new FormatParam[1];
args[0] = arg;
/// <returns>The formatted string.</returns>
public static string Evaluate(string format, FormatParam arg1, FormatParam arg2)
{
- FormatParam[]? args = t_cachedTwoElementArgsArray;
- if (args == null)
- {
- t_cachedTwoElementArgsArray = args = new FormatParam[2];
- }
+ FormatParam[] args = t_cachedTwoElementArgsArray ??= new FormatParam[2];
args[0] = arg1;
args[1] = arg2;
}
[RequiresUnreferencedCode("PropertyDescriptor's PropertyType cannot be statically discovered. The public parameterless constructor or the 'Default' static field may be trimmed from the Attribute's Type.")]
- PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[]? attributes)
- {
- if (_propertyDescriptors == null)
- {
- _propertyDescriptors = new PropertyDescriptorCollection(null);
- }
- return _propertyDescriptors;
- }
+ PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[]? attributes) =>
+ _propertyDescriptors ??= new PropertyDescriptorCollection(null);
object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor? pd)
{
get { return _name; }
set
{
- if (value == null)
- {
- value = string.Empty;
- }
+ value ??= string.Empty;
if (string.IsNullOrEmpty(value) && (Table != null) && InCollection)
{
get { return _caption ?? _columnName; }
set
{
- if (value == null)
- {
- value = string.Empty;
- }
+ value ??= string.Empty;
if (_caption == null || string.Compare(_caption, value, true, Locale) != 0)
{
long logScopeId = DataCommonEventSource.Log.EnterScope("<ds.DataColumn.set_ColumnName|API> {0}, '{1}'", ObjectID, value);
try
{
- if (value == null)
- {
- value = string.Empty;
- }
+ value ??= string.Empty;
if (string.Compare(_columnName, value, true, Locale) != 0)
{
{
get
{
- if (_encodedColumnName == null)
- {
- _encodedColumnName = XmlConvert.EncodeLocalName(ColumnName);
- }
+ _encodedColumnName ??= XmlConvert.EncodeLocalName(ColumnName);
Debug.Assert(!string.IsNullOrEmpty(_encodedColumnName));
return _encodedColumnName;
get { return _columnPrefix; }
set
{
- if (value == null)
- {
- value = string.Empty;
- }
+ value ??= string.Empty;
DataCommonEventSource.Log.Trace("<ds.DataColumn.set_Prefix|API> {0}, '{1}'", ObjectID, value);
{
long logScopeId = DataCommonEventSource.Log.EnterScope("<ds.DataColumn.set_Expression|API> {0}, '{1}'", ObjectID, value);
- if (value == null)
- {
- value = string.Empty;
- }
+ value ??= string.Empty;
try
{
{
if (value != null && value != DBNull.Value && ((string)value).Length > MaxLength)
{
- if (errorText == null)
- {
- errorText = ExceptionBuilder.MaxLengthViolationText(ColumnName);
- }
+ errorText ??= ExceptionBuilder.MaxLengthViolationText(ColumnName);
dr.RowError = errorText;
dr.SetColumnError(this, errorText);
error = true;
{
if (!DataStorage.IsObjectNull(value) && ((SqlString)value).Value.Length > MaxLength)
{
- if (errorText == null)
- {
- errorText = ExceptionBuilder.MaxLengthViolationText(ColumnName);
- }
+ errorText ??= ExceptionBuilder.MaxLengthViolationText(ColumnName);
dr.RowError = errorText;
dr.SetColumnError(this, errorText);
error = true;
OnPropertyChanging(new PropertyChangedEventArgs(name));
}
- private DataStorage InsureStorage()
- {
- if (_storage == null)
- {
- _storage = DataStorage.CreateStorage(this, _dataType, _storageType);
- }
-
- return _storage;
- }
+ private DataStorage InsureStorage() =>
+ _storage ??= DataStorage.CreateStorage(this, _dataType, _storageType);
internal void SetCapacity(int capacity)
{
}
else
{
- if (_errorList == null)
- {
- _errorList = new ColumnError[initialCapacity];
- }
+ _errorList ??= new ColumnError[initialCapacity];
int i = IndexOf(column);
_errorList[i]._column = column;
_errorList[i]._error = error;
long logScopeId = DataCommonEventSource.Log.EnterScope("<ds.DataRelation.set_RelationName|API> {0}, '{1}'", ObjectID, value);
try
{
- if (value == null)
- {
- value = string.Empty;
- }
+ value ??= string.Empty;
CultureInfo locale = (_dataSet != null ? _dataSet.Locale : CultureInfo.CurrentCulture);
if (string.Compare(_relationName, value, true, locale) != 0)
long logScopeId = DataCommonEventSource.Log.EnterScope("<ds.DataRow.SetColumnError|API> {0}, column={1}, error='{2}'", _objectID, column.ObjectID, error);
try
{
- if (_error == null) _error = new DataError();
+ _error ??= new DataError();
if (GetColumnError(column) != error)
{
_error.SetColumnError(column, error);
public string GetColumnError(DataColumn column)
{
CheckColumn(column);
- if (_error == null) _error = new DataError();
+ _error ??= new DataError();
return _error.GetColumnError(column);
}
{
lock (_defaultViewManagerLock)
{
- if (_defaultViewManager == null)
- {
- _defaultViewManager = new DataViewManager(this, true);
- }
+ _defaultViewManager ??= new DataViewManager(this, true);
}
}
+
return _defaultViewManager;
}
}
set
{
DataCommonEventSource.Log.Trace("<ds.DataSet.set_Namespace|API> {0}, '{1}'", ObjectID, value);
- if (value == null)
- {
- value = string.Empty;
- }
+ value ??= string.Empty;
if (value != _namespaceURI)
{
get { return _datasetPrefix; }
set
{
- if (value == null)
- {
- value = string.Empty;
- }
+ value ??= string.Empty;
if ((XmlConvert.DecodeName(value) == value) && (XmlConvert.EncodeName(value) != value))
{
}
else
{
- if (xmlload == null)
- {
- xmlload = new XmlDataLoader(this, fIsXdr, topNode, false);
- }
+ xmlload ??= new XmlDataLoader(this, fIsXdr, topNode, false);
xmlload.LoadData(reader);
topNodeIsProcessed = true; // we process the topnode
// now top node contains the data part
xdoc.AppendChild(topNode);
- if (xmlload == null)
- {
- xmlload = new XmlDataLoader(this, fIsXdr, topNode, false);
- }
+ xmlload ??= new XmlDataLoader(this, fIsXdr, topNode, false);
if (!isEmptyDataSet && !topNodeIsProcessed)
{
}
else
{
- if (xmlload == null)
- {
- xmlload = new XmlDataLoader(this, fIsXdr, topNode, mode == XmlReadMode.IgnoreSchema);
- }
+ xmlload ??= new XmlDataLoader(this, fIsXdr, topNode, mode == XmlReadMode.IgnoreSchema);
xmlload.LoadData(reader);
}
} //end of the while
// now top node contains the data part
xdoc.AppendChild(topNode);
- if (xmlload == null)
- xmlload = new XmlDataLoader(this, fIsXdr, mode == XmlReadMode.IgnoreSchema);
+ xmlload ??= new XmlDataLoader(this, fIsXdr, mode == XmlReadMode.IgnoreSchema);
if (mode == XmlReadMode.DiffGram)
{
long logScopeId = DataCommonEventSource.Log.EnterScope("<ds.DataTable.set_TableName|API> {0}, value='{1}'", ObjectID, value);
try
{
- if (value == null)
- {
- value = string.Empty;
- }
+ value ??= string.Empty;
CultureInfo currentLocale = Locale;
if (string.Compare(_tableName, value, true, currentLocale) != 0)
{
get { return _tablePrefix; }
set
{
- if (value == null)
- {
- value = string.Empty;
- }
+ value ??= string.Empty;
DataCommonEventSource.Log.Trace("<ds.DataTable.set_Prefix|API> {0}, value='{1}'", ObjectID, value);
if ((XmlConvert.DecodeName(value) == value) && (XmlConvert.EncodeName(value) != value))
{
private DataTable CloneHierarchy(DataTable sourceTable, DataSet ds, Hashtable? visitedMap)
{
- if (visitedMap == null)
- {
- visitedMap = new Hashtable();
- }
+ visitedMap ??= new Hashtable();
if (visitedMap.Contains(sourceTable))
{
return ((DataTable)visitedMap[sourceTable]!);
}
else
{
- if (xmlload == null)
- {
- xmlload = new XmlDataLoader(this, fIsXdr, topNode, false);
- }
+ xmlload ??= new XmlDataLoader(this, fIsXdr, topNode, false);
xmlload.LoadData(reader);
ret = fSchemaFound ? XmlReadMode.ReadSchema : XmlReadMode.IgnoreSchema;
}
throw ExceptionBuilder.DataTableInferenceNotSupported();
}
- if (xmlload == null)
- xmlload = new XmlDataLoader(this, fIsXdr, false);
+ xmlload ??= new XmlDataLoader(this, fIsXdr, false);
// so we InferSchema
if (!fDiffsFound)
{
throw ExceptionBuilder.DataTableInferenceNotSupported();
}
- if (xmlload == null)
- {
- xmlload = new XmlDataLoader(this, fIsXdr, topNode, mode == XmlReadMode.IgnoreSchema);
- }
+ xmlload ??= new XmlDataLoader(this, fIsXdr, topNode, mode == XmlReadMode.IgnoreSchema);
xmlload.LoadData(reader);
}
} //end of the while
// now top node contains the data part
xdoc.AppendChild(topNode);
- if (xmlload == null)
- {
- xmlload = new XmlDataLoader(this, fIsXdr, mode == XmlReadMode.IgnoreSchema);
- }
+ xmlload ??= new XmlDataLoader(this, fIsXdr, mode == XmlReadMode.IgnoreSchema);
if (mode == XmlReadMode.DiffGram)
{
#endif
#if DEBUG
- if (t_usedTables == null)
- t_usedTables = new List<DataTable>();
- t_usedTables.Add(table);
+ (t_usedTables ??= new List<DataTable>()).Add(table);
#endif
_targetTable = table;
table._rowDiffId = null;
#if DEBUG
// initialize list of tables out of current tables
// note: it might remain empty (still initialization is needed for assert to operate)
- if (RowDiffIdUsageSection.t_usedTables == null)
- RowDiffIdUsageSection.t_usedTables = new List<DataTable>();
+ RowDiffIdUsageSection.t_usedTables ??= new List<DataTable>();
#endif
for (int tableIndex = 0; tableIndex < ds.Tables.Count; ++tableIndex)
{
// assert scope has been created either with RowDiffIdUsageSection.Prepare or DSRowDiffIdUsageSection.Prepare
RowDiffIdUsageSection.Assert("missing call to RowDiffIdUsageSection.Prepare or DSRowDiffIdUsageSection.Prepare");
- if (_rowDiffId == null)
- {
- _rowDiffId = new Hashtable();
- }
- return _rowDiffId;
+ return _rowDiffId ??= new Hashtable();
}
}
internal void AddDependentColumn(DataColumn expressionColumn)
{
- if (_dependentColumns == null)
- {
- _dependentColumns = new List<DataColumn>();
- }
+ _dependentColumns ??= new List<DataColumn>();
if (!_dependentColumns.Contains(expressionColumn))
{
// each time, we just get schema table of current table for once, no need to recreate each time, if schema is changed, reader is already
// is invalid
- if (_schemaTable == null)
- {
- _schemaTable = GetSchemaTableFromDataTable(_currentDataTable);
- }
-
- return _schemaTable;
+ return _schemaTable ??= GetSchemaTableFromDataTable(_currentDataTable);
}
public override bool NextResult()
_currentDataTable = _tables[++_tableCounter];
- if (_listener != null)
- {
- _listener.UpdataTable(_currentDataTable); // it will unsubscribe from preveous tables events and subscribe to new table's events
- }
+ _listener?.UpdataTable(_currentDataTable); // it will unsubscribe from preveous tables events and subscribe to new table's events
_schemaTable = null;
_rowCounter = -1;
throw ExceptionBuilder.SetRowStateFilter();
}
- if (Sort == null)
- {
- Sort = string.Empty;
- }
-
- if (RowFilter == null)
- {
- RowFilter = string.Empty;
- }
+ Sort ??= string.Empty;
+ RowFilter ??= string.Empty;
DataExpression newFilter = new DataExpression(table, RowFilter);
SetIndex(Sort, RowState, newFilter);
[RequiresUnreferencedCode(Select.RequiresUnreferencedCodeMessage)]
set
{
- if (value == null)
- {
- value = string.Empty;
- }
+ value ??= string.Empty;
if (_rowFilter != value)
{
get { return _sort; }
set
{
- if (value == null)
- {
- value = string.Empty;
- }
+ value ??= string.Empty;
if (_sort != value)
{
//
if (addPrimaryKeys && schemaRow.IsKey)
{
- if (keys == null)
- {
- keys = new DataColumn[schemaRows.Length];
- }
+ keys ??= new DataColumn[schemaRows.Length];
keys[keyCount++] = dataColumn;
// see case 3 above, we do want dataColumn.AllowDBNull not schemaRow.AllowDBNull
if (offset < 0 || offset >= Length)
throw new ArgumentOutOfRangeException(nameof(offset));
- if (_rgbWorkBuf == null)
- _rgbWorkBuf = new byte[1];
+ _rgbWorkBuf ??= new byte[1];
Read(offset, _rgbWorkBuf, 0, 1);
return _rgbWorkBuf[0];
}
set
{
- if (_rgbWorkBuf == null)
- _rgbWorkBuf = new byte[1];
+ _rgbWorkBuf ??= new byte[1];
+
_rgbWorkBuf[0] = value;
Write(offset, _rgbWorkBuf, 0, 1);
}
if (offset < 0 || offset >= Length)
throw new ArgumentOutOfRangeException(nameof(offset));
- if (_rgchWorkBuf == null)
- _rgchWorkBuf = new char[1];
+ _rgchWorkBuf ??= new char[1];
Read(offset, _rgchWorkBuf, 0, 1);
return _rgchWorkBuf[0];
}
set
{
- if (_rgchWorkBuf == null)
- _rgchWorkBuf = new char[1];
+ _rgchWorkBuf ??= new char[1];
+
_rgchWorkBuf[0] = value;
Write(offset, _rgchWorkBuf, 0, 1);
}
private void SetCompareInfo()
{
Debug.Assert(!IsNull);
- if (m_cmpInfo == null)
- m_cmpInfo = (CultureInfo.GetCultureInfo(m_lcid)).CompareInfo;
+ m_cmpInfo ??= (CultureInfo.GetCultureInfo(m_lcid)).CompareInfo;
}
public CompareInfo CompareInfo
return m_cmpInfo!;
}
else
+ {
throw new SqlNullValueException();
+ }
}
}
get
{
if (!IsNull)
+ {
return m_flag;
+ }
else
+ {
throw new SqlNullValueException();
+ }
}
}
}
// NOTE: Maintaining createSqlReaderMethodInfo private field member to preserve the serialization of the class
- if (_createSqlReaderMethodInfo == null)
- {
- _createSqlReaderMethodInfo = CreateSqlReaderMethodInfo;
- }
+ _createSqlReaderMethodInfo ??= CreateSqlReaderMethodInfo;
Debug.Assert(_createSqlReaderMethodInfo != null, "MethodInfo reference for XmlReader.CreateSqlReader should not be null.");
XmlReader r = CreateSqlXmlReader(stream);
return CreateSqlReaderMethodInfo.CreateDelegate<Func<Stream, XmlReaderSettings, XmlParserContext?, XmlReader>>();
}
- private static MethodInfo CreateSqlReaderMethodInfo
- {
- get
- {
- if (s_createSqlReaderMethodInfo == null)
- {
- s_createSqlReaderMethodInfo = typeof(System.Xml.XmlReader).GetMethod("CreateSqlReader", BindingFlags.Static | BindingFlags.NonPublic)!;
- }
-
- return s_createSqlReaderMethodInfo;
- }
- }
+ private static MethodInfo CreateSqlReaderMethodInfo =>
+ s_createSqlReaderMethodInfo ??= typeof(System.Xml.XmlReader).GetMethod("CreateSqlReader", BindingFlags.Static | BindingFlags.NonPublic)!;
// INullable
public bool IsNull
XmlSchemaSimpleType? xmlSimpleType = (item as XmlSchemaSimpleType);
if (xmlSimpleType != null)
{
- if (_udSimpleTypes == null)
- {
- _udSimpleTypes = new Hashtable();
- }
+ _udSimpleTypes ??= new Hashtable();
_udSimpleTypes[type.QualifiedName.ToString()] = xmlSimpleType;
DataColumn? dc = (DataColumn?)_existingSimpleTypeMap![type.QualifiedName.ToString()];
{
if (attrs[i].LocalName == "Expression")
{
- if (_expressions == null)
- _expressions = new Hashtable();
+ _expressions ??= new Hashtable();
_expressions[dc] = attrs[i].Value;
_columnExpressions!.Add(dc);
break;
}
}
- if (value == null)
- value = string.Empty;
-
- return value;
+ return value ?? string.Empty;
}
private static string GetInitialTextFromNodes(ref XmlNode? n)
}
}
- if (value == null)
- value = string.Empty;
-
- return value;
+ return value ?? string.Empty;
}
private static DataColumn? GetTextOnlyColumn(DataRow row)
// nothing left down here, continue from element
- if (n == null)
- n = e;
+ n ??= e;
}
}
// Keep constraints status for datataset/table
InitNameTable(); // Adds DataSet namespaces to reader's nametable
- if (_nodeToSchemaMap == null)
- { // Create XML to dataset map
- _nodeToSchemaMap = _isTableLevel ? new XmlToDatasetMap(_dataReader.NameTable, _dataTable!) :
+ // Create XML to dataset map
+ _nodeToSchemaMap ??= _isTableLevel ? new XmlToDatasetMap(_dataReader.NameTable, _dataTable!) :
new XmlToDatasetMap(_dataReader.NameTable, _dataSet!);
- }
if (_isTableLevel)
{
StringBuilder? builder = null;
while (_dataReader.Read() && entryDepth < _dataReader.Depth && IsTextLikeNode(_dataReader.NodeType))
{
- if (builder == null)
- {
- builder = new StringBuilder(text);
- }
+ builder ??= new StringBuilder(text);
builder.Append(_dataReader.Value); // Concatenate other sequential text like
// nodes we might have. This is rare.
// We're using this instead of dataReader.ReadString()
string _tableLocalName = table.EncodedTableName; // Table name
- string? tableLocalName = nameTable.Get(_tableLocalName); // Look it up in nametable
-
- if (tableLocalName == null)
- { // If not found
- tableLocalName = nameTable.Add(_tableLocalName); // Add it
- }
+ string tableLocalName =
+ nameTable.Get(_tableLocalName) ?? // Look it up in nametable
+ nameTable.Add(_tableLocalName); // If not found, add it
table._encodedTableName = tableLocalName; // And set it back
private static bool AddColumnSchema(XmlNameTable nameTable, DataColumn col, XmlNodeIdHashtable columns)
{
string _columnLocalName = XmlConvert.EncodeLocalName(col.ColumnName);
- string? columnLocalName = nameTable.Get(_columnLocalName); // Look it up in a name table
-
- if (columnLocalName == null)
- { // Not found?
- columnLocalName = nameTable.Add(_columnLocalName); // Add it
- }
+ string columnLocalName =
+ nameTable.Get(_columnLocalName) ?? // Look it up in a name table
+ nameTable.Add(_columnLocalName); // Not found? Add it
col._encodedColumnName = columnLocalName; // And set it back
// Hash tables with columns schema maps
// and child tables schema maps
- string? dsNamespace = nameTable.Get(dataSet.Namespace); // Attept to look up DataSet namespace
- // in the name table
-
- if (dsNamespace == null)
- { // Found ?
- dsNamespace = nameTable.Add(dataSet.Namespace); // Nope. Add it
- }
- dataSet._namespaceURI = dsNamespace; // Set a DataSet namespace URI
+ string dsNamespace =
+ nameTable.Get(dataSet.Namespace) ?? // Attempt to look up DataSet namespace in the name table
+ nameTable.Add(dataSet.Namespace); // Found? Nope. Add it
+ dataSet._namespaceURI = dsNamespace; // Set a DataSet namespace URI
foreach (DataTable t in dataSet.Tables)
{ // For each table
// Handle namespaces and names as usuall
string _tableLocalName = XmlConvert.EncodeLocalName(r.ChildTable.TableName);
- string? tableLocalName = nameTable.Get(_tableLocalName);
-
- if (tableLocalName == null)
- {
- tableLocalName = nameTable.Add(_tableLocalName);
- }
-
- string? tableNamespace = nameTable.Get(r.ChildTable.Namespace);
+ string? tableLocalName =
+ nameTable.Get(_tableLocalName) ??
+ nameTable.Add(_tableLocalName);
- if (tableNamespace == null)
- {
- tableNamespace = nameTable.Add(r.ChildTable.Namespace);
- }
+ string? tableNamespace =
+ nameTable.Get(r.ChildTable.Namespace) ??
+ nameTable.Add(r.ChildTable.Namespace);
XmlNodeIdentety idTable = new XmlNodeIdentety(tableLocalName, tableNamespace);
tableSchemaInfo.ColumnsSchemaMap[idTable] = r.ChildTable;
// fBoundToDataSet and fBoundToDocument should have the same value
Debug.Assert(_fBoundToDataSet ? _fBoundToDocument : (!_fBoundToDocument));
#endif
- if (prefix == null)
- prefix = string.Empty;
- if (namespaceURI == null)
- namespaceURI = string.Empty;
+ prefix ??= string.Empty;
+ namespaceURI ??= string.Empty;
if (!_fAssociateDataRow)
{
if (docelem == null)
{
string docElemName = XmlConvert.EncodeLocalName(DataSet.DataSetName);
- if (docElemName == null || docElemName.Length == 0)
+ if (string.IsNullOrEmpty(docElemName))
+ {
docElemName = "Xml";
- string ns = DataSet.Namespace;
- if (ns == null)
- ns = string.Empty;
- docelem = new XmlBoundElement(string.Empty, docElemName, ns, this);
+ }
+
+ docelem = new XmlBoundElement(string.Empty, docElemName, DataSet.Namespace ?? string.Empty, this);
AppendChild(docelem);
}
Debug.Assert(col.ColumnMapping == MappingType.SimpleContent);
newNode = CreateTextNode(col.ConvertObjectToXml(value));
if (node.FirstChild != null)
+ {
node.InsertBefore(newNode, node.FirstChild);
+ }
else
+ {
node.AppendChild(newNode);
- if (priorNode == null)
- priorNode = newNode;
+ }
+ priorNode ??= newNode;
}
}
}
_bHasXSINIL = true;
}
else
+ {
attr.Value = Keywords.TRUE;
+ }
}
else
{
// retrieve all the value in between so they can go back to values they've skipped
for (int c = 0; c < i; c++)
{
- if (values[c] == null)
- {
- values[c] = _record.GetValue(c);
- }
+ values[c] ??= _record.GetValue(c);
}
}
return values[i];
internal DbSchemaInfo GetSchema(int i)
{
- if (_schema == null)
- {
- _schema = new DbSchemaInfo[Count];
- }
+ _schema ??= new DbSchemaInfo[Count];
return _schema[i] ??= new DbSchemaInfo();
}
_connection.AddWeakReference(this, OdbcReferenceCollection.CommandTag);
}
- if (_cmdWrapper._dataReaderBuf == null)
- {
- _cmdWrapper._dataReaderBuf = new CNativeBuffer(4096);
- }
+ _cmdWrapper._dataReaderBuf ??= new CNativeBuffer(4096);
// if there is already a statement handle we need to do some cleanup
//
{
if (IsOpen)
{
- if (ProviderInfo.DriverName == null)
- {
- ProviderInfo.DriverName = GetInfoStringUnhandled(ODBC32.SQL_INFO.DRIVER_NAME)!;
- }
- return ProviderInfo.DriverName;
+ return ProviderInfo.DriverName ??= GetInfoStringUnhandled(ODBC32.SQL_INFO.DRIVER_NAME)!;
}
+
return string.Empty;
}
}
if (null != _dataCache)
{
DbSchemaInfo info = _dataCache.GetSchema(i);
- if (info._typename == null)
- {
- info._typename = GetColAttributeStr(i, ODBC32.SQL_DESC.TYPE_NAME, ODBC32.SQL_COLUMN.TYPE_NAME, ODBC32.HANDLER.THROW)!;
- }
- return info._typename;
+ return info._typename ??= GetColAttributeStr(i, ODBC32.SQL_DESC.TYPE_NAME, ODBC32.SQL_COLUMN.TYPE_NAME, ODBC32.HANDLER.THROW)!;
}
throw ADP.DataReaderNoData();
}
if (null != _dataCache)
{
DbSchemaInfo info = _dataCache.GetSchema(i);
- if (info._type == null)
- {
- info._type = GetSqlType(i)._type;
- }
- return info._type;
+ return info._type ??= GetSqlType(i)._type;
}
throw ADP.DataReaderNoData();
}
if (null != _dataCache)
{
DbSchemaInfo info = _dataCache.GetSchema(i);
- if (info._name == null)
- {
- info._name = GetColAttributeStr(i, ODBC32.SQL_DESC.NAME, ODBC32.SQL_COLUMN.NAME, ODBC32.HANDLER.THROW);
- if (null == info._name)
- { // MDAC 66681
- info._name = "";
- }
- }
- return info._name;
+ return info._name ??= GetColAttributeStr(i, ODBC32.SQL_DESC.NAME, ODBC32.SQL_COLUMN.NAME, ODBC32.HANDLER.THROW) ?? "";
}
throw ADP.DataReaderNoData();
}
_metadata[ordinal].isNullable = false;
_metadata[ordinal].baseTableName = qualifiedTableName.Table;
- if (_metadata[ordinal].baseColumnName == null)
- {
- _metadata[ordinal].baseColumnName = columnname;
- }
+ _metadata[ordinal].baseColumnName ??= columnname;
}
else
{
if (ordinal != -1)
{
_metadata[ordinal].isRowVersion = true;
- if (_metadata[ordinal].baseColumnName == null)
- {
- _metadata[ordinal].baseColumnName = columnname;
- }
+ _metadata[ordinal].baseColumnName ??= columnname;
}
}
// Unbind the column
// test test test - we don't know if this is nulalble or not so why do we want to set it to a value?
_metadata[indexordinal].isNullable = false;
_metadata[indexordinal].isUnique = true;
- if (_metadata[indexordinal].baseTableName == null)
- {
- _metadata[indexordinal].baseTableName = qualifiedTableName.Table;
- }
- if (_metadata[indexordinal].baseColumnName == null)
- {
- _metadata[indexordinal].baseColumnName = columnname;
- }
+ _metadata[indexordinal].baseTableName ??= qualifiedTableName.Table;
+ _metadata[indexordinal].baseColumnName ??= columnname;
}
}
// Unbind the columns
public bool connectSqlServer(string connStr)
{
- if (con == null)
- {
- con = new OdbcConnection(connStr);
- }
+ con ??= new OdbcConnection(connStr);
con.Open();
trn = con.BeginTransaction();
connection.GetLiteralQuotes(ADP.QuoteIdentifier, out quotePrefix, out quoteSuffix);
// if the quote suffix is null assume that it is the same as the prefix (See OLEDB spec
// IDBInfo::GetLiteralInfo DBLITERAL_QUOTE_SUFFIX.)
- if (quoteSuffix == null)
- {
- quoteSuffix = quotePrefix;
- }
+ quoteSuffix ??= quotePrefix;
}
return ADP.BuildQuotedString(quotePrefix, quoteSuffix, unquotedIdentifier);
connection.GetLiteralQuotes(ADP.UnquoteIdentifier, out quotePrefix, out quoteSuffix);
// if the quote suffix is null assume that it is the same as the prefix (See OLEDB spec
// IDBInfo::GetLiteralInfo DBLITERAL_QUOTE_SUFFIX.)
- if (quoteSuffix == null)
- {
- quoteSuffix = quotePrefix;
- }
+ quoteSuffix ??= quotePrefix;
}
string? unquotedIdentifier;
{
// if the quote suffix is null assume that it is the same as the prefix (See OLEDB spec
// IDBInfo::GetLiteralInfo DBLITERAL_QUOTE_SUFFIX.)
- if (quoteSuffix == null)
- {
- quoteSuffix = quotePrefix;
- }
+ quoteSuffix ??= quotePrefix;
// only know how to build the parttern if the suffix is 1 character
// in all other cases just leave the field null
public static void CreateFilterAndTransformList(ref FilterAndTransform? specList, string? filterAndPayloadSpecs, DiagnosticSourceEventSource eventSource)
{
DestroyFilterAndTransformList(ref specList, eventSource); // Stop anything that was on before.
- if (filterAndPayloadSpecs == null)
- filterAndPayloadSpecs = "";
+ filterAndPayloadSpecs ??= "";
// Points just beyond the last point in the string that has yet to be parsed. Thus we start with the whole string.
int endIdx = filterAndPayloadSpecs.Length;
_eventSource.Message("DiagnosticSource: Could not find Event to log Activity " + activityName);
}
- if (writeEvent == null)
- {
- writeEvent = _eventSource.Event;
- }
+ writeEvent ??= _eventSource.Event;
// Set up a subscription that watches for the given Diagnostic Sources and events which will call back
// to the EventSource.
_fetches = new PropertySpec(propertyName, _fetches);
// If the user did not explicitly set a name, it is the last one (first to be processed from the end).
- if (_outputName == null)
- _outputName = propertyName;
+ _outputName ??= propertyName;
endIdx = dotIdx; // This works even when LastIndexOf return -1.
}
/// <param name="measurementCallback">The callback which can be used to get measurement recording of numeric type T.</param>
public void SetMeasurementEventCallback<T>(MeasurementCallback<T>? measurementCallback) where T : struct
{
- if (measurementCallback is null)
- {
- measurementCallback = (instrument, measurement, tags, state) => { /* no-op */};
- }
+ measurementCallback ??= (instrument, measurement, tags, state) => { /* no-op */};
+
if (typeof(T) == typeof(byte))
{
_byteMeasurementCallback = (MeasurementCallback<byte>)(object)measurementCallback;
private ulong _s0, _s1, _s2, _s3;
- public static RandomNumberGenerator Current
- {
- get
- {
- if (t_random == null)
- {
- t_random = new RandomNumberGenerator();
- }
- return t_random;
- }
- }
+ public static RandomNumberGenerator Current => t_random ??= new RandomNumberGenerator();
#if ALLOW_PARTIALLY_TRUSTED_CALLERS
[System.Security.SecuritySafeCriticalAttribute]
// The EventLog.set_Source used to do some normalization and throw some exceptions. We mimic that behavior here.
private static string CheckAndNormalizeSourceName(string source)
{
- if (source == null)
- source = string.Empty;
+ source ??= string.Empty;
// this 254 limit is the max length of a registry key.
if (source.Length + EventLogKey.Length > 254)
public EventLogConfiguration(string logName, EventLogSession session)
{
- if (session == null)
- session = EventLogSession.GlobalSession;
+ session ??= EventLogSession.GlobalSession;
_session = session;
LogName = logName;
return _containerChannel;
lock (_syncObject)
{
- if (_containerChannel == null)
- {
- _containerChannel = (string)NativeWrapper.EvtGetEventInfo(this.Handle, UnsafeNativeMethods.EvtEventPropertyId.EvtEventPath);
- }
- return _containerChannel;
+ return _containerChannel ??= (string)NativeWrapper.EvtGetEventInfo(this.Handle, UnsafeNativeMethods.EvtEventPropertyId.EvtEventPath);
}
}
}
return _matchedQueryIds;
lock (_syncObject)
{
- if (_matchedQueryIds == null)
- {
- _matchedQueryIds = (int[])NativeWrapper.EvtGetEventInfo(this.Handle, UnsafeNativeMethods.EvtEventPropertyId.EvtEventQueryIDs);
- }
- return _matchedQueryIds;
+ return _matchedQueryIds ??= (int[])NativeWrapper.EvtGetEventInfo(this.Handle, UnsafeNativeMethods.EvtEventPropertyId.EvtEventQueryIDs);
}
}
}
return _keywordsNames;
lock (_syncObject)
{
- if (_keywordsNames == null)
- {
- _keywordsNames = _cachedMetadataInformation.GetKeywordDisplayNames(this.ProviderName, Handle);
- }
- return _keywordsNames;
+ return _keywordsNames ??= _cachedMetadataInformation.GetKeywordDisplayNames(this.ProviderName, Handle);
}
}
}
public EventLogSession(string server, string domain, string user, SecureString password, SessionAuthentication logOnType)
{
- if (server == null)
- server = "localhost";
+ server ??= "localhost";
_syncObject = new object();
internal ProviderMetadata(string providerName, EventLogSession session, CultureInfo targetCultureInfo, string logFilePath)
{
- if (targetCultureInfo == null)
- targetCultureInfo = CultureInfo.CurrentCulture;
-
- if (session == null)
- session = EventLogSession.GlobalSession;
+ targetCultureInfo ??= CultureInfo.CurrentCulture;
+ session ??= EventLogSession.GlobalSession;
_session = session;
_providerName = providerName;
internal string FindStandardLevelDisplayName(string name, uint value)
{
- if (_standardLevels == null)
- _standardLevels = (List<EventLevel>)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevels);
+ _standardLevels ??= (List<EventLevel>)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevels);
foreach (EventLevel standardLevel in _standardLevels)
{
if (standardLevel.Name == name && standardLevel.Value == value)
}
internal string FindStandardOpcodeDisplayName(string name, uint value)
{
- if (_standardOpcodes == null)
- _standardOpcodes = (List<EventOpcode>)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodes);
+ _standardOpcodes ??= (List<EventOpcode>)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodes);
foreach (EventOpcode standardOpcode in _standardOpcodes)
{
if (standardOpcode.Name == name && standardOpcode.Value == value)
}
internal string FindStandardKeywordDisplayName(string name, long value)
{
- if (_standardKeywords == null)
- _standardKeywords = (List<EventKeyword>)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywords);
+ _standardKeywords ??= (List<EventKeyword>)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywords);
foreach (EventKeyword standardKeyword in _standardKeywords)
{
if (standardKeyword.Name == name && standardKeyword.Value == value)
}
internal string FindStandardTaskDisplayName(string name, uint value)
{
- if (_standardTasks == null)
- _standardTasks = (List<EventTask>)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTasks);
+ _standardTasks ??= (List<EventTask>)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTasks);
foreach (EventTask standardTask in _standardTasks)
{
if (standardTask.Name == name && standardTask.Value == value)
Initialize();
- if (_helpMsg == null)
- _helpMsg = PerformanceCounterLib.GetCounterHelp(currentMachineName, currentCategoryName, _counterName);
+ _helpMsg ??= PerformanceCounterLib.GetCounterHelp(currentMachineName, currentCategoryName, _counterName);
return _helpMsg;
}
if (_categoryName == null)
throw new InvalidOperationException(SR.CategoryNameNotSet);
- if (_categoryHelp == null)
- _categoryHelp = PerformanceCounterLib.GetCategoryHelp(_machineName, _categoryName);
+ _categoryHelp ??= PerformanceCounterLib.GetCategoryHelp(_machineName, _categoryName);
return _categoryHelp;
}
{
lock (InternalSyncObject)
{
- if (s_computerName == null)
- {
- s_computerName = Interop.Kernel32.GetComputerName() ?? string.Empty;
- }
+ s_computerName ??= Interop.Kernel32.GetComputerName() ?? string.Empty;
}
}
{
lock (_helpTableLock)
{
- if (_helpTable == null)
- _helpTable = GetStringTable(true);
+ _helpTable ??= GetStringTable(true);
}
}
{
lock (_nameTableLock)
{
- if (_nameTable == null)
- _nameTable = GetStringTable(false);
+ _nameTable ??= GetStringTable(false);
}
}
for (int index = 0; index < entry.CounterIndexes.Length; ++index)
{
int counterIndex = entry.CounterIndexes[index];
- string counterName = (string)NameTable[counterIndex];
- if (counterName == null)
- counterName = string.Empty;
+ string counterName = (string)NameTable[counterIndex] ?? string.Empty;
if (string.Equals(counterName, counter, StringComparison.OrdinalIgnoreCase))
return true;
{
serviceParentKey = Registry.LocalMachine.OpenSubKey(ServicePath, true);
- serviceKey = serviceParentKey.OpenSubKey(categoryName + "\\Performance", true);
- if (serviceKey == null)
- serviceKey = serviceParentKey.CreateSubKey(categoryName + "\\Performance");
+ string categoryPerfKeyName = $"{categoryName}\\Performance";
+ serviceKey =
+ serviceParentKey.OpenSubKey(categoryPerfKeyName, writable: true) ??
+ serviceParentKey.CreateSubKey(categoryPerfKeyName);
serviceKey.SetValue("Open", "OpenPerformanceData");
serviceKey.SetValue("Collect", "CollectPerformanceData");
counterTypes[i] = ((int)creationData[i].CounterType).ToString(CultureInfo.InvariantCulture);
}
- linkageKey = serviceParentKey.OpenSubKey(categoryName + "\\Linkage", true);
- if (linkageKey == null)
- linkageKey = serviceParentKey.CreateSubKey(categoryName + "\\Linkage");
+ string categoryLinkageKeyName = $"{categoryName}\\Linkage";
+ linkageKey =
+ serviceParentKey.OpenSubKey(categoryLinkageKeyName, writable: true) ??
+ serviceParentKey.CreateSubKey(categoryLinkageKeyName);
linkageKey.SetValue("Export", new string[] { categoryName });
serviceKey.SetValue("Counter Names", (object)counters);
object firstID = serviceKey.GetValue("First Counter");
- if (firstID != null)
- iniRegistered = true;
- else
- iniRegistered = false;
+ iniRegistered = firstID != null;
}
finally
{
- if (serviceKey != null)
- serviceKey.Close();
-
- if (linkageKey != null)
- linkageKey.Close();
-
- if (serviceParentKey != null)
- serviceParentKey.Close();
+ serviceKey?.Close();
+ linkageKey?.Close();
+ serviceParentKey?.Close();
}
}
for (int index = 0; index < entry.CounterIndexes.Length; ++index)
{
int counterIndex = entry.CounterIndexes[index];
- string counterName = (string)NameTable[counterIndex];
- if (counterName == null)
- counterName = string.Empty;
+ string counterName = (string)NameTable[counterIndex] ?? string.Empty;
if (string.Equals(counterName, counter, StringComparison.OrdinalIgnoreCase))
{
//race with CloseAllLibraries
lock (InternalSyncObject)
{
- if (PerformanceCounterLib.s_libraryTable == null)
- PerformanceCounterLib.s_libraryTable = new Hashtable();
+ PerformanceCounterLib.s_libraryTable ??= new Hashtable();
string libraryKey = machineName + ":" + lcidString;
if (PerformanceCounterLib.s_libraryTable.Contains(libraryKey))
+ {
return (PerformanceCounterLib)PerformanceCounterLib.s_libraryTable[libraryKey];
+ }
else
{
PerformanceCounterLib library = new PerformanceCounterLib(machineName, lcidString);
{
lock (InternalSyncObject)
{
- if (_performanceMonitor == null)
- _performanceMonitor = new PerformanceMonitor(_machineName);
+ _performanceMonitor ??= new PerformanceMonitor(_machineName);
}
}
private Hashtable GetStringTable(bool isHelp)
{
Hashtable stringTable;
- RegistryKey libraryKey;
- if (string.Equals(_machineName, ComputerName, StringComparison.OrdinalIgnoreCase))
- libraryKey = Registry.PerformanceData;
- else
- {
- libraryKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.PerformanceData, _machineName);
- }
+ RegistryKey libraryKey = string.Equals(_machineName, ComputerName, StringComparison.OrdinalIgnoreCase) ?
+ Registry.PerformanceData :
+ RegistryKey.OpenRemoteBaseKey(RegistryHive.PerformanceData, _machineName);
try
{
for (int index = 0; index < (names.Length / 2); ++index)
{
- string nameString = names[(index * 2) + 1];
- if (nameString == null)
- nameString = string.Empty;
+ string nameString = names[(index * 2) + 1] ?? string.Empty;
int key;
if (!int.TryParse(names[index * 2], NumberStyles.Integer, CultureInfo.InvariantCulture, out key))
{
lock (_nameTableLock)
{
- if (_nameTable == null)
- _nameTable = GetStringTable(false);
+ _nameTable ??= GetStringTable(false);
}
}
{
lock (LazyInitializer.EnsureInitialized(ref s_internalSyncObject))
{
- if (_performanceMonitor == null)
- _performanceMonitor = new PerformanceMonitor(_machineName);
+ _performanceMonitor ??= new PerformanceMonitor(_machineName);
}
}
for (int index = 0; index < (names.Length / 2); ++index)
{
- string nameString = names[(index * 2) + 1];
- if (nameString == null)
- nameString = string.Empty;
+ string nameString = names[(index * 2) + 1] ?? string.Empty;
int key;
if (!int.TryParse(names[index * 2], NumberStyles.Integer, CultureInfo.InvariantCulture, out key))
return true;
}
- public string MainWindowTitle
- {
- get
- {
- if (_mainWindowTitle == null)
- {
- _mainWindowTitle = GetMainWindowTitle();
- }
-
- return _mainWindowTitle;
- }
- }
+ public string MainWindowTitle => _mainWindowTitle ??= GetMainWindowTitle();
private bool IsRespondingCore()
{
}
else
{
- if (additionalToRemove == null)
- {
- additionalToRemove = new List<ProcessWaitState>();
- }
+ additionalToRemove ??= new List<ProcessWaitState>();
additionalToRemove.Add(pws);
}
}
private void Write(string? message, bool useLogFile)
{
- if (message == null)
- {
- message = string.Empty;
- }
+ message ??= string.Empty;
if (NeedIndent && message.Length != 0)
{
protected Switch(string displayName, string? description, string defaultSwitchValue)
{
- // displayName is used as a hashtable key, so it can never
- // be null.
- if (displayName == null) displayName = string.Empty;
-
- _displayName = displayName;
+ // displayName is used as a hashtable key, so it can never be null.
+ _displayName = displayName ?? string.Empty;
_description = description;
// Add a weakreference to this switch and cleanup invalid references
}
}
- public string Callstack
- {
- get
- {
- if (_stackTrace == null)
- {
- _stackTrace = Environment.StackTrace;
- }
-
- return _stackTrace;
- }
- }
+ public string Callstack => _stackTrace ??= Environment.StackTrace;
public Stack LogicalOperationStack
{
}
}
- internal static string AppName
- {
- get
- {
- if (s_appName == null)
- {
- s_appName = Assembly.GetEntryAssembly()?.GetName().Name ?? string.Empty;
- }
- return s_appName;
- }
- }
+ internal static string AppName => s_appName ??= Assembly.GetEntryAssembly()?.GetName().Name ?? string.Empty;
public static bool AutoFlush
{
_listenerName = name;
}
- public StringDictionary Attributes
- {
- get
- {
- if (_attributes == null)
- _attributes = new StringDictionary();
- return _attributes;
- }
- }
+ public StringDictionary Attributes => _attributes ??= new StringDictionary();
/// <devdoc>
/// <para> Gets or sets a name for this <see cref='System.Diagnostics.TraceListener'/>.</para>
// Ensure that config is loaded
Initialize();
- if (_attributes == null)
- _attributes = new StringDictionary();
-
- return _attributes;
+ return _attributes ??= new StringDictionary();
}
}
LoadFilterMappingTable(mappingIndex, s_filterPropertiesTableRaw);
LoadPropertyMappingTable(mappingIndex, s_propertyMappingTableRaw);
- if (NonPresentAttrDefaultStateMapping == null)
- NonPresentAttrDefaultStateMapping = new Dictionary<string, bool>();
+ NonPresentAttrDefaultStateMapping ??= new Dictionary<string, bool>();
for (int i = 0; i < s_presenceStateTable.GetLength(0); i++)
{
// (it's probably read-only, e.g., "lastLogon").
if (toLdap != null)
{
- if (mappingTableByProperty[propertyName] == null)
- mappingTableByProperty[propertyName] = new ArrayList();
+ mappingTableByProperty[propertyName] ??= new ArrayList();
((ArrayList)mappingTableByProperty[propertyName]).Add(propertyEntry);
}
- if (mappingTableByPropertyFull[propertyName] == null)
- mappingTableByPropertyFull[propertyName] = new ArrayList();
+ mappingTableByPropertyFull[propertyName] ??= new ArrayList();
((ArrayList)mappingTableByPropertyFull[propertyName]).Add(propertyEntry);
{
string ldapAttributeLower = ldapAttribute.ToLowerInvariant();
- if (mappingTableByLDAP[ldapAttributeLower] == null)
- mappingTableByLDAP[ldapAttributeLower] = new ArrayList();
+ mappingTableByLDAP[ldapAttributeLower] ??= new ArrayList();
((ArrayList)mappingTableByLDAP[ldapAttributeLower]).Add(propertyEntry);
}
protected static bool IdentityClaimToFilter(string identity, string identityFormat, ref string filter, bool throwOnFail)
{
- if (identity == null)
- identity = "";
+ identity ??= "";
StringBuilder sb = new StringBuilder();
if (ic.UrnScheme == null)
throw new ArgumentException(SR.StoreCtxIdentityClaimMustHaveScheme);
- string urnValue = ic.UrnValue;
- if (urnValue == null)
- urnValue = "";
+ string urnValue = ic.UrnValue ?? "";
string filterString = null;
{
// If this is the first AccountInfo attribute we're loading,
// we'll need to create the AccountInfo to hold it
- if (_accountInfo == null)
- _accountInfo = new AccountInfo(this);
+ _accountInfo ??= new AccountInfo(this);
_accountInfo.LoadValueIntoProperty(propertyName, value);
}
{
// If this is the first PasswordInfo attribute we're loading,
// we'll need to create the PasswordInfo to hold it
- if (_passwordInfo == null)
- _passwordInfo = new PasswordInfo(this);
+ _passwordInfo ??= new PasswordInfo(this);
_passwordInfo.LoadValueIntoProperty(propertyName, value);
}
try
{
- string hostname = _name;
-
- if (hostname == null)
- hostname = Utils.GetComputerFlatName();
+ string hostname = _name ?? Utils.GetComputerFlatName();
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalContext", "DoMachineInit: hostname is " + hostname);
// {
foreach (Hashtable propertyMappingTableByProperty in byPropertyTables)
{
- if (propertyMappingTableByProperty[propertyName] == null)
- propertyMappingTableByProperty[propertyName] = new ArrayList();
+ propertyMappingTableByProperty[propertyName] ??= new ArrayList();
((ArrayList)propertyMappingTableByProperty[propertyName]).Add(propertyEntry);
}
foreach (Hashtable propertyMappingTableByWinNT in byWinNTTables)
{
- if (propertyMappingTableByWinNT[winNTAttributeLower] == null)
- propertyMappingTableByWinNT[winNTAttributeLower] = new ArrayList();
+ propertyMappingTableByWinNT[winNTAttributeLower] ??= new ArrayList();
((ArrayList)propertyMappingTableByWinNT[winNTAttributeLower]).Add(propertyEntry);
}
((CustomFilter) AdvancedSearchFilter).SetFilter(name);
}
- public override AdvancedFilters AdvancedSearchFilter
- {
- get
- {
- if (_customFilter == null)
- {
- _customFilter = new CustomFilter(this);
- }
-
- return _customFilter;
- }
- }
+ public override AdvancedFilters AdvancedSearchFilter => _customFilter ??= new CustomFilter(this);
// Custom properties
[DirectoryProperty("postalCode")]
UTF8Encoding utf8Encoder = new UTF8Encoding();
byte[] encodingResult = null;
// value is allowed to be null in certain scenario, so if it is null, just set it to empty array.
- if (value == null)
- value = Array.Empty<object>();
+ value ??= Array.Empty<object>();
Debug.WriteLine("Begin encoding\n");
// refresh the schema on the client
// bind to the abstract schema
- if (_abstractSchemaEntry == null)
- {
- _abstractSchemaEntry = directoryEntryMgr.GetCachedDirectoryEntry("Schema");
- }
+ _abstractSchemaEntry ??= directoryEntryMgr.GetCachedDirectoryEntry("Schema");
_abstractSchemaEntry.RefreshCache();
}
catch (COMException e)
get
{
CheckIfDisposed();
- if (_cachedSchemaRoleOwner == null)
- {
- _cachedSchemaRoleOwner = GetSchemaRoleOwner();
- }
- return _cachedSchemaRoleOwner;
+ return _cachedSchemaRoleOwner ??= GetSchemaRoleOwner();
}
}
try
{
// create a new directory entry for this class
- if (_schemaEntry == null)
- {
- _schemaEntry = DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext);
- }
+ _schemaEntry ??= DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext);
// this will create the class and set the CN value
string rdn = "CN=" + _commonName;
{
if (!_propertiesFromSchemaContainerInitialized)
{
- if (_schemaEntry == null)
- {
- _schemaEntry = DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext);
- }
+ _schemaEntry ??= DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext);
_propertyValuesFromServer = GetPropertiesFromSchemaContainer(_context, _schemaEntry, (_isDefunctOnServer) ? _commonName! : _ldapDisplayName, _isDefunctOnServer);
_propertiesFromSchemaContainerInitialized = true;
return classes;
}
- if (_schemaEntry == null)
- {
- _schemaEntry = DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext);
- }
+ _schemaEntry ??= DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext);
// constructing the filter
StringBuilder str = new StringBuilder(100);
return properties;
}
- if (_schemaEntry == null)
- {
- _schemaEntry = DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext);
- }
+ _schemaEntry ??= DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext);
// constructing the filter
StringBuilder str = new StringBuilder(100);
{
if (_isBound)
{
- if (_classEntry == null)
- {
- _classEntry = _schemaClass.GetSchemaClassDirectoryEntry();
- }
+ _classEntry ??= _schemaClass.GetSchemaClassDirectoryEntry();
try
{
{
if (_isBound)
{
- if (_classEntry == null)
- {
- _classEntry = _schemaClass.GetSchemaClassDirectoryEntry();
- }
+ _classEntry ??= _schemaClass.GetSchemaClassDirectoryEntry();
try
{
{
if (_isBound)
{
- if (_classEntry == null)
- {
- _classEntry = _schemaClass.GetSchemaClassDirectoryEntry();
- }
+ _classEntry ??= _schemaClass.GetSchemaClassDirectoryEntry();
// because this collection can contain values from the superior classes,
// these values would not exist in the classEntry
try
{
// create a new directory entry for this class
- if (_schemaEntry == null)
- {
- _schemaEntry = DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext);
- }
+ _schemaEntry ??= DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext);
// this will create the class and set the CN value
string rdn = "CN=" + _commonName;
try
{
- if (_schemaEntry == null)
- {
- _schemaEntry = DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext);
- }
+ _schemaEntry ??= DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext);
string filter = "(&(" + PropertyManager.ObjectCategory + "=attributeSchema)" + "(" + PropertyManager.LinkID + "=" + linkIdToSearch + "))";
ReadOnlyActiveDirectorySchemaPropertyCollection linkedProperties = ActiveDirectorySchema.GetAllProperties(_context, _schemaEntry, filter);
{
if (!_propertiesFromSchemaContainerInitialized)
{
- if (_schemaEntry == null)
- {
- _schemaEntry = DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext);
- }
+ _schemaEntry ??= DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext);
_propertyValuesFromServer = GetPropertiesFromSchemaContainer(_context, _schemaEntry, (_isDefunctOnServer) ? _commonName! : _ldapDisplayName, _isDefunctOnServer);
_propertiesFromSchemaContainerInitialized = true;
{
if (_isBound)
{
- if (_classEntry == null)
- {
- _classEntry = _schemaClass.GetSchemaClassDirectoryEntry();
- }
+ _classEntry ??= _schemaClass.GetSchemaClassDirectoryEntry();
try
{
{
if (_isBound)
{
- if (_classEntry == null)
- {
- _classEntry = _schemaClass.GetSchemaClassDirectoryEntry();
- }
+ _classEntry ??= _schemaClass.GetSchemaClassDirectoryEntry();
try
{
{
if (_isBound)
{
- if (_classEntry == null)
- {
- _classEntry = _schemaClass.GetSchemaClassDirectoryEntry();
- }
+ _classEntry ??= _schemaClass.GetSchemaClassDirectoryEntry();
// because this collection can contain values from the superior classes,
// these values would not exist in the classEntry
get
{
CheckIfDisposed();
- if (_cachedSites == null)
- {
- _cachedSites = new ReadOnlySiteCollection(GetSites());
- }
- return _cachedSites;
+ return _cachedSites ??= new ReadOnlySiteCollection(GetSites());
}
}
get
{
CheckIfDisposed();
- if (_cachedADAMInstances == null)
- {
- _cachedADAMInstances = FindAllAdamInstances();
- }
- return _cachedADAMInstances;
+ return _cachedADAMInstances ??= FindAllAdamInstances();
}
}
get
{
CheckIfDisposed();
- if (_cachedApplicationPartitions == null)
- {
- _cachedApplicationPartitions = new ApplicationPartitionCollection(GetApplicationPartitions());
- }
- return _cachedApplicationPartitions;
+ return _cachedApplicationPartitions ??= new ApplicationPartitionCollection(GetApplicationPartitions());
}
}
get
{
CheckIfDisposed();
- if (_cachedSchemaRoleOwner == null)
- {
- _cachedSchemaRoleOwner = GetRoleOwner(AdamRole.SchemaRole);
- }
- return _cachedSchemaRoleOwner;
+ return _cachedSchemaRoleOwner ??= GetRoleOwner(AdamRole.SchemaRole);
}
}
get
{
CheckIfDisposed();
- if (_cachedNamingRoleOwner == null)
- {
- _cachedNamingRoleOwner = GetRoleOwner(AdamRole.NamingRole);
- }
- return _cachedNamingRoleOwner;
+ return _cachedNamingRoleOwner ??= GetRoleOwner(AdamRole.NamingRole);
}
}
private DirectoryEntry GetNewDirectoryEntry(string dn)
{
- if (_bindingPrefix == null)
- {
- _bindingPrefix = "LDAP://" + _context.GetServerName() + "/";
- }
+ _bindingPrefix ??= "LDAP://" + _context.GetServerName() + "/";
_pathCracker.Set(dn, NativeComInterfaces.ADS_SETTYPE_DN);
string escapedDN = _pathCracker.Retrieve(NativeComInterfaces.ADS_FORMAT_X500_DN);
get
{
CheckIfDisposed();
- if (cachedPartitions == null)
- {
- cachedPartitions = new ReadOnlyStringCollection(GetPartitions());
- }
- return cachedPartitions;
+ return cachedPartitions ??= new ReadOnlyStringCollection(GetPartitions());
}
}
get
{
CheckIfDisposed();
- if (_cachedDomainControllers == null)
- {
- _cachedDomainControllers = FindAllDomainControllers();
- }
- return _cachedDomainControllers;
+ return _cachedDomainControllers ??= FindAllDomainControllers();
}
}
get
{
CheckIfDisposed();
- if (_cachedChildren == null)
- {
- _cachedChildren = new DomainCollection(GetChildDomains());
- }
- return _cachedChildren;
+ return _cachedChildren ??= new DomainCollection(GetChildDomains());
}
}
get
{
CheckIfDisposed();
- if (_cachedRidRoleOwner == null)
- {
- _cachedRidRoleOwner = GetRoleOwner(ActiveDirectoryRole.RidRole);
- }
- return _cachedRidRoleOwner;
+ return _cachedRidRoleOwner ??= GetRoleOwner(ActiveDirectoryRole.RidRole);
}
}
get
{
CheckIfDisposed();
- if (_cachedInfrastructureRoleOwner == null)
- {
- _cachedInfrastructureRoleOwner = GetRoleOwner(ActiveDirectoryRole.InfrastructureRole);
- }
- return _cachedInfrastructureRoleOwner;
+ return _cachedInfrastructureRoleOwner ??= GetRoleOwner(ActiveDirectoryRole.InfrastructureRole);
}
}
get
{
CheckIfDisposed();
- if (_cachedRoles == null)
- {
- _cachedRoles = new ActiveDirectoryRoleCollection(GetRoles());
- }
- return _cachedRoles;
+ return _cachedRoles ??= new ActiveDirectoryRoleCollection(GetRoles());
}
}
throw new ArgumentException(SR.InvalidFlags, nameof(flag));
}
- if (domainName == null)
- {
- domainName = DirectoryContext.GetLoggedOnDomain();
- }
+ domainName ??= DirectoryContext.GetLoggedOnDomain();
// call DsGetDcName
errorCode = Locator.DsGetDcNameWrapper(null, domainName, siteName, (long)flag | (long)PrivateLocatorFlags.DirectoryServicesRequired, out domainControllerInfo);
get
{
CheckIfDisposed();
- if (_cachedSites == null)
- {
- _cachedSites = new ReadOnlySiteCollection(GetSites());
- }
- return _cachedSites;
+ return _cachedSites ??= new ReadOnlySiteCollection(GetSites());
}
}
get
{
CheckIfDisposed();
- if (_cachedDomains == null)
- {
- _cachedDomains = new DomainCollection(GetDomains());
- }
- return _cachedDomains;
+ return _cachedDomains ??= new DomainCollection(GetDomains());
}
}
get
{
CheckIfDisposed();
- if (_cachedGlobalCatalogs == null)
- {
- _cachedGlobalCatalogs = FindAllGlobalCatalogs();
- }
- return _cachedGlobalCatalogs;
+ return _cachedGlobalCatalogs ??= FindAllGlobalCatalogs();
}
}
get
{
CheckIfDisposed();
- if (_cachedApplicationPartitions == null)
- {
- _cachedApplicationPartitions = new ApplicationPartitionCollection(GetApplicationPartitions());
- }
- return _cachedApplicationPartitions;
+ return _cachedApplicationPartitions ??= new ApplicationPartitionCollection(GetApplicationPartitions());
}
}
get
{
CheckIfDisposed();
- if (_cachedSchemaRoleOwner == null)
- {
- _cachedSchemaRoleOwner = GetRoleOwner(ActiveDirectoryRole.SchemaRole);
- }
- return _cachedSchemaRoleOwner;
+ return _cachedSchemaRoleOwner ??= GetRoleOwner(ActiveDirectoryRole.SchemaRole);
}
}
get
{
CheckIfDisposed();
- if (_cachedNamingRoleOwner == null)
- {
- _cachedNamingRoleOwner = GetRoleOwner(ActiveDirectoryRole.NamingRole);
- }
- return _cachedNamingRoleOwner;
+ return _cachedNamingRoleOwner ??= GetRoleOwner(ActiveDirectoryRole.NamingRole);
}
}
internal ReadOnlyStringCollection(ArrayList values)
{
- if (values == null)
- {
- values = new ArrayList();
- }
-
- this.InnerList.AddRange(values);
+ this.InnerList.AddRange(values ?? new ArrayList());
}
public string this[int index]
{
return base.ConvertTo(context, culture, value, destinationType!);
}
- public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext? context)
- {
- if (s_values == null)
- {
- s_values = new StandardValuesCollection(new object?[] { null });
- }
- return s_values;
- }
+ public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext? context) =>
+ s_values ??= new StandardValuesCollection(new object?[] { null });
internal static DirectoryEntry? GetFromCache(string path)
{
if (_enumVariant == null)
throw new InvalidOperationException(SR.DSNoCurrentChild);
- if (_currentEntry == null)
- _currentEntry = new DirectoryEntry(_enumVariant.GetValue(), _container.UsePropertyCache, _container.GetUsername(), _container.GetPassword(), _container.AuthenticationType);
-
- return _currentEntry;
+ return _currentEntry ??= new DirectoryEntry(_enumVariant.GetValue(), _container.UsePropertyCache, _container.GetUsername(), _container.GetPassword(), _container.AuthenticationType);
}
}
get => _path;
set
{
- if (value == null)
- value = "";
+ value ??= "";
if (System.DirectoryServices.ActiveDirectory.Utils.Compare(_path, value) == 0)
return;
/// <devdoc>
/// Gets a <see cref='System.DirectoryServices.PropertyCollection'/> of properties set on this object.
/// </devdoc>
- public PropertyCollection Properties
- {
- get
- {
- if (_propertyCollection == null)
- {
- _propertyCollection = new PropertyCollection(this);
- }
-
- return _propertyCollection;
- }
- }
+ public PropertyCollection Properties =>
+ _propertyCollection ??= new PropertyCollection(this);
/// <devdoc>
/// Gets the name of the schema used for this <see cref='System.DirectoryServices.DirectoryEntry'/>
_passwordIsNull = true;
}
- if (value == null)
- _userNameIsNull = true;
- else
- _userNameIsNull = false;
+ _userNameIsNull = value == null;
_credentials.UserName = value;
/// </devdoc>
[Editor("System.Windows.Forms.Design.StringCollectionEditor, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a",
"System.Drawing.Design.UITypeEditor, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
- public StringCollection PropertiesToLoad
- {
- get
- {
- if (_propertiesToLoad == null)
- {
- _propertiesToLoad = new StringCollection();
- }
- return _propertiesToLoad;
- }
- }
+ public StringCollection PropertiesToLoad =>
+ _propertiesToLoad ??= new StringCollection();
/// <devdoc>
/// Gets or sets how referrals are chased.
get => _attributeScopeQuery;
set
{
- if (value == null)
- value = "";
+ value ??= "";
// user explicitly set AttributeScopeQuery and value is not null or empty string
if (value.Length != 0)
}
}
- internal UnsafeNativeMethods.IDirectorySearch SearchObject
- {
- get
- {
- if (_searchObject == null)
- {
- _searchObject = (UnsafeNativeMethods.IDirectorySearch)_rootEntry.AdsObject; // get it only once
- }
- return _searchObject;
- }
- }
+ internal UnsafeNativeMethods.IDirectorySearch SearchObject =>
+ _searchObject ??= (UnsafeNativeMethods.IDirectorySearch)_rootEntry.AdsObject; // get it only once
/// <devdoc>
/// Gets the handle returned by IDirectorySearch::ExecuteSearch, which was called
if (!_initialized || _eof)
throw new InvalidOperationException(SR.DSNoCurrentEntry);
- if (_currentResult == null)
- _currentResult = GetCurrentResult();
-
- return _currentResult;
+ return _currentResult ??= GetCurrentResult();
}
}
obj = GetNamedColor(text);
if (obj == null) {
- if (culture == null) {
- culture = CultureInfo.CurrentCulture;
- }
+ culture ??= CultureInfo.CurrentCulture;
char sep = culture.TextInfo.ListSeparator[0];
bool tryMappingToKnownColor = true;
return "'" + c.Name + "'";
}
else {
- if (culture == null) {
- culture = CultureInfo.CurrentCulture;
- }
+ culture ??= CultureInfo.CurrentCulture;
string sep = culture.TextInfo.ListSeparator + " ";
TypeConverter intConverter = TypeDescriptor.GetConverter(typeof(int));
string[] args;
{
if (destinationType == typeof(string))
{
- if (culture == null)
- {
- culture = CultureInfo.CurrentCulture;
- }
+ culture ??= CultureInfo.CurrentCulture;
ValueStringBuilder sb = default;
sb.Append(font.Name);
return null;
}
- if (culture == null)
- {
- culture = CultureInfo.CurrentCulture;
- }
+ culture ??= CultureInfo.CurrentCulture;
char separator = culture.TextInfo.ListSeparator[0]; // For vi-VN: ','
string fontName = font; // start with the assumption that only the font name was provided.
}
// font family not found in private fonts also
- if (fontFamily == null)
- fontFamily = FontFamily.GenericSansSerif;
+ fontFamily ??= FontFamily.GenericSansSerif;
}
return new Font(fontFamily, size, style, unit, charSet, vertical);
{
ArgumentNullException.ThrowIfNull(format);
- ImageCodecInfo? codec = format.FindEncoder();
-
- if (codec == null)
- codec = ImageFormat.Png.FindEncoder()!;
+ ImageCodecInfo codec = format.FindEncoder() ?? ImageFormat.Png.FindEncoder()!;
Save(filename, codec, null);
}
{
// Construct the image array
//
- if (s_imageInfoList == null)
- {
- s_imageInfoList = new List<ImageInfo>();
- }
+ s_imageInfoList ??= new List<ImageInfo>();
// Add the new image
//
// COM+ takes forever to Finalize() weak references, so it pays to reuse them.
if (list[index] == null)
+ {
list[index] = new WeakReference(obj);
+ }
else
{
Debug.Assert(list[index].Target == null, $"Trying to reuse a weak reference that isn't broken yet: list[{index}], length = {list.Length}");
// Parse 2 integer values.
//
- if (culture == null) {
- culture = CultureInfo.CurrentCulture;
- }
+ culture ??= CultureInfo.CurrentCulture;
char sep = culture.TextInfo.ListSeparator[0];
string[] tokens = text.Split(sep);
int[] values = new int[tokens.Length];
if (destinationType == typeof(string)) {
Point pt = (Point)value;
- if (culture == null) {
- culture = CultureInfo.CurrentCulture;
- }
+ culture ??= CultureInfo.CurrentCulture;
string sep = culture.TextInfo.ListSeparator + " ";
TypeConverter intConverter = TypeDescriptor.GetConverter(typeof(int));
string[] args = new string[2];
else
{
// Parse 4 integer values.
- if (culture == null)
- {
- culture = CultureInfo.CurrentCulture;
- }
+ culture ??= CultureInfo.CurrentCulture;
char sep = culture.TextInfo.ListSeparator[0];
string[] tokens = text.Split(sep);
int[] values = new int[tokens.Length];
{
if (destinationType == typeof(string))
{
- if (culture == null)
- {
- culture = CultureInfo.CurrentCulture;
- }
+ culture ??= CultureInfo.CurrentCulture;
string sep = culture.TextInfo.ListSeparator + " ";
TypeConverter intConverter = GetIntConverter();
string?[] args = new string[4];
/// </summary>
public PrinterSettings PrinterSettings
{
- get { return printerSettings; }
- set
- {
- if (value == null)
- value = new PrinterSettings();
- printerSettings = value;
- }
+ get => printerSettings;
+ set => printerSettings = value ?? new PrinterSettings();
}
/// <summary>
get { return _defaultPageSettings; }
set
{
- if (value == null)
- value = new PageSettings();
- _defaultPageSettings = value;
+ _defaultPageSettings = value ?? new PageSettings();
_userSetPageSettings = true;
}
}
]
public string DocumentName
{
- get { return _documentName; }
-
- set
- {
- if (value == null)
- value = "";
- _documentName = value;
- }
+ get => _documentName;
+ set => _documentName = value ?? "";
}
// If true, positions the origin of the graphics object
]
public PrintController PrintController
{
- get
- {
- if (_printController == null)
- {
- _printController = new StandardPrintController();
- }
- return _printController;
- }
- set
- {
- _printController = value;
- }
+ get => _printController ??= new StandardPrintController();
+ set => _printController = value;
}
/// <summary>
get { return _printerSettings; }
set
{
- if (value == null)
- value = new PrinterSettings();
+ value ??= new PrinterSettings();
_printerSettings = value;
// reset the PageSettings that match the PrinterSettings only if we have created the defaultPageSettings..
if (!_userSetPageSettings)
// Write null terminated string, return length of string in characters (including null)
private static short WriteOneDEVNAME(string str, IntPtr bufferStart, int index)
{
- if (str == null)
- str = "";
+ str ??= "";
IntPtr address = (IntPtr)(checked((long)bufferStart + index * Marshal.SystemDefaultCharSize));
char[] data = str.ToCharArray();
}
set
{
- if (value == null)
- {
- value = new PageSettings();
- }
+ value ??= new PageSettings();
_pageSettings = value;
PageSettingsChanged = true;
}
// Parse 4 integer values.
//
- if (culture == null) {
- culture = CultureInfo.CurrentCulture;
- }
+ culture ??= CultureInfo.CurrentCulture;
char sep = culture.TextInfo.ListSeparator[0];
string[] tokens = text.Split(sep);
int[] values = new int[tokens.Length];
if (destinationType == typeof(string)) {
Rectangle rect = (Rectangle)value;
- if (culture == null) {
- culture = CultureInfo.CurrentCulture;
- }
+ culture ??= CultureInfo.CurrentCulture;
string sep = culture.TextInfo.ListSeparator + " ";
TypeConverter intConverter = TypeDescriptor.GetConverter(typeof(int));
string[] args = new string[4];
// Parse 2 integer values.
//
- if (culture == null) {
- culture = CultureInfo.CurrentCulture;
- }
+ culture ??= CultureInfo.CurrentCulture;
char sep = culture.TextInfo.ListSeparator[0];
string[] tokens = text.Split(sep);
int[] values = new int[tokens.Length];
if (destinationType == typeof(string)) {
Size size = (Size)value;
- if (culture == null) {
- culture = CultureInfo.CurrentCulture;
- }
+ culture ??= CultureInfo.CurrentCulture;
string sep = culture.TextInfo.ListSeparator + " ";
TypeConverter intConverter = TypeDescriptor.GetConverter(typeof(int));
- string[] args = new string[2];
- int nArg = 0;
// Note: ConvertToString will raise exception if value cannot be converted.
+ return
+ intConverter.ConvertToString(context, culture, size.Width) +
+ sep +
+ intConverter.ConvertToString(context, culture, size.Height);
args[nArg++] = intConverter.ConvertToString(context, culture, size.Width);
args[nArg++] = intConverter.ConvertToString(context, culture, size.Height);
-
- return string.Join(sep, args);
}
if (destinationType == typeof(InstanceDescriptor)) {
Size size = (Size)value;
Debug.Assert(idx >= 0 && idx < systemBrushes.Length, "System colors have been added but our system color array has not been expanded.");
- if (systemBrushes[idx] == null)
- {
- systemBrushes[idx] = new SolidBrush(c, true);
- }
-
- return systemBrushes[idx];
+ return systemBrushes[idx] ??= new SolidBrush(c, true);
}
}
}
}
// Use GenericSansSerif as a last resort - this will always work.
- if (defaultFont == null)
- {
- defaultFont = new Font(FontFamily.GenericSansSerif, 8);
- }
+ defaultFont ??= new Font(FontFamily.GenericSansSerif, 8);
if (defaultFont.Unit != GraphicsUnit.Point)
{
idx--;
Debug.Assert(idx >= 0 && idx < systemPens.Length, "System colors have been added but our system color array has not been expanded.");
- if (systemPens[idx] == null)
- {
- systemPens[idx] = new Pen(c, true);
- }
-
- return systemPens[idx];
+ return systemPens[idx] ??= new Pen(c, true);
}
}
}
{
if ((large && _largeImage == null) || (!large && _smallImage == null))
{
- Image? img;
- if (large)
- {
- img = _largeImage;
- }
- else
- {
- img = _smallImage;
- }
-
- if (img == null)
- {
- img = GetImageFromResource(type, imgName, large);
- }
+ Image? img = large ? _largeImage : _smallImage;
+ img ??= GetImageFromResource(type, imgName, large);
// last resort for large images.
if (large && _largeImage == null && _smallImage != null)
HandleRef hdc = new HandleRef(this, _hDC);
int state = Interop.Gdi32.SaveDC(hdc);
- if (_contextStack == null)
- {
- _contextStack = new Stack();
- }
+ _contextStack ??= new Stack();
GraphicsState g = new GraphicsState();
g.hBitmap = _hCurrentBmp;
/// </summary>
internal static void AddDeviceContext(DeviceContext dc)
{
- if (t_activeDeviceContexts == null)
+ ClientUtils.WeakRefCollection wrc = t_activeDeviceContexts ??= new ClientUtils.WeakRefCollection()
{
- t_activeDeviceContexts = new ClientUtils.WeakRefCollection()
- {
- RefCheckThreshold = 20
- };
- }
+ RefCheckThreshold = 20
+ };
- if (!t_activeDeviceContexts.Contains(dc))
+ if (!wrc.Contains(dc))
{
dc.Disposing += new EventHandler(OnDcDisposing);
- t_activeDeviceContexts.Add(dc);
+ wrc.Add(dc);
}
}
throw new AsnContentException(SR.ContentException_InvalidUnderCerOrDer_TryBer);
}
- if (readerStack == null)
- {
- readerStack = new Stack<(int, int, bool, int)>();
- }
+ readerStack ??= new Stack<(int, int, bool, int)>();
if (!source.Overlaps(cur, out int curOffset))
{
throw new AsnContentException(SR.ContentException_InvalidUnderCerOrDer_TryBer);
}
- if (readerStack == null)
- {
- readerStack = new Stack<(int, int, bool, int)>();
- }
+ readerStack ??= new Stack<(int, int, bool, int)>();
if (!source.Overlaps(cur, out int curOffset))
{
private Scope PushTag(Asn1Tag tag, UniversalTagNumber tagType)
{
- if (_nestingStack == null)
- {
- _nestingStack = new Stack<StackFrame>();
- }
+ _nestingStack ??= new Stack<StackFrame>();
Debug.Assert(tag.IsConstructed);
WriteTag(tag);
// Generate an ID if id is null. Throw exception if neither null nor a valid unique xsd:ID.
if (id == null)
+ {
id = GenerateUniqueRelationshipId();
+ }
else
+ {
ValidateUniqueRelationshipId(id);
+ }
// create and add
PackageRelationship relationship = new PackageRelationship(_package, _sourcePart, targetUri, targetMode, relationshipType, id);
}
//Returns the normalized string for the part uri.
- internal string NormalizedPartUriString
- {
- get
- {
- if (_normalizedPartUriString == null)
- _normalizedPartUriString = GetNormalizedPartUriString();
-
- return _normalizedPartUriString;
- }
- }
+ internal string NormalizedPartUriString => _normalizedPartUriString ??= GetNormalizedPartUriString();
//Returns the normalized part uri
- internal ValidatedPartUri NormalizedPartUri
- {
- get
- {
- if (_normalizedPartUri == null)
- _normalizedPartUri = GetNormalizedPartUri();
-
- return _normalizedPartUri;
- }
- }
+ internal ValidatedPartUri NormalizedPartUri => _normalizedPartUri ??= GetNormalizedPartUri();
//Returns true, if the original string passed to create
//this object was normalized
{
ThrowIfObjectDisposed();
- if (_packageProperties == null)
- _packageProperties = new PartBasedPackageProperties(this);
- return _packageProperties;
+ return _packageProperties ??= new PartBasedPackageProperties(this);
}
}
private void EnsureRelationships()
{
// once per package
- if (_relationships == null)
- {
- _relationships = new InternalRelationshipCollection(this);
- }
+ _relationships ??= new InternalRelationshipCollection(this);
}
//Delete All Package-level Relationships
_container = package;
if (contentType == null)
+ {
_contentType = null;
+ }
else
+ {
_contentType = new ContentType(contentType);
+ }
_requestedStreams = null;
_compressionOption = compressionOption;
Debug.Assert(!IsStreamClosed(s));
//Lazy init
- if (_requestedStreams == null)
- _requestedStreams = new List<Stream>(); //Default capacity is 4
+ _requestedStreams ??= new List<Stream>(); //Default capacity is 4
//Delete all the closed streams from the _requestedStreams list.
//Each time a new stream is handed out, we go through the list
/// </param>
private void AddSubsumingNamespace(string namespaceName)
{
- if (_subsumingNamespaces == null)
- _subsumingNamespaces = new Dictionary<string, object?>();
+ _subsumingNamespaces ??= new Dictionary<string, object?>();
_subsumingNamespaces[namespaceName] = null;
}
/// </param>
private void AddKnownNamespace(string namespaceName)
{
- if (_knownNamespaces == null)
- _knownNamespaces = new Dictionary<string, object?>();
+ _knownNamespaces ??= new Dictionary<string, object?>();
_knownNamespaces[namespaceName] = null;
}
}
}
- private string AlternateContent
- {
- get
- {
- if (_alternateContent == null)
- {
- _alternateContent = Reader.NameTable.Add("AlternateContent");
- }
- return _alternateContent;
- }
- }
+ private string AlternateContent => _alternateContent ??= Reader.NameTable.Add("AlternateContent");
- private string Choice
- {
- get
- {
- if (_choice == null)
- {
- _choice = Reader.NameTable.Add("Choice");
- }
- return _choice;
- }
- }
+ private string Choice => _choice ??= Reader.NameTable.Add("Choice");
- private string Fallback
- {
- get
- {
- if (_fallback == null)
- {
- _fallback = Reader.NameTable.Add("Fallback");
- }
- return _fallback;
- }
- }
+ private string Fallback => _fallback ??= Reader.NameTable.Add("Fallback");
- private string Requires
- {
- get
- {
- if (_requires == null)
- {
- _requires = Reader.NameTable.Add("Requires");
- }
- return _requires;
- }
- }
+ private string Requires => _requires ??= Reader.NameTable.Add("Requires");
- private string Ignorable
- {
- get
- {
- if (_ignorable == null)
- {
- _ignorable = Reader.NameTable.Add("Ignorable");
- }
- return _ignorable;
- }
- }
+ private string Ignorable => _ignorable ??= Reader.NameTable.Add("Ignorable");
- private string MustUnderstand
- {
- get
- {
- if (_mustUnderstand == null)
- {
- _mustUnderstand = Reader.NameTable.Add("MustUnderstand");
- }
- return _mustUnderstand;
- }
- }
+ private string MustUnderstand => _mustUnderstand ??= Reader.NameTable.Add("MustUnderstand");
- private string ProcessContent
- {
- get
- {
- if (_processContent == null)
- {
- _processContent = Reader.NameTable.Add("ProcessContent");
- }
- return _processContent;
- }
- }
+ private string ProcessContent => _processContent ??= Reader.NameTable.Add("ProcessContent");
- private string PreserveElements
- {
- get
- {
- if (_preserveElements == null)
- {
- _preserveElements = Reader.NameTable.Add("PreserveElements");
- }
- return _preserveElements;
- }
- }
+ private string PreserveElements => _preserveElements ??= Reader.NameTable.Add("PreserveElements");
- private string PreserveAttributes
- {
- get
- {
- if (_preserveAttributes == null)
- {
- _preserveAttributes = Reader.NameTable.Add("PreserveAttributes");
- }
- return _preserveAttributes;
- }
- }
+ private string PreserveAttributes => _preserveAttributes ??= Reader.NameTable.Add("PreserveAttributes");
- private string CompatibilityUri
- {
- get
- {
- if (_compatibilityUri == null)
- {
- _compatibilityUri = Reader.NameTable.Add(MarkupCompatibilityURI);
- }
- return _compatibilityUri;
- }
- }
+ private string CompatibilityUri => _compatibilityUri ??= Reader.NameTable.Add(MarkupCompatibilityURI);
#endregion Private Properties
#region Nested Classes
private struct NamespaceElementPair
}
else
{
- if (_names == null)
- {
- _names = new Dictionary<string, object?>();
- }
-
+ _names ??= new Dictionary<string, object?>();
_names[elementName] = null; // we don't care about value, just key
}
}
}
else
{
- if (_names == null)
- {
- _names = new Dictionary<string, string>();
- }
-
+ _names ??= new Dictionary<string, string>();
_names.Add(itemName, itemName);
}
}
{
// The part Uris are stored in the Override Dictionary in their original form , but they are compared
// in a normalized manner using the PartUriComparer
- if (_overrideDictionary == null)
- _overrideDictionary = new Dictionary<PackUriHelper.ValidatedPartUri, ContentType>(OverrideDictionaryInitialSize);
+ _overrideDictionary ??= new Dictionary<PackUriHelper.ValidatedPartUri, ContentType>(OverrideDictionaryInitialSize);
}
private void ParseContentTypesFile(System.Collections.ObjectModel.ReadOnlyCollection<ZipArchiveEntry> zipFiles)
}
catch (Exception ex)
{
- if (exceptions == null)
- {
- exceptions = new List<Exception>();
- }
-
+ exceptions ??= new List<Exception>();
exceptions.Add(ex);
}
}
{
lock (_lock)
{
- if (_internalTokenSource == null)
- {
- _internalTokenSource = new CancellationTokenSource();
- }
- return _internalTokenSource;
+ return _internalTokenSource ??= new CancellationTokenSource();
}
}
}
{
lock (_lockObject)
{
- if (_internalTokenSource == null)
- {
- _internalTokenSource = new CancellationTokenSource();
- }
- return _internalTokenSource;
+ return _internalTokenSource ??= new CancellationTokenSource();
}
}
}
if (variable.IsByRef)
{
- if (block == null)
- block = new ReadOnlyCollectionBuilder<Expression>();
+ block ??= new ReadOnlyCollectionBuilder<Expression>();
block.Add(
Expression.Assign(
/// </summary>
private List<WeakReference> GetTransitionList(int hashCode)
{
- if (_transitions == null)
- {
- _transitions = new Dictionary<int, List<WeakReference>>();
- }
+ _transitions ??= new Dictionary<int, List<WeakReference>>();
if (!_transitions.TryGetValue(hashCode, out List<WeakReference>? infos))
{
{
Type lookingUp = initialArg;
TypeInfo nextTypeInfo;
- if (curTypeInfo.TypeChain == null)
- {
- curTypeInfo.TypeChain = new Dictionary<Type, TypeInfo>();
- }
+ curTypeInfo.TypeChain ??= new Dictionary<Type, TypeInfo>();
if (!curTypeInfo.TypeChain.TryGetValue(lookingUp, out nextTypeInfo))
{
{
Debug.Assert(CanJumpInto);
- if (_labels == null)
- {
- _labels = new Dictionary<LabelTarget, LabelInfo>();
- }
+ _labels ??= new Dictionary<LabelTarget, LabelInfo>();
_labels.Add(target, info);
}
Debug.Assert(label != null);
}
- if (label == null)
- {
- label = DefineLabel(node.Target);
- }
+ label ??= DefineLabel(node.Target);
if (node.DefaultValue != null)
{
WriteBack? wb = EmitAddressWriteBack(argument, type);
if (wb != null)
{
- if (writeBacks == null)
- {
- writeBacks = new List<WriteBack>();
- }
+ writeBacks ??= new List<WriteBack>();
writeBacks.Add(wb);
}
// if (switchValue == null) {
// switchIndex = nullCase;
// } else {
- // if (_dictField == null) {
- // _dictField = new Dictionary<string, int>(count) { { ... }, ... };
- // }
+ // _dictField ??= new Dictionary<string, int>(count) { { ... }, ... };
// if (!_dictField.TryGetValue(switchValue, out switchIndex)) {
// switchIndex = -1;
// }
/// </param>
private void MarkRef(int index)
{
- if (_byRefs == null)
- {
- _byRefs = new bool[_expressions.Length];
- }
+ _byRefs ??= new bool[_expressions.Length];
_byRefs[index] = true;
}
Debug.Assert(_freeTemps == null || !_freeTemps.Contains(temp));
Debug.Assert(_usedTemps == null || !_usedTemps.Contains(temp));
- if (_usedTemps == null)
- {
- _usedTemps = new Stack<ParameterExpression>();
- }
+ _usedTemps ??= new Stack<ParameterExpression>();
_usedTemps.Push(temp);
{
Debug.Assert(_freeTemps == null || !_freeTemps.Contains(temp));
- if (_freeTemps == null)
- {
- _freeTemps = new List<ParameterExpression>();
- }
+ _freeTemps ??= new List<ParameterExpression>();
_freeTemps.Add(temp);
}
@case = new SwitchCase(body.Node, testValues);
- if (clone == null)
- {
- clone = Clone(cases, i);
- }
+ clone ??= Clone(cases, i);
}
if (clone != null)
{
handler = Expression.MakeCatchBlock(handler.Test, handler.Variable, rbody.Node, filter);
- if (clone == null)
- {
- clone = Clone(handlers, i);
- }
+ clone ??= Clone(handlers, i);
}
if (clone != null)
}
// Otherwise, merge it
- if (currentScope.MergedScopes == null)
- {
- currentScope.MergedScopes = new HashSet<BlockExpression>(ReferenceEqualityComparer.Instance);
- }
+ currentScope.MergedScopes ??= new HashSet<BlockExpression>(ReferenceEqualityComparer.Instance);
currentScope.MergedScopes.Add(block);
foreach (ParameterExpression v in block.Variables)
{
}
Debug.Assert(referenceScope != null);
- if (referenceScope.ReferenceCount == null)
- {
- referenceScope.ReferenceCount = new Dictionary<ParameterExpression, int>();
- }
+ referenceScope.ReferenceCount ??= new Dictionary<ParameterExpression, int>();
Helpers.IncrementCount(node, referenceScope.ReferenceCount);
return node;
{
Out($".Lambda {GetLambdaName(node)}<{node.Type}>");
- if (_lambdas == null)
- {
- _lambdas = new Queue<LambdaExpression>();
- }
+ _lambdas ??= new Queue<LambdaExpression>();
// N^2 performance, for keeping the order of the lambdas.
if (!_lambdas.Contains(node))
private int GetId(object o)
{
- if (_ids == null)
- {
- _ids = new Dictionary<object, int>();
- }
+ _ids ??= new Dictionary<object, int>();
int id;
if (!_ids.TryGetValue(o, out id))
if (_targetIndex == UnknownIndex)
{
- if (_forwardBranchFixups == null)
- {
- _forwardBranchFixups = new List<int>();
- }
+ _forwardBranchFixups ??= new List<int>();
_forwardBranchFixups.Add(branchIndex);
}
else
Instruction[] cache = Cache;
if (cache != null && offset >= 0 && offset < cache.Length)
{
- return cache[offset] ?? (cache[offset] = this);
+ return cache[offset] ??= this;
}
return this;
{
private static Instruction[]? s_cache;
- public override Instruction[] Cache
- {
- get
- {
- if (s_cache == null)
- {
- s_cache = new Instruction[CacheSize];
- }
- return s_cache;
- }
- }
+ public override Instruction[] Cache => s_cache ??= new Instruction[CacheSize];
public override string InstructionName => "BranchFalse";
public override int ConsumedStack => 1;
{
private static Instruction[]? s_cache;
- public override Instruction[] Cache
- {
- get
- {
- if (s_cache == null)
- {
- s_cache = new Instruction[CacheSize];
- }
- return s_cache;
- }
- }
+ public override Instruction[] Cache => s_cache ??= new Instruction[CacheSize];
public override string InstructionName => "BranchTrue";
public override int ConsumedStack => 1;
{
private static Instruction[]? s_cache;
- public override Instruction[] Cache
- {
- get
- {
- if (s_cache == null)
- {
- s_cache = new Instruction[CacheSize];
- }
- return s_cache;
- }
- }
+ public override Instruction[] Cache => s_cache ??= new Instruction[CacheSize];
public override string InstructionName => "CoalescingBranch";
public override int ConsumedStack => 1;
{
get
{
- if (s_caches == null)
- {
- s_caches = new Instruction[2][][] { new Instruction[2][], new Instruction[2][] };
- }
- return s_caches[ConsumedStack][ProducedStack] ?? (s_caches[ConsumedStack][ProducedStack] = new Instruction[CacheSize]);
+ s_caches ??= new Instruction[2][][] { new Instruction[2][], new Instruction[2][] };
+ return s_caches[ConsumedStack][ProducedStack] ??= new Instruction[CacheSize];
}
}
if (labelIndex < CacheSize)
{
int index = Variants * labelIndex | (labelTargetGetsValue ? 4 : 0) | (hasResult ? 2 : 0) | (hasValue ? 1 : 0);
- return s_cache[index] ?? (s_cache[index] = new GotoInstruction(labelIndex, hasResult, hasValue, labelTargetGetsValue));
+ return s_cache[index] ??= new GotoInstruction(labelIndex, hasResult, hasValue, labelTargetGetsValue);
}
return new GotoInstruction(labelIndex, hasResult, hasValue, labelTargetGetsValue);
}
{
if (labelIndex < CacheSize)
{
- return s_cache[labelIndex] ?? (s_cache[labelIndex] = new EnterFinallyInstruction(labelIndex));
+ return s_cache[labelIndex] ??= new EnterFinallyInstruction(labelIndex);
}
return new EnterFinallyInstruction(labelIndex);
}
{
if (labelIndex < CacheSize)
{
- return s_cache[labelIndex] ?? (s_cache[labelIndex] = new EnterFaultInstruction(labelIndex));
+ return s_cache[labelIndex] ??= new EnterFaultInstruction(labelIndex);
}
return new EnterFaultInstruction(labelIndex);
if (labelIndex < CacheSize)
{
int index = (2 * labelIndex) | (hasValue ? 1 : 0);
- return s_cache[index] ?? (s_cache[index] = new LeaveExceptionHandlerInstruction(labelIndex, hasValue));
+ return s_cache[index] ??= new LeaveExceptionHandlerInstruction(labelIndex, hasValue);
}
return new LeaveExceptionHandlerInstruction(labelIndex, hasValue);
}
{
if (i >= PushIntMinCachedValue && i <= PushIntMaxCachedValue)
{
- if (s_Ints == null)
- {
- s_Ints = new Instruction[PushIntMaxCachedValue - PushIntMinCachedValue + 1];
- }
+ s_Ints ??= new Instruction[PushIntMaxCachedValue - PushIntMinCachedValue + 1];
i -= PushIntMinCachedValue;
- Emit(s_Ints[i] ?? (s_Ints[i] = new LoadObjectInstruction(value)));
+ Emit(s_Ints[i] ??= new LoadObjectInstruction(value));
return;
}
}
if (_objects == null)
{
_objects = new List<object>();
- if (s_loadObjectCached == null)
- {
- s_loadObjectCached = new Instruction[CachedObjectCount];
- }
+ s_loadObjectCached ??= new Instruction[CachedObjectCount];
}
if (_objects.Count < s_loadObjectCached!.Length)
{
uint index = (uint)_objects.Count;
_objects.Add(value);
- Emit(s_loadObjectCached[index] ?? (s_loadObjectCached[index] = new LoadCachedObjectInstruction(index)));
+ Emit(s_loadObjectCached[index] ??= new LoadCachedObjectInstruction(index));
}
else
{
public void EmitLoadLocal(int index)
{
- if (s_loadLocal == null)
- {
- s_loadLocal = new Instruction[LocalInstrCacheSize];
- }
+ s_loadLocal ??= new Instruction[LocalInstrCacheSize];
if (index < s_loadLocal.Length)
{
- Emit(s_loadLocal[index] ?? (s_loadLocal[index] = new LoadLocalInstruction(index)));
+ Emit(s_loadLocal[index] ??= new LoadLocalInstruction(index));
}
else
{
internal static Instruction LoadLocalBoxed(int index)
{
- if (s_loadLocalBoxed == null)
- {
- s_loadLocalBoxed = new Instruction[LocalInstrCacheSize];
- }
+ s_loadLocalBoxed ??= new Instruction[LocalInstrCacheSize];
if (index < s_loadLocalBoxed.Length)
{
- return s_loadLocalBoxed[index] ?? (s_loadLocalBoxed[index] = new LoadLocalBoxedInstruction(index));
+ return s_loadLocalBoxed[index] ??= new LoadLocalBoxedInstruction(index);
}
else
{
public void EmitLoadLocalFromClosure(int index)
{
- if (s_loadLocalFromClosure == null)
- {
- s_loadLocalFromClosure = new Instruction[LocalInstrCacheSize];
- }
+ s_loadLocalFromClosure ??= new Instruction[LocalInstrCacheSize];
if (index < s_loadLocalFromClosure.Length)
{
- Emit(s_loadLocalFromClosure[index] ?? (s_loadLocalFromClosure[index] = new LoadLocalFromClosureInstruction(index)));
+ Emit(s_loadLocalFromClosure[index] ??= new LoadLocalFromClosureInstruction(index));
}
else
{
public void EmitLoadLocalFromClosureBoxed(int index)
{
- if (s_loadLocalFromClosureBoxed == null)
- {
- s_loadLocalFromClosureBoxed = new Instruction[LocalInstrCacheSize];
- }
+ s_loadLocalFromClosureBoxed ??= new Instruction[LocalInstrCacheSize];
if (index < s_loadLocalFromClosureBoxed.Length)
{
- Emit(s_loadLocalFromClosureBoxed[index] ?? (s_loadLocalFromClosureBoxed[index] = new LoadLocalFromClosureBoxedInstruction(index)));
+ Emit(s_loadLocalFromClosureBoxed[index] ??= new LoadLocalFromClosureBoxedInstruction(index));
}
else
{
public void EmitAssignLocal(int index)
{
- if (s_assignLocal == null)
- {
- s_assignLocal = new Instruction[LocalInstrCacheSize];
- }
+ s_assignLocal ??= new Instruction[LocalInstrCacheSize];
if (index < s_assignLocal.Length)
{
- Emit(s_assignLocal[index] ?? (s_assignLocal[index] = new AssignLocalInstruction(index)));
+ Emit(s_assignLocal[index] ??= new AssignLocalInstruction(index));
}
else
{
public void EmitStoreLocal(int index)
{
- if (s_storeLocal == null)
- {
- s_storeLocal = new Instruction[LocalInstrCacheSize];
- }
+ s_storeLocal ??= new Instruction[LocalInstrCacheSize];
if (index < s_storeLocal.Length)
{
- Emit(s_storeLocal[index] ?? (s_storeLocal[index] = new StoreLocalInstruction(index)));
+ Emit(s_storeLocal[index] ??= new StoreLocalInstruction(index));
}
else
{
internal static Instruction AssignLocalBoxed(int index)
{
- if (s_assignLocalBoxed == null)
- {
- s_assignLocalBoxed = new Instruction[LocalInstrCacheSize];
- }
+ s_assignLocalBoxed ??= new Instruction[LocalInstrCacheSize];
if (index < s_assignLocalBoxed.Length)
{
- return s_assignLocalBoxed[index] ?? (s_assignLocalBoxed[index] = new AssignLocalBoxedInstruction(index));
+ return s_assignLocalBoxed[index] ??= new AssignLocalBoxedInstruction(index);
}
else
{
internal static Instruction StoreLocalBoxed(int index)
{
- if (s_storeLocalBoxed == null)
- {
- s_storeLocalBoxed = new Instruction[LocalInstrCacheSize];
- }
+ s_storeLocalBoxed ??= new Instruction[LocalInstrCacheSize];
if (index < s_storeLocalBoxed.Length)
{
- return s_storeLocalBoxed[index] ?? (s_storeLocalBoxed[index] = new StoreLocalBoxedInstruction(index));
+ return s_storeLocalBoxed[index] ??= new StoreLocalBoxedInstruction(index);
}
else
{
public void EmitAssignLocalToClosure(int index)
{
- if (s_assignLocalToClosure == null)
- {
- s_assignLocalToClosure = new Instruction[LocalInstrCacheSize];
- }
+ s_assignLocalToClosure ??= new Instruction[LocalInstrCacheSize];
if (index < s_assignLocalToClosure.Length)
{
- Emit(s_assignLocalToClosure[index] ?? (s_assignLocalToClosure[index] = new AssignLocalToClosureInstruction(index)));
+ Emit(s_assignLocalToClosure[index] ??= new AssignLocalToClosureInstruction(index));
}
else
{
public BranchLabel MakeLabel()
{
- if (_labels == null)
- {
- _labels = new List<BranchLabel>();
- }
+ _labels ??= new List<BranchLabel>();
var label = new BranchLabel();
_labels.Add(label);
internal void SaveTraceToException(Exception exception)
{
- if (exception.Data[typeof(InterpretedFrameInfo)] == null)
- {
- exception.Data[typeof(InterpretedFrameInfo)] = new List<InterpretedFrameInfo>(GetStackTraceDebugInfo()).ToArray();
- }
+ exception.Data[typeof(InterpretedFrameInfo)] ??= new List<InterpretedFrameInfo>(GetStackTraceDebugInfo()).ToArray();
}
public static InterpretedFrameInfo[]? GetExceptionStackTrace(Exception exception)
private void EnsureLabel(LightCompiler compiler)
{
- if (_label == null)
- {
- _label = compiler.Instructions.MakeLabel();
- }
+ _label ??= compiler.Instructions.MakeLabel();
}
private bool DefinedIn(LabelScopeInfo scope)
{
Debug.Assert(CanJumpInto);
- if (_labels == null)
- {
- _labels = new HybridReferenceDictionary<LabelTarget, LabelInfo>();
- }
+ _labels ??= new HybridReferenceDictionary<LabelTarget, LabelInfo>();
_labels[target] = info;
}
Debug.Assert(label != null);
}
- if (label == null)
- {
- label = DefineLabel(node.Target);
- }
+ label ??= DefineLabel(node.Target);
if (node.DefaultValue != null)
{
ByRefUpdater? updater = CompileAddress(arg, i);
if (updater != null)
{
- if (updaters == null)
- {
- updaters = new List<ByRefUpdater>();
- }
+ updaters ??= new List<ByRefUpdater>();
updaters.Add(updater);
}
ByRefUpdater? updater = CompileAddress(arg, i);
if (updater != null)
{
- if (updaters == null)
- {
- updaters = new List<ByRefUpdater>();
- }
+ updaters ??= new List<ByRefUpdater>();
updaters.Add(updater);
}
}
if (_variables.TryGetValue(variable, out existing))
{
newScope = new VariableScope(result, start, existing);
- if (existing.ChildScopes == null)
- {
- existing.ChildScopes = new List<VariableScope>();
- }
+ existing.ChildScopes ??= new List<VariableScope>();
existing.ChildScopes.Add(newScope);
}
else
// method and call that will be used for creating instances of this
// delegate type
Func<Expression, string?, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>? fastPath;
- CacheDict<Type, Func<Expression, string?, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>>? factories = s_lambdaFactories;
- if (factories == null)
- {
- s_lambdaFactories = factories = new CacheDict<Type, Func<Expression, string?, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>>(50);
- }
+ CacheDict<Type, Func<Expression, string?, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>>? factories =
+ s_lambdaFactories ??= new CacheDict<Type, Func<Expression, string?, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>>(50);
if (!factories.TryGetValue(delegateType, out fastPath))
{
{
ArgumentNullException.ThrowIfNull(instance);
ArgumentNullException.ThrowIfNull(methodName);
- if (arguments == null)
- {
- arguments = Array.Empty<Expression>();
- }
+ arguments ??= Array.Empty<Expression>();
BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy;
return Expression.Call(instance, FindMethod(instance.Type, methodName, typeArguments, arguments, flags)!, arguments);
ArgumentNullException.ThrowIfNull(type);
ArgumentNullException.ThrowIfNull(methodName);
- if (arguments == null) arguments = Array.Empty<Expression>();
- BindingFlags flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy;
- return Expression.Call(null, FindMethod(type, methodName, typeArguments, arguments, flags)!, arguments);
+ arguments ??= Array.Empty<Expression>();
+ const BindingFlags Flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy;
+ return Expression.Call(null, FindMethod(type, methodName, typeArguments, arguments, Flags)!, arguments);
}
/// <summary>Creates a <see cref="MethodCallExpression"/> that represents a method call.</summary>
{
private static LambdaSignature<T>? s_instance;
- internal static LambdaSignature<T> Instance
- {
- get
- {
- if (s_instance == null)
- {
- s_instance = new LambdaSignature<T>();
- }
- return s_instance;
- }
- }
+ internal static LambdaSignature<T> Instance => s_instance ??= new LambdaSignature<T>();
internal readonly ReadOnlyCollection<ParameterExpression> Parameters;
internal readonly LabelTarget ReturnLabel;
internal override bool MoveNext(ref int currentElement, ref int currentKey)
{
- if (_currentCount == null)
- _currentCount = new Shared<int>(-1);
+ _currentCount ??= new Shared<int>(-1);
// Calculate the next index and ensure it falls within our range.
int nextCount = _currentCount.Value + 1;
internal override bool MoveNext([MaybeNullWhen(false), AllowNull] ref TResult currentElement, ref int currentKey)
{
- if (_currentIndex == null)
- _currentIndex = new Shared<int>(-1);
+ _currentIndex ??= new Shared<int>(-1);
if (_currentIndex.Value < (_count - 1))
{
Debug.Assert(!ParallelEnumerable.SinglePartitionMode);
- Mutables? mutables = _mutables;
- if (mutables == null)
- mutables = _mutables = new Mutables();
+ Mutables mutables = _mutables ??= new Mutables();
// If we haven't enumerated the source yet, do that now. This is the first phase
// of a two-phase barrier style operation.
Debug.Assert(!ParallelEnumerable.SinglePartitionMode);
- Mutables? mutables = _mutables;
- if (mutables == null)
- mutables = _mutables = new Mutables();
+ Mutables mutables = _mutables ??= new Mutables();
// If we haven't enumerated the source yet, do that now. This is the first phase
// of a two-phase barrier style operation.
internal override bool MoveNext([MaybeNullWhen(false), AllowNull] ref T currentElement, ref int currentKey)
{
// Lazily allocate the mutable holder.
- Mutables? mutables = _mutables;
- if (mutables == null)
- {
- mutables = _mutables = new Mutables();
- }
+ Mutables mutables = _mutables ??= new Mutables();
// If we are aren't within the chunk, we need to find another.
if (++mutables._currentPositionInChunk < mutables._currentChunkSize || MoveNextSlowPath())
internal override bool MoveNext([MaybeNullWhen(false), AllowNull] ref T currentElement, ref int currentKey)
{
// Lazily allocate the current index if needed.
- if (_currentIndex == null)
- {
- _currentIndex = new Shared<int>(_startIndex);
- }
+ _currentIndex ??= new Shared<int>(_startIndex);
// Now increment the current index, check bounds, and so on.
int current = ++_currentIndex.Value;
internal override bool MoveNext([MaybeNullWhen(false), AllowNull] ref T currentElement, ref int currentKey)
{
// Lazily allocate the mutable holder.
- Mutables? mutables = _mutables;
- if (mutables == null)
- {
- mutables = _mutables = new Mutables();
- }
+ Mutables mutables = _mutables ??= new Mutables();
// If we are aren't within the chunk, we need to find another.
if (++mutables._currentPositionInChunk < mutables._currentChunkSize || MoveNextSlowPath())
internal override bool MoveNext([MaybeNullWhen(false), AllowNull] ref T currentElement, ref int currentKey)
{
// Lazily allocate the current index if needed.
- if (_currentIndex == null)
- {
- _currentIndex = new Shared<int>(_startIndex);
- }
+ _currentIndex ??= new Shared<int>(_startIndex);
// Now increment the current index, check bounds, and so on.
int current = ++_currentIndex.Value;
internal override bool MoveNext([MaybeNullWhen(false), AllowNull] ref T currentElement, ref int currentKey)
{
- Mutables? mutables = _mutables;
- if (mutables == null)
- {
- mutables = _mutables = new Mutables();
- }
+ Mutables? mutables = _mutables ??= new Mutables();
Debug.Assert(mutables._chunkBuffer != null);
_leftOrdered = leftOrdered;
_rightOrdered = rightOrdered;
- _comparer = comparer;
-
- if (_comparer == null)
- {
- _comparer = EqualityComparer<TInputOutput>.Default;
- }
+ _comparer = comparer ?? EqualityComparer<TInputOutput>.Default;
_cancellationToken = cancellationToken;
}
QueryResults<TOutput> queryResults = GetQueryResults(querySettings);
- if (mergeOptions == null)
- {
- mergeOptions = querySettings.MergeOptions;
- }
-
+ mergeOptions ??= querySettings.MergeOptions;
Debug.Assert(mergeOptions != null);
// Top-level preemptive cancellation test.
internal QuerySettings WithDefaults()
{
QuerySettings settings = this;
- if (settings.TaskScheduler == null)
- {
- settings.TaskScheduler = TaskScheduler.Default;
- }
-
- if (settings.DegreeOfParallelism == null)
- {
- settings.DegreeOfParallelism = Scheduling.GetDefaultDegreeOfParallelism();
- }
-
- if (settings.ExecutionMode == null)
- {
- settings.ExecutionMode = ParallelExecutionMode.Default;
- }
-
- if (settings.MergeOptions == null)
- {
- settings.MergeOptions = ParallelMergeOptions.Default;
- }
+ settings.TaskScheduler ??= TaskScheduler.Default;
+ settings.DegreeOfParallelism ??= Scheduling.GetDefaultDegreeOfParallelism();
+ settings.ExecutionMode ??= ParallelExecutionMode.Default;
+ settings.MergeOptions ??= ParallelMergeOptions.Default;
if (settings.MergeOptions == ParallelMergeOptions.Default)
{
settings.MergeOptions = ParallelMergeOptions.AutoBuffered;
Debug.Assert(child != null, "child data source cannot be null");
_searchValue = searchValue;
-
- if (comparer == null)
- {
- _comparer = EqualityComparer<TInput>.Default;
- }
- else
- {
- _comparer = comparer;
- }
+ _comparer = comparer ?? EqualityComparer<TInput>.Default;
}
//---------------------------------------------------------------------------------------
TKey keyUnused = default!;
Pair<TInputOutput, NoKeyMemoizationRequired> current = default(Pair<TInputOutput, NoKeyMemoizationRequired>);
- if (_outputLoopCount == null)
- _outputLoopCount = new Shared<int>(0);
+ _outputLoopCount ??= new Shared<int>(0);
while (_source.MoveNext(ref current, ref keyUnused))
{
// Iterate through the input until we reach the end of the sequence or find
// an element matching the predicate.
- if (_outputLoopCount == null)
- _outputLoopCount = new Shared<int>(0);
+ _outputLoopCount ??= new Shared<int>(0);
while (_source.MoveNext(ref currentElement!, ref currentKey))
{
_keySelector = keySelector;
// If a comparer wasn't supplied, we use the default one for the key type.
- if (comparer == null)
- {
- _comparer = Util.GetDefaultComparer<TSortKey>();
- }
- else
- {
- _comparer = comparer;
- }
-
+ _comparer = comparer ?? Util.GetDefaultComparer<TSortKey>();
if (descending)
{
_comparer = new ReverseComparer<TSortKey>(_comparer);
// Iterate through the input until we reach the end of the sequence or find
// an element matching the predicate.
- if (_outputLoopCount == null)
- _outputLoopCount = new Shared<int>(0);
+ _outputLoopCount ??= new Shared<int>(0);
while (_source.MoveNext(ref currentElement!, ref currentKey))
{
TKey currentKey = default(TKey)!;
bool hadNext = _source.MoveNext(ref current!, ref currentKey);
- if (keys == null)
- {
- keys = new GrowingArray<TKey>();
- }
+ keys ??= new GrowingArray<TKey>();
if (hadNext)
{
{
private readonly IEqualityComparer<T> _comparer;
- internal WrapperEqualityComparer(IEqualityComparer<T>? comparer)
- {
- if (comparer == null)
- {
- _comparer = EqualityComparer<T>.Default;
- }
- else
- {
- _comparer = comparer;
- }
- }
+ internal WrapperEqualityComparer(IEqualityComparer<T>? comparer) =>
+ _comparer = comparer ?? EqualityComparer<T>.Default;
public bool Equals(Wrapper<T> x, Wrapper<T> y)
{
{
LabelTarget? newTarget;
if (_targetCache == null)
+ {
_targetCache = new Dictionary<LabelTarget, LabelTarget>();
+ }
else if (_targetCache.TryGetValue(node!, out newTarget))
+ {
return newTarget;
+ }
+
Type type = node!.Type;
if (!typeof(IQueryable).IsAssignableFrom(type))
newTarget = base.VisitLabelTarget(node);
{
Initialize(true);
- if (properties == null)
- properties = new PropertyDataCollection(this, false);
-
- return properties;
+ return properties ??= new PropertyDataCollection(this, false);
}
}
{
Initialize(false);
- if (systemProperties == null)
- systemProperties = new PropertyDataCollection(this, true);
-
- return systemProperties;
+ return systemProperties ??= new PropertyDataCollection(this, true);
}
}
{
Initialize(true);
- if (qualifiers == null)
- qualifiers = new QualifierDataCollection(this);
-
- return qualifiers;
+ return qualifiers ??= new QualifierDataCollection(this);
}
}
{
Initialize(true);
- if (methods == null)
- methods = new MethodDataCollection(this);
-
- return methods;
+ return methods ??= new MethodDataCollection(this);
}
}
{
get
{
- if (scope == null)
- return scope = ManagementScope._Clone(null);
- else
- return scope;
+ return scope ??= ManagementScope._Clone(null);
}
set
{
{
get
{
- if (path == null)
- return path = ManagementPath._Clone(null);
- else
- return path;
+ return path ??= ManagementPath._Clone(null);
}
set
{
{
get
{
- if (options == null)
- return options = ObjectGetOptions._Clone(null);
- else
- return options;
+ return options ??= ObjectGetOptions._Clone(null);
}
set
{
{
}
- if (newPath == null)
- newPath = new ManagementPath();
-
- return newPath;
+ return newPath ?? new ManagementPath();
}
/// <summary>
{
get
{
- if (context == null)
- return context = new ManagementNamedValueCollection();
- else
- return context;
+ return context ??= new ManagementNamedValueCollection();
}
set
{
{
// Test/utilize isWbemPathShared *only* on public + internal members!
if (wmiPath == null)
+ {
wmiPath = CreateWbemPath(path);
+ }
else
+ {
SetWbemPath(wmiPath, path);
+ }
}
private static void SetWbemPath(IWbemPath wbemPath, string path)
wmiPathTmp = CreateWbemPath(nsPath);
if (wmiPath == null)
+ {
wmiPath = this.CreateWbemPath("");
+ }
else if (isWbemPathShared)
{
// Check if this IWbemPath is shared among multiple managed objects.
int status = (int)ManagementStatus.NoError;
if (wmiPath == null)
+ {
wmiPath = (IWbemPath)MTAHelper.CreateInMTA(typeof(WbemDefPath)); //new WbemDefPath();
+ }
else if (isWbemPathShared)
{
// Check if this IWbemPath is shared among multiple managed objects.
{
get
{
- if (options == null)
- return options = ConnectionOptions._Clone(null, new IdentifierChangedEventHandler(HandleIdentifierChange));
- else
- return options;
+ return options ??= ConnectionOptions._Clone(null, new IdentifierChangedEventHandler(HandleIdentifierChange));
}
set
{
{
get
{
- if (prvpath == null)
- return prvpath = ManagementPath._Clone(null);
- else
- return prvpath;
+ return prvpath ??= ManagementPath._Clone(null);
}
set
{
/// qualifiers for this method.
/// </value>
/// <seealso cref='System.Management.QualifierData'/>
- public QualifierDataCollection Qualifiers
- {
- get
- {
- if (qualifiers == null)
- qualifiers = new QualifierDataCollection(parent, methodName, QualifierType.MethodQualifier);
- return qualifiers;
- }
- }
+ public QualifierDataCollection Qualifiers => qualifiers ??= new QualifierDataCollection(parent, methodName, QualifierType.MethodQualifier);
}//MethodData
}
/// <para>A <see cref='System.Management.QualifierDataCollection'/> that represents
/// the set of qualifiers defined on the property.</para>
/// </value>
- public QualifierDataCollection Qualifiers
- {
- get
- {
- if (qualifiers == null)
- qualifiers = new QualifierDataCollection(parent, propertyName, QualifierType.PropertyQualifier);
+ public QualifierDataCollection Qualifiers => qualifiers ??= new QualifierDataCollection(parent, propertyName, QualifierType.PropertyQualifier);
- return qualifiers;
- }
- }
internal long NullEnumValue
{
get
/// </summary>
private void AddPropertySet(CodeIndexerExpression prop, bool bArray, CodeStatementCollection statColl, string strType, CodeVariableReferenceExpression varValue)
{
- if (varValue == null)
- {
- varValue = new CodeVariableReferenceExpression("value");
- }
+ varValue ??= new CodeVariableReferenceExpression("value");
if (bArray == false)
{
throw new InvalidOperationException(SR.Format(SR.net_http_invalid_enable_first, "ClientCertificateOptions", "Manual"));
}
- if (_clientCertificates == null)
- {
- _clientCertificates = new X509Certificate2Collection();
- }
-
- return _clientCertificates;
+ return _clientCertificates ??= new X509Certificate2Collection();
}
}
}
}
- public IDictionary<string, object> Properties
- {
- get
- {
- if (_properties == null)
- {
- _properties = new Dictionary<string, object>();
- }
-
- return _properties;
- }
- }
+ public IDictionary<string, object> Properties => _properties ??= new Dictionary<string, object>();
#endregion
protected override void Dispose(bool disposing)
// Cache-Control is a header supporting lists of values. However, expose the header as an instance of
// CacheControlHeaderValue. So if we already have an instance of CacheControlHeaderValue, add the values
// from this string to the existing instances.
- CacheControlHeaderValue? result = storeValue;
- if (result == null)
- {
- result = new CacheControlHeaderValue();
- }
+ CacheControlHeaderValue? result = storeValue ?? new CacheControlHeaderValue();
if (!TrySetCacheControlValues(result, nameValueList))
{
}
#endif
- public HttpContentHeaders Headers
- {
- get
- {
- if (_headers == null)
- {
- _headers = new HttpContentHeaders(this);
- }
- return _headers;
- }
- }
+ public HttpContentHeaders Headers => _headers ??= new HttpContentHeaders(this);
private bool IsBuffered
{
{
if (IsEnabled())
{
- if (arg1 == null) arg1 = "";
- if (arg2 == null) arg2 = "";
- if (arg4 == null) arg4 = "";
+ arg1 ??= "";
+ arg2 ??= "";
+ arg4 ??= "";
fixed (char* arg1Ptr = arg1)
fixed (char* arg2Ptr = arg2)
{
if (IsEnabled())
{
- if (arg4 == null) arg4 = "";
- if (arg5 == null) arg5 = "";
+ arg4 ??= "";
+ arg5 ??= "";
fixed (char* string4Bytes = arg4)
fixed (char* string5Bytes = arg5)
{
// Close the QuicConnection in the background.
- if (_connectionClosedTask == null)
- {
- _connectionClosedTask = _connection.CloseAsync((long)Http3ErrorCode.NoError).AsTask();
- }
+ _connectionClosedTask ??= _connection.CloseAsync((long)Http3ErrorCode.NoError).AsTask();
QuicConnection connection = _connection;
_connection = null;
{
lock (SyncObj)
{
- if (_http3ConnectionCreateLock == null)
- {
- _http3ConnectionCreateLock = new SemaphoreSlim(1);
- }
+ _http3ConnectionCreateLock ??= new SemaphoreSlim(1);
}
}
Uri? allProxy = GetUriFromString(Environment.GetEnvironmentVariable(EnvAllProxyLC)) ??
GetUriFromString(Environment.GetEnvironmentVariable(EnvAllProxyUC));
- if (httpProxy == null)
- {
- httpProxy = allProxy;
- }
-
- if (httpsProxy == null)
- {
- httpsProxy = allProxy;
- }
+ httpProxy ??= allProxy;
+ httpsProxy ??= allProxy;
}
// Do not instantiate if nothing is set.
{
Uri? allProxy = GetUriFromString(Environment.GetEnvironmentVariable(EnvAllProxyUC));
- if (httpProxy == null)
- {
- httpProxy = allProxy;
- }
-
- if (httpsProxy == null)
- {
- httpsProxy = allProxy;
- }
+ httpProxy ??= allProxy;
+ httpsProxy ??= allProxy;
}
// Do not instantiate if nothing is set.
// This can be used to cache the results of HttpListener.AuthenticationSchemeSelectorDelegate.
internal AuthenticationSchemes AuthenticationSchemes { get; set; }
- public HttpListenerResponse Response
- {
- get
- {
- if (_response == null)
- {
- _response = new HttpListenerResponse(this);
- }
-
- return _response;
- }
- }
+ public HttpListenerResponse Response => _response ??= new HttpListenerResponse(this);
public Task<HttpListenerWebSocketContext> AcceptWebSocketAsync(string? subProtocol)
{
{
_cookies = ParseCookies(RequestUri, cookieString);
}
- if (_cookies == null)
- {
- _cookies = new CookieCollection();
- }
+
+ _cookies ??= new CookieCollection();
}
return _cookies;
}
internal void AddByte(byte b)
{
- {
- if (_byteBuffer == null)
- _byteBuffer = new byte[_bufferSize];
+ _byteBuffer ??= new byte[_bufferSize];
- _byteBuffer[_numBytes++] = b;
- }
+ _byteBuffer[_numBytes++] = b;
}
internal string GetString()
{
get
{
- if (_statusDescription == null)
- {
- // if the user hasn't set this, generated on the fly, if possible.
- // We know this one is safe, no need to verify it as in the setter.
- _statusDescription = HttpStatusDescription.Get(StatusCode);
- }
- if (_statusDescription == null)
- {
- _statusDescription = string.Empty;
- }
- return _statusDescription;
+ // if the user hasn't set this, generate on the fly, if possible.
+ // We know this one is safe, no need to verify it as in the setter.
+ return _statusDescription ??= HttpStatusDescription.Get(StatusCode) ?? string.Empty;
}
set
{
return true;
}
- var c2 = c as X509Certificate2;
- if (c2 == null)
- {
- c2 = new X509Certificate2(c.GetRawCertData());
- }
-
- _clientCert = c2;
+ _clientCert = c as X509Certificate2 ?? new X509Certificate2(c.GetRawCertData());
_clientCertErrors = new int[] { (int)e };
return true;
});
public void BeginReadRequest()
{
- if (_buffer == null)
- _buffer = new byte[BufferSize];
+ _buffer ??= new byte[BufferSize];
try
{
if (_reuses == 1)
private string? ReadLine(byte[] buffer, int offset, int len, ref int used)
{
- if (_currentLine == null)
- _currentLine = new StringBuilder(128);
+ _currentLine ??= new StringBuilder(128);
int last = offset + len;
used = 0;
for (int i = offset; i < last && _lineState != LineState.LF; i++)
private void EnsureResponseStream()
{
- if (_responseStream == null)
- {
- _responseStream = _httpContext!.Connection.GetResponseStream();
- }
+ _responseStream ??= _httpContext!.Connection.GetResponseStream();
}
public Version ProtocolVersion
{
lock (_locker)
{
- if (_handle == null)
- _handle = new ManualResetEvent(_completed);
+ _handle ??= new ManualResetEvent(_completed);
}
return _handle;
lock (_locker)
{
- if (_handle == null)
- _handle = new ManualResetEvent(_completed);
+ _handle ??= new ManualResetEvent(_completed);
}
return _handle;
private readonly List<string> _serviceNames;
private ServiceNameCollection? _serviceNameCollection;
- public ServiceNameCollection ServiceNames
- {
- get
- {
- if (_serviceNameCollection == null)
- {
- _serviceNameCollection = new ServiceNameCollection(_serviceNames);
- }
- return _serviceNameCollection;
- }
- }
+ public ServiceNameCollection ServiceNames => _serviceNameCollection ??= new ServiceNameCollection(_serviceNames);
public ServiceNameStore()
{
}
// HandleAuthentication may have cleaned this up.
- if (memoryBlob == null)
- {
- memoryBlob = new SyncRequestContext(checked((int)size));
- }
+ memoryBlob ??= new SyncRequestContext(checked((int)size));
requestId = 0;
}
ExtendedProtectionSelector? extendedProtectionSelector = _extendedProtectionSelectorDelegate;
if (extendedProtectionSelector != null)
{
- extendedProtectionPolicy = extendedProtectionSelector(httpContext.Request);
-
- if (extendedProtectionPolicy == null)
- {
- extendedProtectionPolicy = new ExtendedProtectionPolicy(PolicyEnforcement.Never);
- }
// Cache the results of extendedProtectionSelector (if any)
+ extendedProtectionPolicy = extendedProtectionSelector(httpContext.Request) ?? new ExtendedProtectionPolicy(PolicyEnforcement.Never);
httpContext.ExtendedProtectionPolicy = extendedProtectionPolicy;
}
if (challenge.Length > 0)
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, "challenge:" + challenge);
- if (challenges == null)
- {
- challenges = new ArrayList(4);
- }
+ challenges ??= new ArrayList(4);
challenges.Add(challenge);
}
}
{
get
{
- if (_webHeaders == null)
- {
- _webHeaders = Interop.HttpApi.GetHeaders(RequestBuffer, OriginalBlobAddress);
- }
+ _webHeaders ??= Interop.HttpApi.GetHeaders(RequestBuffer, OriginalBlobAddress);
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"webHeaders:{_webHeaders}");
return _webHeaders;
}
{
get
{
- if (_httpMethod == null)
- {
- _httpMethod = Interop.HttpApi.GetVerb(RequestBuffer, OriginalBlobAddress);
- }
+ _httpMethod ??= Interop.HttpApi.GetVerb(RequestBuffer, OriginalBlobAddress);
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"_httpMethod:{_httpMethod}");
return _httpMethod!;
}
}
- public Stream InputStream
- {
- get
- {
- if (_requestStream == null)
- {
- _requestStream = HasEntityBody ? new HttpRequestStream(HttpListenerContext) : Stream.Null;
- }
- return _requestStream;
- }
- }
+ public Stream InputStream => _requestStream ??= HasEntityBody ? new HttpRequestStream(HttpListenerContext) : Stream.Null;
public bool IsAuthenticated
{
{
get
{
- if (_localEndPoint == null)
- {
- _localEndPoint = Interop.HttpApi.GetLocalEndPoint(RequestBuffer, OriginalBlobAddress);
- }
+ _localEndPoint ??= Interop.HttpApi.GetLocalEndPoint(RequestBuffer, OriginalBlobAddress);
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"_localEndPoint={_localEndPoint}");
return _localEndPoint!;
}
{
get
{
- if (_requestUri == null)
- {
- _requestUri = HttpListenerRequestUriBuilder.GetRequestUri(
- _rawUrl!, RequestScheme, _cookedUrlHost!, _cookedUrlPath!, _cookedUrlQuery!);
- }
+ _requestUri ??= HttpListenerRequestUriBuilder.GetRequestUri(
+ _rawUrl!, RequestScheme, _cookedUrlHost!, _cookedUrlPath!, _cookedUrlQuery!);
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"_requestUri:{_requestUri}");
return _requestUri;
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
-using System.ComponentModel;
-using System.Diagnostics;
using Microsoft.Win32.SafeHandles;
namespace System.Net
{
ContentLength64 = responseEntity.Length;
}
+
EnsureResponseStream();
- Debug.Assert(_responseStream != null);
if (willBlock)
{
try
{
- _responseStream!.Write(responseEntity, 0, responseEntity.Length);
+ _responseStream.Write(responseEntity, 0, responseEntity.Length);
}
catch (Win32Exception)
{
}
finally
{
- _responseStream!.Close();
+ _responseStream.Close();
_responseState = ResponseState.Closed;
HttpListenerContext!.Close();
}
}
else
{
- _responseStream!.BeginWrite(responseEntity, 0, responseEntity.Length, new AsyncCallback(NonBlockingCloseCallback), null);
+ _responseStream.BeginWrite(responseEntity, 0, responseEntity.Length, new AsyncCallback(NonBlockingCloseCallback), null);
}
}
{
return;
}
+
EnsureResponseStream();
- _responseStream!.Close();
+ _responseStream.Close();
_responseState = ResponseState.Closed;
HttpListenerContext!.Close();
internal BoundaryType BoundaryType => _boundaryType;
+ [MemberNotNull(nameof(_responseStream))]
private void EnsureResponseStream()
{
- if (_responseStream == null)
- {
- _responseStream = new HttpResponseStream(HttpListenerContext!);
- }
+ _responseStream ??= new HttpResponseStream(HttpListenerContext!);
}
private void NonBlockingCloseCallback(IAsyncResult asyncResult)
{
lock (_thisLock)
{
- if (_receiveOperation == null)
- {
- _receiveOperation = new WebSocketOperation.ReceiveOperation(this);
- }
+ _receiveOperation ??= new WebSocketOperation.ReceiveOperation(this);
}
}
}
{
lock (_thisLock)
{
- if (_sendOperation == null)
- {
- _sendOperation = new WebSocketOperation.SendOperation(this);
- }
+ _sendOperation ??= new WebSocketOperation.SendOperation(this);
}
}
}
internal void PrepareEnvelopeHeaders(bool sendEnvelope, bool allowUnicode)
{
- if (_headersEncoding == null)
- {
- _headersEncoding = Encoding.GetEncoding(MimeBasePart.DefaultCharSet);
- }
+ _headersEncoding ??= Encoding.GetEncoding(MimeBasePart.DefaultCharSet);
EncodeHeaders(EnvelopeHeaders, allowUnicode);
internal void PrepareHeaders(bool sendEnvelope, bool allowUnicode)
{
- string headerName;
-
- if (_headersEncoding == null)
- {
- _headersEncoding = Encoding.GetEncoding(MimeBasePart.DefaultCharSet);
- }
+ _headersEncoding ??= Encoding.GetEncoding(MimeBasePart.DefaultCharSet);
//ContentType is written directly to the stream so remove potential user duplicate
Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.ContentType)!);
// add sender to headers first so that it is written first to allow the IIS smtp svc to
// send MAIL FROM with the sender if both sender and from are present
- headerName = MailHeaderInfo.GetString(MailHeaderID.Sender)!;
+ string headerName = MailHeaderInfo.GetString(MailHeaderID.Sender)!;
if (Sender != null)
{
Headers.InternalAdd(headerName, Sender.Encode(headerName.Length, allowUnicode));
if (NetEventSource.Log.IsEnabled()) NetEventSource.Associate(this, _transport);
_onSendCompletedDelegate = new SendOrPostCallback(SendCompletedWaitCallback);
- if (_host != null && _host.Length != 0)
+ if (!string.IsNullOrEmpty(_host))
{
_host = _host.Trim();
}
_port = DefaultPort;
}
- if (_targetName == null)
- _targetName = "SMTPSVC/" + _host;
+ _targetName ??= "SMTPSVC/" + _host;
if (_clientDomain == null)
{
{
if (_readState != ReadState.Done)
{
- if (_byteBuffer == null)
- {
- _byteBuffer = new byte[SmtpReplyReaderFactory.DefaultBufferSize];
- }
+ _byteBuffer ??= new byte[SmtpReplyReaderFactory.DefaultBufferSize];
while (0 != Read(caller, _byteBuffer, 0, _byteBuffer.Length)) ;
}
return Array.Empty<LineInfo>();
}
- if (_byteBuffer == null)
- {
- _byteBuffer = new byte[SmtpReplyReaderFactory.DefaultBufferSize];
- }
+ _byteBuffer ??= new byte[SmtpReplyReaderFactory.DefaultBufferSize];
System.Diagnostics.Debug.Assert(_readState == ReadState.Status0);
return;
}
- if (_parent._byteBuffer == null)
- {
- _parent._byteBuffer = new byte[SmtpReplyReaderFactory.DefaultBufferSize];
- }
+ _parent._byteBuffer ??= new byte[SmtpReplyReaderFactory.DefaultBufferSize];
System.Diagnostics.Debug.Assert(_parent._readState == ReadState.Status0);
get
{
//persist existing info before returning
- if (_headers == null)
- {
- _headers = new HeaderCollection();
- }
+ _headers ??= new HeaderCollection();
- if (_contentType == null)
- {
- _contentType = new ContentType();
- }
+ _contentType ??= new ContentType();
_contentType.PersistIfNeeded(_headers, false);
- if (_contentDisposition != null)
- {
- _contentDisposition.PersistIfNeeded(_headers, false);
- }
+ _contentDisposition?.PersistIfNeeded(_headers, false);
return _headers;
}
ContentType.Boundary = GetNextBoundary();
}
- internal Collection<MimeBasePart> Parts
- {
- get
- {
- if (_parts == null)
- {
- _parts = new Collection<MimeBasePart>();
- }
- return _parts;
- }
- }
+ internal Collection<MimeBasePart> Parts => _parts ??= new Collection<MimeBasePart>();
internal static void Complete(IAsyncResult result, Exception? e)
{
}
catch (Exception ex)
{
- if (e == null)
- {
- e = ex;
- }
+ e ??= ex;
}
context._completed = true;
context._result.InvokeCallback(e);
}
catch (Exception ex)
{
- if (e == null)
- {
- e = ex;
- }
+ e ??= ex;
}
context._completed = true;
context._result.InvokeCallback(e);
// now that the value is valid, ensure that internalObjects exists since we have to
// add to it
- if (_internalObjects == null)
- {
- _internalObjects = new Dictionary<string, object>();
- }
+ _internalObjects ??= new Dictionary<string, object>();
if (addValue)
{
{
// InternalSet is only used with objects that belong in internalObjects so we must always
// initialize it here
- if (_internalObjects == null)
- {
- _internalObjects = new Dictionary<string, object>();
- }
+ _internalObjects ??= new Dictionary<string, object>();
// always replace the existing value when we set internally
_internalObjects[key] = value;
internal void AddException(Exception e)
{
- if (_exceptions == null)
- {
- _exceptions = new List<Exception>();
- }
+ _exceptions ??= new List<Exception>();
_exceptions.Add(e);
}
}
internal void AddException(Exception e)
{
- if (_exceptions == null)
- {
- _exceptions = new List<Exception>();
- }
+ _exceptions ??= new List<Exception>();
_exceptions.Add(e);
}
}
// Cache correct handle.
InitialiseIcmpHandle();
- if (_replyBuffer == null)
- {
- _replyBuffer = SafeLocalAllocHandle.LocalAlloc(MaxUdpPacket);
- }
+ _replyBuffer ??= SafeLocalAllocHandle.LocalAlloc(MaxUdpPacket);
int error;
try
{
while ((dot < last) && (dot = fqdnRemote.IndexOf('.', dot + 1)) != -1)
{
- if (domainAttributeMatchOnlyCookieVariantPlain == null)
- {
- domainAttributeMatchOnlyCookieVariantPlain = new System.Collections.Generic.List<string>();
- }
-
// These candidates can only match CookieVariant.Plain cookies.
+ domainAttributeMatchOnlyCookieVariantPlain ??= new System.Collections.Generic.List<string>();
domainAttributeMatchOnlyCookieVariantPlain.Add(fqdnRemote.Substring(dot));
}
}
// In 'source' are already ordered.
// If two same cookies come from different 'source' then they
// will follow (not replace) each other.
- if (destination == null)
- {
- destination = new CookieCollection();
- }
+ destination ??= new CookieCollection();
destination.InternalAdd(cookie, false);
}
}
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Adding key:[{key}], cred:[{cred.Domain}],[{cred.UserName}]");
- if (_cache == null)
- {
- _cache = new Dictionary<CredentialKey, NetworkCredential>();
- }
-
+ _cache ??= new Dictionary<CredentialKey, NetworkCredential>();
_cache.Add(key, cred);
}
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Adding key:[{key}], cred:[{credential.Domain}],[{credential.UserName}]");
- if (_cacheForHosts == null)
- {
- _cacheForHosts = new Dictionary<CredentialHostKey, NetworkCredential>();
- }
-
+ _cacheForHosts ??= new Dictionary<CredentialHostKey, NetworkCredential>();
_cacheForHosts.Add(key, credential);
}
/// or standard IPv6 representation.
/// </para>
/// </devdoc>
- public override string ToString()
- {
- if (_toString == null)
- {
- _toString = IsIPv4 ?
- IPAddressParser.IPv4AddressToString(PrivateAddress) :
- IPAddressParser.IPv6AddressToString(_numbers!, PrivateScopeId);
- }
-
- return _toString;
- }
+ public override string ToString() =>
+ _toString ??= IsIPv4 ?
+ IPAddressParser.IPv4AddressToString(PrivateAddress) :
+ IPAddressParser.IPv6AddressToString(_numbers!, PrivateScopeId);
public bool TryFormat(Span<char> destination, out int charsWritten)
{
}
set
{
- if (_credentials == null)
- {
- _credentials = new WeakReference(null);
- }
+ _credentials ??= new WeakReference(null);
_credentials.Target = value;
}
}
}
networkCredential = new NetworkCredential(username, password);
}
- if (networkCredential == null)
- {
- networkCredential = s_defaultFtpNetworkCredential;
- }
- _authInfo = networkCredential;
+
+ _authInfo = networkCredential ?? s_defaultFtpNetworkCredential;
}
//
if (isAsync)
{
// non-null in the case of re-submit (recovery)
- if (_requestCompleteAsyncResult == null)
- _requestCompleteAsyncResult = new LazyAsyncResult(null, null, null);
+ _requestCompleteAsyncResult ??= new LazyAsyncResult(null, null, null);
return _connection!.SubmitRequest(this, true, true)!;
}
}
}
- private TimerThread.Queue TimerQueue
- {
- get
- {
- if (_timerQueue == null)
- {
- _timerQueue = TimerThread.GetOrCreateQueue(RemainingTimeout);
- }
-
- return _timerQueue;
- }
- }
+ private TimerThread.Queue TimerQueue => _timerQueue ??= TimerThread.GetOrCreateQueue(RemainingTimeout);
/// <summary>
/// <para>Returns true if we should restart the request after an error</para>
public override WebHeaderCollection Headers
{
- get
- {
- if (_ftpRequestHeaders == null)
- {
- _ftpRequestHeaders = new WebHeaderCollection();
- }
- return _ftpRequestHeaders;
- }
- set
- {
- _ftpRequestHeaders = value;
- }
+ get => _ftpRequestHeaders ??= new WebHeaderCollection();
+ set => _ftpRequestHeaders = value;
}
// NOT SUPPORTED method
{
lock (this)
{
- if (_ftpRequestHeaders == null)
- {
- _ftpRequestHeaders = new WebHeaderCollection();
- }
+ _ftpRequestHeaders ??= new WebHeaderCollection();
}
}
return _ftpRequestHeaders;
catch { };
}
- if (localId == null)
- {
- localId = IdOf(innerStream);
- }
+ localId ??= IdOf(innerStream);
SslStreamCtor(IdOf(sslStream), localId, remoteId);
}
{
Debug.Assert(e != null, $"Expected non-null Exception to be passed to {nameof(SetException)}");
- if (_exception == null)
- {
- _exception = ExceptionDispatchInfo.Capture(e);
- }
+ _exception ??= ExceptionDispatchInfo.Capture(e);
CloseContext();
}
{
issuers = GetRequestCertificateAuthorities();
remoteCert = CertificateValidationPal.GetRemoteCertificate(_securityContext);
- if (_sslAuthenticationOptions.ClientCertificates == null)
- {
- _sslAuthenticationOptions.ClientCertificates = new X509CertificateCollection();
- }
+ _sslAuthenticationOptions.ClientCertificates ??= new X509CertificateCollection();
clientCertificate = _sslAuthenticationOptions.CertSelectionDelegate(this, _sslAuthenticationOptions.TargetHost, _sslAuthenticationOptions.ClientCertificates, remoteCert, issuers);
}
finally
}
else
{
- if (chain == null)
- {
- chain = new X509Chain();
- }
-
+ chain ??= new X509Chain();
chain.ChainPolicy.RevocationMode = _sslAuthenticationOptions.CertificateRevocationCheckMode;
chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
PinSocketAddressBuffer();
// Create a WSAMessageBuffer if none exists yet.
- if (_wsaMessageBufferPinned == null)
- {
- _wsaMessageBufferPinned = GC.AllocateUninitializedArray<byte>(sizeof(Interop.Winsock.WSAMsg), pinned: true);
- }
+ _wsaMessageBufferPinned ??= GC.AllocateUninitializedArray<byte>(sizeof(Interop.Winsock.WSAMsg), pinned: true);
// Create and pin an appropriately sized control buffer if none already
IPAddress? ipAddress = (_socketAddress!.Family == AddressFamily.InterNetworkV6 ? _socketAddress.GetIPAddress() : null);
uint wsaRecvMsgWSABufferCount;
if (_bufferList == null)
{
- if (_wsaRecvMsgWSABufferArrayPinned == null)
- {
- _wsaRecvMsgWSABufferArrayPinned = GC.AllocateUninitializedArray<WSABuffer>(1, pinned: true);
- }
+ _wsaRecvMsgWSABufferArrayPinned ??= GC.AllocateUninitializedArray<WSABuffer>(1, pinned: true);
fixed (byte* bufferPtr = &MemoryMarshal.GetReference(_buffer.Span))
{
throw new InvalidOperationException(SR.net_notconnected);
}
- if (_dataStream == null)
- {
- _dataStream = new NetworkStream(Client, true);
- }
-
- return _dataStream;
+ return _dataStream ??= new NetworkStream(Client, true);
}
public void Close() => Dispose();
}
// Do we have an encoding guess? If not, use default.
- if (enc == null)
- {
- enc = Encoding;
- }
+ enc ??= Encoding;
// Calculate BOM length based on encoding guess. Then check for it in the data.
if (bomLengthInData == -1)
}
}
- private static HeaderInfoTable HeaderInfo
- {
- get
- {
- if (_headerInfo == null)
- {
- _headerInfo = new HeaderInfoTable();
- }
- return _headerInfo;
- }
- }
+ private static HeaderInfoTable HeaderInfo => _headerInfo ??= new HeaderInfoTable();
- private NameValueCollection InnerCollection
- {
- get
- {
- if (_innerCollection == null)
- _innerCollection = new NameValueCollection(ApproxHighAvgNumHeaders, CaseInsensitiveAscii.StaticInstance);
- return _innerCollection;
- }
- }
+ private NameValueCollection InnerCollection => _innerCollection ??= new NameValueCollection(ApproxHighAvgNumHeaders, CaseInsensitiveAscii.StaticInstance);
private bool AllowHttpResponseHeader
{
private static Guid GenerateGuidFromName(string name)
{
#if ES_BUILD_STANDALONE
- if (namespaceBytes == null)
- {
- namespaceBytes = new byte[] {
- 0x48, 0x2C, 0x2D, 0xB2, 0xC3, 0x90, 0x47, 0xC8,
- 0x87, 0xF8, 0x1A, 0x15, 0xBF, 0xC1, 0x30, 0xFB,
- };
- }
+ namespaceBytes ??= new byte[] {
+ 0x48, 0x2C, 0x2D, 0xB2, 0xC3, 0x90, 0x47, 0xC8,
+ 0x87, 0xF8, 0x1A, 0x15, 0xBF, 0xC1, 0x30, 0xFB,
+ };
#else
ReadOnlySpan<byte> namespaceBytes = new byte[] // rely on C# compiler optimization to remove byte[] allocation
{
internal void AddNullTerminatedString(string? value)
{
// Treat null strings as empty strings.
- if (value == null)
- {
- value = string.Empty;
- }
+ value ??= string.Empty;
// Calculate the size of the string including the trailing NULL char.
// Don't use value.Length here because string allows for embedded NULL characters.
this.name = eventAttrib.Name;
}
- if (this.name == null)
- {
- this.name = dataType.Name;
- }
+ this.name ??= dataType.Name;
}
}
}
calendarWeekRule = cultureData.CalendarWeekRule;
}
- if (amDesignator == null)
- {
- amDesignator = cultureData.AMDesignator;
- }
- if (pmDesignator == null)
- {
- pmDesignator = cultureData.PMDesignator;
- }
- if (timeSeparator == null)
- {
- timeSeparator = cultureData.TimeSeparator;
- }
- if (dateSeparator == null)
- {
- dateSeparator = cultureData.DateSeparator(calendarId);
- }
+ amDesignator ??= cultureData.AMDesignator;
+ pmDesignator ??= cultureData.PMDesignator;
+ timeSeparator ??= cultureData.TimeSeparator;
+ dateSeparator ??= cultureData.DateSeparator(calendarId);
allLongTimePatterns = _cultureData.LongTimes;
Debug.Assert(allLongTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long time patterns");
{
get
{
- if (amDesignator == null)
- {
- amDesignator = _cultureData.AMDesignator;
- }
-
+ amDesignator ??= _cultureData.AMDesignator;
Debug.Assert(amDesignator != null, "DateTimeFormatInfo.AMDesignator, amDesignator != null");
return amDesignator;
}
{
get
{
- if (dateSeparator == null)
- {
- dateSeparator = _cultureData.DateSeparator(Calendar.ID);
- }
+ dateSeparator ??= _cultureData.DateSeparator(Calendar.ID);
Debug.Assert(dateSeparator != null, "DateTimeFormatInfo.DateSeparator, dateSeparator != null");
return dateSeparator;
}
{
get
{
- if (pmDesignator == null)
- {
- pmDesignator = _cultureData.PMDesignator;
- }
-
+ pmDesignator ??= _cultureData.PMDesignator;
Debug.Assert(pmDesignator != null, "DateTimeFormatInfo.PMDesignator, pmDesignator != null");
return pmDesignator;
}
{
get
{
- if (timeSeparator == null)
- {
- timeSeparator = _cultureData.TimeSeparator;
- }
+ timeSeparator ??= _cultureData.TimeSeparator;
Debug.Assert(timeSeparator != null, "DateTimeFormatInfo.TimeSeparator, timeSeparator != null");
return timeSeparator;
}
return c;
}
- if (casingTable == null)
- {
- casingTable = InitOrdinalCasingPage(pageNumber);
- }
+ casingTable ??= InitOrdinalCasingPage(pageNumber);
return (char) casingTable[((int)c) & 0xFF];
}
i++;
if (hasLowerCase)
{
- if (lowercaseData == null)
- {
- lowercaseData = ToLower(str);
- }
+ lowercaseData ??= ToLower(str);
result.Append(lowercaseData, lowercaseStart, i - lowercaseStart);
}
else
{
if (hasLowerCase)
{
- if (lowercaseData == null)
- {
- lowercaseData = ToLower(str);
- }
+ lowercaseData ??= ToLower(str);
result.Append(lowercaseData, lowercaseStart, count);
}
else
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
_buffer = shadowBuffer;
}
+ [MemberNotNull(nameof(_buffer))]
private void EnsureBufferAllocated()
{
Debug.Assert(_bufferSize > 0);
// BufferedStream is not intended for multi-threaded use, so no worries about the get/set race on _buffer.
- if (_buffer == null)
- _buffer = new byte[_bufferSize];
+ _buffer ??= new byte[_bufferSize];
}
public Stream UnderlyingStream
// Ok. We can fill the buffer:
EnsureBufferAllocated();
- _readLen = _stream.Read(_buffer!, 0, _bufferSize);
+ _readLen = _stream.Read(_buffer, 0, _bufferSize);
bytesFromBuffer = ReadFromBuffer(buffer, offset, count);
{
// Otherwise, fill the buffer, then read from that.
EnsureBufferAllocated();
- _readLen = _stream.Read(_buffer!, 0, _bufferSize);
+ _readLen = _stream.Read(_buffer, 0, _bufferSize);
return ReadFromBuffer(destination) + bytesFromBuffer;
}
}
FlushWrite();
EnsureBufferAllocated();
- _readLen = _stream.Read(_buffer!, 0, _bufferSize);
+ _readLen = _stream.Read(_buffer, 0, _bufferSize);
_readPos = 0;
if (_readLen == 0)
return -1;
- return _buffer![_readPos++];
+ return _buffer[_readPos++];
}
private void WriteToBuffer(byte[] buffer, ref int offset, ref int count)
return;
EnsureBufferAllocated();
- Buffer.BlockCopy(buffer, offset, _buffer!, _writePos, bytesToWrite);
+ Buffer.BlockCopy(buffer, offset, _buffer, _writePos, bytesToWrite);
_writePos += bytesToWrite;
count -= bytesToWrite;
if (_options.RecurseSubdirectories && _remainingRecursionDepth > 0 && ShouldRecurseIntoEntry(ref entry))
{
// Recursion is on and the directory was accepted, Queue it
- if (_pending == null)
- _pending = new Queue<(string Path, int RemainingDepth)>();
+ _pending ??= new Queue<(string Path, int RemainingDepth)>();
_pending.Enqueue((Path.Join(_currentPath, entry.FileName), _remainingRecursionDepth - 1));
}
}
{
try
{
- if (_pending == null)
- _pending = new Queue<(IntPtr, string, int)>();
+ _pending ??= new Queue<(IntPtr, string, int)>();
_pending.Enqueue((subDirectoryHandle, subDirectory, _remainingRecursionDepth - 1));
}
catch
}
catch (Exception e)
{
- if (exception == null)
- exception = e;
+ exception ??= e;
}
}
else
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.stream);
}
- if (encoding == null)
- {
- encoding = Encoding.UTF8;
- }
+
if (!stream.CanRead)
{
throw new ArgumentException(SR.Argument_StreamNotReadable);
}
+
if (bufferSize == -1)
{
bufferSize = DefaultBufferSize;
}
_stream = stream;
- _encoding = encoding;
+ _encoding = encoding ??= Encoding.UTF8;
_decoder = encoding.GetDecoder();
if (bufferSize < MinBufferSize)
{
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.stream);
}
- if (encoding == null)
- {
- encoding = UTF8NoBOM;
- }
+
if (!stream.CanWrite)
{
throw new ArgumentException(SR.Argument_StreamNotWritable);
}
+
if (bufferSize == -1)
{
bufferSize = DefaultBufferSize;
}
_stream = stream;
- _encoding = encoding;
+ _encoding = encoding ?? UTF8NoBOM;
_encoder = _encoding.GetEncoder();
if (bufferSize < MinBufferSize)
{
}
- public override Encoding Encoding
- {
- get
- {
- if (s_encoding == null)
- {
- s_encoding = new UnicodeEncoding(false, false);
- }
- return s_encoding;
- }
- }
+ public override Encoding Encoding => s_encoding ??= new UnicodeEncoding(false, false);
// Returns the underlying StringBuilder. This is either the StringBuilder
// that was passed to the constructor, or the StringBuilder that was
get => CoreNewLineStr;
set
{
- if (value == null)
- {
- value = Environment.NewLineConst;
- }
+ value ??= Environment.NewLineConst;
CoreNewLineStr = value;
CoreNewLine = value.ToCharArray();
private void FlushBytes()
{
Debug.Assert(_numBytes > 0);
- if (_charBuffer == null)
- _charBuffer = new char[_bufferSize];
+ _charBuffer ??= new char[_bufferSize];
_numChars += _encoding.GetChars(_byteBuffer!, 0, _numBytes, _charBuffer, _numChars);
_numBytes = 0;
if (_numBytes > 0)
FlushBytes();
- if (_charBuffer == null)
- _charBuffer = new char[_bufferSize];
+ _charBuffer ??= new char[_bufferSize];
_charBuffer[_numChars++] = ch;
}
internal void AddByte(byte b)
{
- if (_byteBuffer == null)
- _byteBuffer = new byte[_bufferSize];
+ _byteBuffer ??= new byte[_bufferSize];
_byteBuffer[_numBytes++] = b;
}
{
get
{
- if (_fullName == null)
- {
- _fullName = string.IsNullOrEmpty(Profile) ?
- $"{Identifier}{ComponentSeparator + VersionKey + KeyValueSeparator + VersionValuePrefix}{Version}" :
- $"{Identifier}{ComponentSeparator + VersionKey + KeyValueSeparator + VersionValuePrefix}{Version}{ComponentSeparator + ProfileKey + KeyValueSeparator}{Profile}";
- }
+ _fullName ??= string.IsNullOrEmpty(Profile) ?
+ $"{Identifier}{ComponentSeparator + VersionKey + KeyValueSeparator + VersionValuePrefix}{Version}" :
+ $"{Identifier}{ComponentSeparator + VersionKey + KeyValueSeparator + VersionValuePrefix}{Version}{ComponentSeparator + ProfileKey + KeyValueSeparator}{Profile}";
Debug.Assert(_fullName != null);
return _fullName;
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex);
}
- if (value == null)
- {
- value = string.Empty;
- }
+ value ??= string.Empty;
+
if (startIndex > value.Length - length)
{
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_IndexLength);
}
// Check values and set defaults
- if (persistedString == null)
- {
- persistedString = string.Empty;
- }
+ persistedString ??= string.Empty;
if (persistedMaxCapacity < 1 || persistedString.Length > persistedMaxCapacity)
{
throw new SerializationException(SR.Serialization_StringBuilderMaxCapacity);
_waitThreadLock.Acquire();
try
{
- WaitThreadNode? current = _waitThreadsHead;
- if (current == null) // Lazily create the first wait thread.
- {
- _waitThreadsHead = current = new WaitThreadNode(new WaitThread());
- }
+ WaitThreadNode? current = _waitThreadsHead ??= new WaitThreadNode(new WaitThread()); // Lazily create the first wait thread.
// Register the wait handle on the first wait thread that is not at capacity.
WaitThreadNode prev;
Debug.Assert(exceptionObject != null, "AddFaultException(): Expected a non-null exceptionObject");
// Initialize the exceptions list if necessary. The list should be non-null iff it contains exceptions.
- List<ExceptionDispatchInfo>? exceptions = m_faultExceptions;
- if (exceptions == null) m_faultExceptions = exceptions = new List<ExceptionDispatchInfo>(1);
- else Debug.Assert(exceptions.Count > 0, "Expected existing exceptions list to have > 0 exceptions.");
+ List<ExceptionDispatchInfo>? exceptions = m_faultExceptions ??= new List<ExceptionDispatchInfo>(1);
// Handle Exception by capturing it into an ExceptionDispatchInfo and storing that
if (exceptionObject is Exception exception)
{
if (!_isScheduled)
{
- List<TimerQueue>? timers = s_scheduledTimers;
- if (timers == null)
- {
- timers = InitializeScheduledTimerManager_Locked();
- }
+ List<TimerQueue> timers = s_scheduledTimers ?? InitializeScheduledTimerManager_Locked();
timers.Add(this);
_isScheduled = true;
}
private Func<object>? _makeNewInstance;
- private Func<object> MakeNewInstance
- {
- get
- {
- if (_makeNewInstance == null)
- {
- _makeNewInstance = FastInvokerBuilder.GetMakeNewInstanceFunc(UnderlyingType);
- }
-
- return _makeNewInstance;
- }
- }
+ private Func<object> MakeNewInstance => _makeNewInstance ??= FastInvokerBuilder.GetMakeNewInstanceFunc(UnderlyingType);
internal bool CreateNewInstanceViaDefaultConstructor([NotNullWhen(true)] out object? obj)
{
set { _childElementNamespaces = value; }
}
- private static Type[] SerInfoCtorArgs
- {
- get
- {
- if (s_serInfoCtorArgs == null)
- s_serInfoCtorArgs = new Type[] { typeof(SerializationInfo), typeof(StreamingContext) };
- return s_serInfoCtorArgs;
- }
- }
+ private static Type[] SerInfoCtorArgs => s_serInfoCtorArgs ??= new Type[] { typeof(SerializationInfo), typeof(StreamingContext) };
internal struct Member
{
private Type _delegateType = null!; // initialized in BeginMethod
private static Module? s_serializationModule;
- private static Module SerializationModule
- {
- get
- {
- if (s_serializationModule == null)
- {
- s_serializationModule = typeof(CodeGenerator).Module; // could to be replaced by different dll that has SkipVerification set to false
- }
- return s_serializationModule;
- }
- }
+ private static Module SerializationModule => s_serializationModule ??= typeof(CodeGenerator).Module; // could to be replaced by different dll that has SkipVerification set to false
+
private DynamicMethod _dynamicMethod = null!; // initialized in BeginMethod
private ILGenerator _ilGen = null!; // initialized in BeginMethod
internal void CallStringFormat(string msg, params object[] values)
{
NewArray(typeof(object), values.Length);
- if (_stringFormatArray == null)
- _stringFormatArray = DeclareLocal(typeof(object[]), "stringFormatArray");
+ _stringFormatArray ??= DeclareLocal(typeof(object[]), "stringFormatArray");
Stloc(_stringFormatArray);
for (int i = 0; i < values.Length; i++)
StoreArrayElement(_stringFormatArray, i, values[i]);
}
else
{
- _itemContract = DataContract.GetDataContractFromGeneratedAssembly(ItemType);
- if (_itemContract == null)
- {
- _itemContract = DataContract.GetDataContract(ItemType);
- }
+ _itemContract =
+ DataContract.GetDataContractFromGeneratedAssembly(ItemType) ??
+ DataContract.GetDataContract(ItemType);
}
}
return _itemContract;
private static MethodInfo? s_buildIncrementCollectionCountDelegateMethod;
- private static MethodInfo BuildIncrementCollectionCountDelegateMethod
- {
- get
- {
- if (s_buildIncrementCollectionCountDelegateMethod == null)
- {
- s_buildIncrementCollectionCountDelegateMethod = typeof(CollectionDataContractCriticalHelper).GetMethod(nameof(BuildIncrementCollectionCountDelegate), Globals.ScanAllMembers)!;
- }
-
- return s_buildIncrementCollectionCountDelegateMethod;
- }
- }
+ private static MethodInfo BuildIncrementCollectionCountDelegateMethod =>
+ s_buildIncrementCollectionCountDelegateMethod ??= typeof(CollectionDataContractCriticalHelper).GetMethod(nameof(BuildIncrementCollectionCountDelegate), Globals.ScanAllMembers)!;
private static IncrementCollectionCountDelegate BuildIncrementCollectionCountDelegate<T>()
{
return (xmlwriter, obj, context) =>
{
context.IncrementCollectionCountGeneric<T>(xmlwriter, (ICollection<T>)obj);
-
};
}
private static MethodInfo? s_buildCreateGenericDictionaryEnumerator;
- private static MethodInfo GetBuildCreateGenericDictionaryEnumeratorMethodInfo
- {
- get
- {
- if (s_buildCreateGenericDictionaryEnumerator == null)
- {
- s_buildCreateGenericDictionaryEnumerator = typeof(CollectionDataContractCriticalHelper).GetMethod(nameof(BuildCreateGenericDictionaryEnumerator), Globals.ScanAllMembers)!;
- }
-
- return s_buildCreateGenericDictionaryEnumerator;
- }
- }
+ private static MethodInfo GetBuildCreateGenericDictionaryEnumeratorMethodInfo =>
+ s_buildCreateGenericDictionaryEnumerator ??= typeof(CollectionDataContractCriticalHelper).GetMethod(nameof(BuildCreateGenericDictionaryEnumerator), Globals.ScanAllMembers)!;
private static CreateGenericDictionaryEnumeratorDelegate BuildCreateGenericDictionaryEnumerator<K, V>()
{
getEnumeratorMethod = type.GetMethod(Globals.GetEnumeratorMethodName, BindingFlags.Instance | BindingFlags.Public, Type.EmptyTypes);
if (getEnumeratorMethod == null || !Globals.TypeOfIEnumerator.IsAssignableFrom(getEnumeratorMethod.ReturnType))
{
- Type? ienumerableInterface = interfaceType.GetInterfaces().Where(t => t.FullName!.StartsWith("System.Collections.Generic.IEnumerable")).FirstOrDefault();
- if (ienumerableInterface == null)
- ienumerableInterface = Globals.TypeOfIEnumerable;
+ Type? ienumerableInterface =
+ interfaceType.GetInterfaces().Where(t => t.FullName!.StartsWith("System.Collections.Generic.IEnumerable")).FirstOrDefault() ??
+ Globals.TypeOfIEnumerable;
getEnumeratorMethod = GetIEnumerableGetEnumeratorMethod(type, ienumerableInterface);
}
}
dataContract = s_dataContractCache[id];
if (dataContract == null)
{
- if (type == null)
- type = Type.GetTypeFromHandle(typeHandle)!;
-
+ type ??= Type.GetTypeFromHandle(typeHandle)!;
type = UnwrapNullableType(type);
dataContract = DataContract.GetDataContractFromGeneratedAssembly(type);
dataContract = s_dataContractCache[id];
if (dataContract == null)
{
- if (type == null)
- type = Type.GetTypeFromHandle(typeHandle)!;
+ type ??= Type.GetTypeFromHandle(typeHandle)!;
type = UnwrapNullableType(type);
type = GetDataContractAdapterType(type);
if (!CollectionDataContract.TryCreateGetOnlyCollectionDataContract(type, out dataContract))
lock (s_initBuiltInContractsLock)
{
- if (s_typeToBuiltInContract == null)
- s_typeToBuiltInContract = new Dictionary<Type, DataContract?>();
+ s_typeToBuiltInContract ??= new Dictionary<Type, DataContract?>();
DataContract? dataContract;
if (!s_typeToBuiltInContract.TryGetValue(type, out dataContract))
{
lock (s_initBuiltInContractsLock)
{
- if (s_nameToBuiltInContract == null)
- s_nameToBuiltInContract = new Dictionary<XmlQualifiedName, DataContract?>();
+ s_nameToBuiltInContract ??= new Dictionary<XmlQualifiedName, DataContract?>();
DataContract? dataContract;
XmlQualifiedName qname = new XmlQualifiedName(name, ns);
lock (s_initBuiltInContractsLock)
{
- if (s_nameToBuiltInContract == null)
- s_nameToBuiltInContract = new Dictionary<XmlQualifiedName, DataContract?>();
+ s_nameToBuiltInContract ??= new Dictionary<XmlQualifiedName, DataContract?>();
DataContract? dataContract;
XmlQualifiedName qname = new XmlQualifiedName(typeName);
{
lock (s_namespacesLock)
{
- if (s_namespaces == null)
- s_namespaces = new Dictionary<string, string>();
- string? value;
- if (s_namespaces.TryGetValue(key, out value))
+ s_namespaces ??= new Dictionary<string, string>();
+ if (s_namespaces.TryGetValue(key, out string? value))
+ {
return value;
+ }
+
try
{
s_namespaces.Add(key, key);
internal Type OriginalUnderlyingType
{
- get
- {
- if (_originalUnderlyingType == null)
- {
- _originalUnderlyingType = GetDataContractOriginalType(this._underlyingType);
- }
- return _originalUnderlyingType;
- }
- set
- {
- _originalUnderlyingType = value;
- }
+ get => _originalUnderlyingType ??= GetDataContractOriginalType(this._underlyingType);
+ set => _originalUnderlyingType = value;
}
+
internal virtual bool IsBuiltInDataContract
{
get
private static string GetDefaultDataContractNamespace(Type type)
{
- string? clrNs = type.Namespace;
- if (clrNs == null)
- clrNs = string.Empty;
- string? ns = GetGlobalDataContractNamespace(clrNs, type.Module.GetCustomAttributes(typeof(ContractNamespaceAttribute)).ToArray());
- if (ns == null)
- ns = GetGlobalDataContractNamespace(clrNs, type.Assembly.GetCustomAttributes(typeof(ContractNamespaceAttribute)).ToArray());
+ string? clrNs = type.Namespace ?? string.Empty;
+ string? ns =
+ GetGlobalDataContractNamespace(clrNs, type.Module.GetCustomAttributes(typeof(ContractNamespaceAttribute)).ToArray()) ??
+ GetGlobalDataContractNamespace(clrNs, type.Assembly.GetCustomAttributes(typeof(ContractNamespaceAttribute)).ToArray());
if (ns == null)
+ {
ns = GetDefaultStableNamespace(type);
+ }
else
+ {
CheckExplicitDataContractNamespaceUri(ns, type);
+ }
+
return ns;
}
internal static string GetDefaultStableNamespace(string? clrNs)
{
- if (clrNs == null) clrNs = string.Empty;
- return new Uri(Globals.DataContractXsdBaseNamespaceUri, clrNs).AbsoluteUri;
+ return new Uri(Globals.DataContractXsdBaseNamespaceUri, clrNs ?? string.Empty).AbsoluteUri;
}
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
for (int i = 0; i < nsAttributes.Length; i++)
{
ContractNamespaceAttribute nsAttribute = (ContractNamespaceAttribute)nsAttributes[i];
- string? clrNsInAttribute = nsAttribute.ClrNamespace;
- if (clrNsInAttribute == null)
- clrNsInAttribute = string.Empty;
+ string clrNsInAttribute = nsAttribute.ClrNamespace ?? string.Empty;
if (clrNsInAttribute == clrNs)
{
if (nsAttribute.ContractNamespace == null)
collectionDataContract.ItemType.GetGenericTypeDefinition() == Globals.TypeOfKeyValue)
{
DataContract itemDataContract = DataContract.GetDataContract(Globals.TypeOfKeyValuePair.MakeGenericType(collectionDataContract.ItemType.GetGenericArguments()));
- if (knownDataContracts == null)
- {
- knownDataContracts = new DataContractDictionary();
- }
+ knownDataContracts ??= new DataContractDictionary();
knownDataContracts.TryAdd(itemDataContract.StableName, itemDataContract);
}
public DataContractSerializer(Type type, DataContractSerializerSettings? settings)
{
- if (settings == null)
- {
- settings = new DataContractSerializerSettings();
- }
+ settings ??= new DataContractSerializerSettings();
Initialize(type, settings.RootName, settings.RootNamespace, settings.KnownTypes, settings.MaxItemsInObjectGraph, false,
settings.PreserveObjectReferences, settings.DataContractResolver, settings.SerializeReadOnlyTypes);
}
graph = SurrogateToDataContractType(_serializationSurrogateProvider, graph, declaredType, ref graphType);
}
- if (dataContractResolver == null)
- dataContractResolver = this.DataContractResolver;
+ dataContractResolver ??= this.DataContractResolver;
if (graph == null)
{
if (MaxItemsInObjectGraph == 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ExceededMaxItemsQuota, MaxItemsInObjectGraph)));
- if (dataContractResolver == null)
- dataContractResolver = this.DataContractResolver;
+ dataContractResolver ??= this.DataContractResolver;
if (verifyObjectName)
{
}
}
- private Dictionary<XmlQualifiedName, DataContract> Contracts
- {
- get
- {
- if (_contracts == null)
- {
- _contracts = new Dictionary<XmlQualifiedName, DataContract>();
- }
- return _contracts;
- }
- }
+ private Dictionary<XmlQualifiedName, DataContract> Contracts =>
+ _contracts ??= new Dictionary<XmlQualifiedName, DataContract>();
+
+ private Dictionary<DataContract, object> ProcessedContracts =>
+ _processedContracts ??= new Dictionary<DataContract, object>();
- private Dictionary<DataContract, object> ProcessedContracts
- {
- get
- {
- if (_processedContracts == null)
- {
- _processedContracts = new Dictionary<DataContract, object>();
- }
- return _processedContracts;
- }
- }
#if SUPPORT_SURROGATE
- private Hashtable SurrogateDataTable
- {
- get
- {
- if (_surrogateDataTable == null)
- _surrogateDataTable = new Hashtable();
- return _surrogateDataTable;
- }
- }
+ private Hashtable SurrogateDataTable => _surrogateDataTable ??= new Hashtable();
#endif
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
}
private FastInvokerBuilder.Getter? _getter;
- internal FastInvokerBuilder.Getter Getter
- {
- get
- {
- if (_getter == null)
- {
- _getter = FastInvokerBuilder.CreateGetter(MemberInfo);
- }
-
- return _getter;
- }
- }
+ internal FastInvokerBuilder.Getter Getter => _getter ??= FastInvokerBuilder.CreateGetter(MemberInfo);
private FastInvokerBuilder.Setter? _setter;
- internal FastInvokerBuilder.Setter Setter
- {
- get
- {
- if (_setter == null)
- {
- _setter = FastInvokerBuilder.CreateSetter(MemberInfo);
- }
-
- return _setter;
- }
- }
+ internal FastInvokerBuilder.Setter Setter => _setter ??= FastInvokerBuilder.CreateSetter(MemberInfo);
private sealed class CriticalHelper
{
}
#endif
- public Collection<Type> KnownTypes
- {
- get
- {
- if (_knownTypes == null)
- {
- _knownTypes = new Collection<Type>();
- }
- return _knownTypes;
- }
- }
+ public Collection<Type> KnownTypes => _knownTypes ??= new Collection<Type>();
}
}
private void GrowElementsIfNeeded()
{
if (_elements == null)
+ {
_elements = new ElementData[8];
+ }
else if (_elements.Length == _depth)
{
ElementData[] newElements = new ElementData[_elements.Length * 2];
public void AddAttribute(string prefix, string ns, string name, string? value)
{
GrowAttributesIfNeeded();
- AttributeData attribute = attributes[attributeCount];
- if (attribute == null)
- attributes[attributeCount] = attribute = new AttributeData();
+ AttributeData attribute = attributes[attributeCount] ??= new AttributeData();
attribute.prefix = prefix;
attribute.ns = ns;
attribute.localName = name;
private void GrowAttributesIfNeeded()
{
if (attributes == null)
+ {
attributes = new AttributeData[4];
+ }
else if (attributes.Length == attributeCount)
{
AttributeData[] newAttributes = new AttributeData[attributes.Length * 2];
internal void Add(string id, object? obj)
{
- if (_objectDictionary == null)
- _objectDictionary = new Dictionary<string, object?>();
+ _objectDictionary ??= new Dictionary<string, object?>();
if (_objectDictionary.ContainsKey(id))
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.MultipleIdDefinition, id)));
internal void Remove(string id)
{
- if (_objectDictionary != null)
- _objectDictionary.Remove(id);
+ _objectDictionary?.Remove(id);
}
internal object? GetObject(string id)
{
- if (_referencedObjectDictionary == null)
- {
- _referencedObjectDictionary = new Dictionary<string, object?>();
- _referencedObjectDictionary.Add(id, null);
- }
- else
- {
- _referencedObjectDictionary.TryAdd(id, null);
- }
+ _referencedObjectDictionary ??= new Dictionary<string, object?>();
+ _referencedObjectDictionary.TryAdd(id, null);
if (_objectDictionary != null)
{
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
public DataContractJsonSerializer(Type type, DataContractJsonSerializerSettings? settings)
{
- if (settings == null)
- {
- settings = new DataContractJsonSerializerSettings();
- }
+ settings ??= new DataContractJsonSerializerSettings();
XmlDictionaryString? rootName = (settings.RootName == null) ? null : new XmlDictionary(1).Add(settings.RootName);
Initialize(type, rootName, settings.KnownTypes, settings.MaxItemsInObjectGraph, settings.IgnoreExtensionDataObject,
while (collectionDataContract != null)
{
DataContract itemContract = collectionDataContract.ItemContract;
- if (_knownDataContracts == null)
- {
- _knownDataContracts = new Dictionary<XmlQualifiedName, DataContract>();
- }
+ _knownDataContracts ??= new Dictionary<XmlQualifiedName, DataContract>();
_knownDataContracts.TryAdd(itemContract.StableName, itemContract);
private void EnsureBuffers()
{
EnsureByteBuffer();
- if (_chars == null)
- {
- _chars = new char[BufferLength];
- }
+ _chars ??= new char[BufferLength];
}
[MemberNotNull(nameof(_bytes))]
return s_serializationExceptionCtor;
}
}
- public static Type[] SerInfoCtorArgs
- {
- get
- {
- if (s_serInfoCtorArgs == null)
- {
- s_serInfoCtorArgs = new Type[] { typeof(SerializationInfo), typeof(StreamingContext) };
- }
- return s_serInfoCtorArgs;
- }
- }
+ public static Type[] SerInfoCtorArgs => s_serInfoCtorArgs ??= new Type[] { typeof(SerializationInfo), typeof(StreamingContext) };
public static MethodInfo ThrowDuplicateMemberExceptionMethod
{
get
{
WriteStartElement(nameLocal: null, nameIndex: i + _childElementIndex);
}
- if (memberValue == null)
- memberValue = LoadMemberValue(member);
+
+ memberValue ??= LoadMemberValue(member);
WriteValue(memberValue);
WriteEndElement();
}
{
if (enumeratorType.IsInterface)
{
- if (moveNextMethod == null)
- moveNextMethod = JsonFormatGeneratorStatics.MoveNextMethod;
- if (getCurrentMethod == null)
- getCurrentMethod = JsonFormatGeneratorStatics.GetCurrentMethod;
+ moveNextMethod ??= JsonFormatGeneratorStatics.MoveNextMethod;
+ getCurrentMethod ??= JsonFormatGeneratorStatics.GetCurrentMethod;
}
else
{
}
}
}
- if (moveNextMethod == null)
- moveNextMethod = CollectionDataContract.GetTargetMethodWithName(Globals.MoveNextMethodName, enumeratorType, ienumeratorInterface)!;
- if (getCurrentMethod == null)
- getCurrentMethod = CollectionDataContract.GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface)!;
+
+ moveNextMethod ??= CollectionDataContract.GetTargetMethodWithName(Globals.MoveNextMethodName, enumeratorType, ienumeratorInterface)!;
+ getCurrentMethod ??= CollectionDataContract.GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface)!;
}
}
Type elementType = getCurrentMethod.ReturnType;
_dateTimeFormat = dateTimeFormat;
}
- internal XmlDictionaryReaderQuotas? ReaderQuotas
- {
- get
- {
- if (this.dictionaryReader == null)
- {
- return null;
- }
- else
- {
- return dictionaryReader.Quotas;
- }
- }
- }
+ internal XmlDictionaryReaderQuotas? ReaderQuotas => dictionaryReader?.Quotas;
- private DateTimeArrayJsonHelperWithString DateTimeArrayHelper
- {
- get
- {
- if (_dateTimeArrayHelper == null)
- {
- _dateTimeArrayHelper = new DateTimeArrayJsonHelperWithString(_dateTimeFormat);
- }
- return _dateTimeArrayHelper;
- }
- }
+ private DateTimeArrayJsonHelperWithString DateTimeArrayHelper =>
+ _dateTimeArrayHelper ??= new DateTimeArrayJsonHelperWithString(_dateTimeFormat);
internal static XmlQualifiedName ParseQualifiedName(string qname)
{
if (shouldWriteValue)
{
- if (memberValue == null)
- {
- memberValue = ReflectionGetMemberValue(obj, member);
- }
+ memberValue ??= ReflectionGetMemberValue(obj, member);
bool requiresNameAttribute = DataContractJsonSerializer.CheckIfXmlNameRequiresMapping(classContract.MemberNames![i]);
PrimitiveDataContract? primitiveContract = member.MemberPrimitiveContract;
if (requiresNameAttribute || !ReflectionTryWritePrimitive(xmlWriter, context, memberType, memberValue, memberNames[i + childElementIndex] /*name*/, null/*ns*/, primitiveContract))
if (val[i] == '\\')
{
i++;
- if (sb == null)
- {
- sb = new StringBuilder();
- }
+ sb ??= new StringBuilder();
sb.Append(val, startIndex, count);
Fx.Assert(i < val.Length, "Found that an '\' was the last character in a string. ReadServerTypeAttriute validates that the escape sequence is valid when it calls ReadQuotedText and ReadEscapedCharacter");
if (i >= val.Length)
get { return XmlSpace.None; }
}
- private static BinHexEncoding BinHexEncoding
- {
- get
- {
- if (s_binHexEncoding == null)
- {
- s_binHexEncoding = new BinHexEncoding();
- }
- return s_binHexEncoding;
- }
- }
+ private static BinHexEncoding BinHexEncoding =>
+ s_binHexEncoding ??= new BinHexEncoding();
private bool HasOpenAttribute => (_isWritingDataTypeAttribute || _isWritingServerTypeAttribute || IsWritingNameAttribute || _isWritingXmlnsAttribute);
{
encoding = null!;
}
- if (_nodeWriter == null)
- {
- _nodeWriter = new JsonNodeWriter();
- }
+
+ _nodeWriter ??= new JsonNodeWriter();
_nodeWriter.SetOutput(stream, ownsStream, encoding);
InitializeWriter();
{
throw new ArgumentException(SR.JsonInvalidLocalNameEmpty, nameof(localName));
}
- if (ns == null)
- {
- ns = string.Empty;
- }
- base.WriteQualifiedName(localName, ns);
+ base.WriteQualifiedName(localName, ns ?? string.Empty);
}
public override void WriteRaw(string data)
}
else
{
- if (text == null)
- {
- text = string.Empty;
- }
+ text ??= string.Empty;
// do work only when not indenting whitespace
if (!((_dataType == JsonDataType.Array || _dataType == JsonDataType.Object || _nodeType == JsonNodeType.EndElement) && XmlConverter.IsWhitespace(text)))
internal override void ReadAttributes(XmlReaderDelegator xmlReader)
{
- if (attributes == null)
- attributes = new Attributes();
+ attributes ??= new Attributes();
attributes.Reset();
if (xmlReader.MoveToAttribute(JsonGlobals.typeString) && xmlReader.Value == JsonGlobals.nullString)
}
else
{
- if (_objectDictionary == null)
- _objectDictionary = new Dictionary<object, object?>();
+ _objectDictionary ??= new Dictionary<object, object?>();
_objectDictionary.Add(obj, null);
_count++;
}
}
- internal MethodInfo XmlFormatReaderMethod
- {
- get
- {
- if (_helper.XmlFormatReaderMethod == null)
- {
- _helper.XmlFormatReaderMethod = typeof(XmlReaderDelegator).GetMethod(ReadMethodName, Globals.ScanAllMembers)!;
- }
- return _helper.XmlFormatReaderMethod;
- }
- }
+ internal MethodInfo XmlFormatReaderMethod =>
+ _helper.XmlFormatReaderMethod ??= typeof(XmlReaderDelegator).GetMethod(ReadMethodName, Globals.ScanAllMembers)!;
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext? context)
private static readonly Type[] s_arrayConstructorParameters = new Type[] { Globals.TypeOfInt };
private static readonly object[] s_arrayConstructorArguments = new object[] { 32 };
- private static MethodInfo CollectionSetItemDelegateMethod
- {
- get
- {
- if (s_getCollectionSetItemDelegateMethod == null)
- {
- s_getCollectionSetItemDelegateMethod = typeof(ReflectionReader).GetMethod(nameof(GetCollectionSetItemDelegate), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)!;
- }
- return s_getCollectionSetItemDelegateMethod!;
- }
- }
+ private static MethodInfo CollectionSetItemDelegateMethod =>
+ s_getCollectionSetItemDelegateMethod ??= typeof(ReflectionReader).GetMethod(nameof(GetCollectionSetItemDelegate), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)!;
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
public object ReflectionReadClass(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext? context, XmlDictionaryString[]? memberNames, XmlDictionaryString[]? memberNamespaces, ClassDataContract classContract)
if (shouldWriteValue)
{
bool writeXsiType = CheckIfMemberHasConflict(member, classContract, derivedMostClassContract);
- if (memberValue == null)
- {
- memberValue = ReflectionGetMemberValue(obj, member);
- }
+ memberValue ??= ReflectionGetMemberValue(obj, member);
PrimitiveDataContract? primitiveContract = member.MemberPrimitiveContract;
if (writeXsiType || !ReflectionTryWritePrimitive(xmlWriter, context, memberType, memberValue, memberNames[i + childElementIndex] /*name*/, ns, primitiveContract))
get { return _schemas; }
}
- private XmlDocument XmlDoc
- {
- get
- {
- if (_xmlDoc == null)
- _xmlDoc = new XmlDocument();
- return _xmlDoc;
- }
- }
+ private XmlDocument XmlDoc => _xmlDoc ??= new XmlDocument();
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
internal void Export()
{
if ((object)schemaItem == (object)providerXsdType)
{
- typeNs = schema.TargetNamespace;
- if (typeNs == null)
- typeNs = string.Empty;
+ typeNs = schema.TargetNamespace ?? string.Empty;
break;
}
}
}
private static XmlQualifiedName? s_anytypeQualifiedName;
- internal static XmlQualifiedName AnytypeQualifiedName
- {
- get
- {
- if (s_anytypeQualifiedName == null)
- s_anytypeQualifiedName = new XmlQualifiedName(Globals.AnyTypeLocalName, Globals.SchemaNamespace);
- return s_anytypeQualifiedName;
- }
- }
+ internal static XmlQualifiedName AnytypeQualifiedName => s_anytypeQualifiedName ??= new XmlQualifiedName(Globals.AnyTypeLocalName, Globals.SchemaNamespace);
private static XmlQualifiedName? s_stringQualifiedName;
- internal static XmlQualifiedName StringQualifiedName
- {
- get
- {
- if (s_stringQualifiedName == null)
- s_stringQualifiedName = new XmlQualifiedName(Globals.StringLocalName, Globals.SchemaNamespace);
- return s_stringQualifiedName;
- }
- }
+ internal static XmlQualifiedName StringQualifiedName => s_stringQualifiedName ??= new XmlQualifiedName(Globals.StringLocalName, Globals.SchemaNamespace);
private static XmlQualifiedName? s_defaultEnumBaseTypeName;
- internal static XmlQualifiedName DefaultEnumBaseTypeName
- {
- get
- {
- if (s_defaultEnumBaseTypeName == null)
- s_defaultEnumBaseTypeName = new XmlQualifiedName(Globals.IntLocalName, Globals.SchemaNamespace);
- return s_defaultEnumBaseTypeName;
- }
- }
+ internal static XmlQualifiedName DefaultEnumBaseTypeName => s_defaultEnumBaseTypeName ??= new XmlQualifiedName(Globals.IntLocalName, Globals.SchemaNamespace);
private static XmlQualifiedName? s_enumerationValueAnnotationName;
- internal static XmlQualifiedName EnumerationValueAnnotationName
- {
- get
- {
- if (s_enumerationValueAnnotationName == null)
- s_enumerationValueAnnotationName = new XmlQualifiedName(Globals.EnumerationValueLocalName, Globals.SerializationNamespace);
- return s_enumerationValueAnnotationName;
- }
- }
+ internal static XmlQualifiedName EnumerationValueAnnotationName => s_enumerationValueAnnotationName ??= new XmlQualifiedName(Globals.EnumerationValueLocalName, Globals.SerializationNamespace);
private static XmlQualifiedName? s_surrogateDataAnnotationName;
- internal static XmlQualifiedName SurrogateDataAnnotationName
- {
- get
- {
- if (s_surrogateDataAnnotationName == null)
- s_surrogateDataAnnotationName = new XmlQualifiedName(Globals.SurrogateDataLocalName, Globals.SerializationNamespace);
- return s_surrogateDataAnnotationName;
- }
- }
+ internal static XmlQualifiedName SurrogateDataAnnotationName => s_surrogateDataAnnotationName ??= new XmlQualifiedName(Globals.SurrogateDataLocalName, Globals.SerializationNamespace);
private static XmlQualifiedName? s_defaultValueAnnotation;
- internal static XmlQualifiedName DefaultValueAnnotation
- {
- get
- {
- if (s_defaultValueAnnotation == null)
- s_defaultValueAnnotation = new XmlQualifiedName(Globals.DefaultValueLocalName, Globals.SerializationNamespace);
- return s_defaultValueAnnotation;
- }
- }
+ internal static XmlQualifiedName DefaultValueAnnotation => s_defaultValueAnnotation ??= new XmlQualifiedName(Globals.DefaultValueLocalName, Globals.SerializationNamespace);
private static XmlQualifiedName? s_actualTypeAnnotationName;
- internal static XmlQualifiedName ActualTypeAnnotationName
- {
- get
- {
- if (s_actualTypeAnnotationName == null)
- s_actualTypeAnnotationName = new XmlQualifiedName(Globals.ActualTypeLocalName, Globals.SerializationNamespace);
- return s_actualTypeAnnotationName;
- }
- }
+ internal static XmlQualifiedName ActualTypeAnnotationName => s_actualTypeAnnotationName ??= new XmlQualifiedName(Globals.ActualTypeLocalName, Globals.SerializationNamespace);
private static XmlQualifiedName? s_isDictionaryAnnotationName;
- internal static XmlQualifiedName IsDictionaryAnnotationName
- {
- get
- {
- if (s_isDictionaryAnnotationName == null)
- s_isDictionaryAnnotationName = new XmlQualifiedName(Globals.IsDictionaryLocalName, Globals.SerializationNamespace);
- return s_isDictionaryAnnotationName;
- }
- }
+ internal static XmlQualifiedName IsDictionaryAnnotationName => s_isDictionaryAnnotationName ??= new XmlQualifiedName(Globals.IsDictionaryLocalName, Globals.SerializationNamespace);
private static XmlQualifiedName? s_isValueTypeName;
- internal static XmlQualifiedName IsValueTypeName
- {
- get
- {
- if (s_isValueTypeName == null)
- s_isValueTypeName = new XmlQualifiedName(Globals.IsValueTypeLocalName, Globals.SerializationNamespace);
- return s_isValueTypeName;
- }
- }
+ internal static XmlQualifiedName IsValueTypeName => s_isValueTypeName ??= new XmlQualifiedName(Globals.IsValueTypeLocalName, Globals.SerializationNamespace);
// Property is not stored in a local because XmlSchemaAttribute is mutable.
// The schema export process should not expose objects that may be modified later.
internal static XmlSchema GetSchema(string ns, XmlSchemaSet schemas)
{
- if (ns == null) { ns = string.Empty; }
+ ns ??= string.Empty;
ICollection currentSchemas = schemas.Schemas();
foreach (XmlSchema schema in currentSchemas)
internal void Push(DataContractDictionary dataContractDictionary)
{
if (dataContractDictionaries == null)
+ {
dataContractDictionaries = new DataContractDictionary[4];
+ }
else if (_count == dataContractDictionaries.Length)
+ {
Array.Resize<DataContractDictionary>(ref dataContractDictionaries, dataContractDictionaries.Length * 2);
+ }
+
dataContractDictionaries[_count++] = dataContractDictionary;
}
context.AddNewObject(obj);
string objectId = context.GetObjectId();
SerializationInfo serInfo = context.ReadSerializationInfo(xmlReader, objType);
- object? newObj = SerializationSurrogateSetObjectData(obj, serInfo, context.GetStreamingContext());
- if (newObj == null)
- newObj = obj;
+ object? newObj = SerializationSurrogateSetObjectData(obj, serInfo, context.GetStreamingContext()) ?? obj;
if (newObj is IDeserializationCallback)
((IDeserializationCallback)newObj).OnDeserialization(null);
if (newObj is IObjectReference)
internal static MethodInfo WriteExtensionDataMethod
{
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
- get
- {
- if (s_writeExtensionDataMethod == null)
- {
- s_writeExtensionDataMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("WriteExtensionData", Globals.ScanAllMembers)!;
- }
- return s_writeExtensionDataMethod;
- }
+ get => s_writeExtensionDataMethod ??= typeof(XmlObjectSerializerWriteContext).GetMethod("WriteExtensionData", Globals.ScanAllMembers)!;
}
private static MethodInfo? s_writeXmlValueMethod;
_ilg.LoadArrayElement(_childElementNamespacesLocal!, i + _childElementIndex);
_ilg.Call(methodInfo: XmlFormatGeneratorStatics.WriteNamespaceDeclMethod);
}
- if (memberValue == null)
- memberValue = LoadMemberValue(member);
+
+ memberValue ??= LoadMemberValue(member);
WriteValue(memberValue, writeXsiType);
WriteEndElement();
}
{
if (enumeratorType.IsInterface)
{
- if (moveNextMethod == null)
- moveNextMethod = XmlFormatGeneratorStatics.MoveNextMethod;
- if (getCurrentMethod == null)
- getCurrentMethod = XmlFormatGeneratorStatics.GetCurrentMethod;
+ moveNextMethod ??= XmlFormatGeneratorStatics.MoveNextMethod;
+ getCurrentMethod ??= XmlFormatGeneratorStatics.GetCurrentMethod;
}
else
{
}
}
}
- if (moveNextMethod == null)
- moveNextMethod = CollectionDataContract.GetTargetMethodWithName(Globals.MoveNextMethodName, enumeratorType, ienumeratorInterface)!;
- if (getCurrentMethod == null)
- getCurrentMethod = CollectionDataContract.GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface)!;
+
+ moveNextMethod ??= CollectionDataContract.GetTargetMethodWithName(Globals.MoveNextMethodName, enumeratorType, ienumeratorInterface)!;
+ getCurrentMethod ??= CollectionDataContract.GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface)!;
}
}
Type elementType = getCurrentMethod.ReturnType;
}
private static IFormatterConverter? s_formatterConverter;
- internal static IFormatterConverter FormatterConverter
- {
- get
- {
- if (s_formatterConverter == null)
- {
- s_formatterConverter = new FormatterConverter();
- }
-
- return s_formatterConverter;
- }
- }
+ internal static IFormatterConverter FormatterConverter => s_formatterConverter ??= new FormatterConverter();
}
}
get { return _dataContractResolver; }
}
- protected KnownTypeDataContractResolver KnownTypeResolver
- {
- get
- {
- if (_knownTypeResolver == null)
- {
- _knownTypeResolver = new KnownTypeDataContractResolver(this);
- }
- return _knownTypeResolver;
- }
- }
+ protected KnownTypeDataContractResolver KnownTypeResolver =>
+ _knownTypeResolver ??= new KnownTypeDataContractResolver(this);
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
internal DataContract GetDataContract(Type type)
}
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
- private DataContract? ResolveDataContractFromKnownTypes(XmlQualifiedName typeName)
- {
- DataContract? dataContract = PrimitiveDataContract.GetPrimitiveDataContract(typeName.Name, typeName.Namespace);
- if (dataContract == null)
- {
- dataContract = scopedKnownTypes.GetDataContract(typeName);
- if (dataContract == null)
- {
- dataContract = GetDataContractFromSerializerKnownTypes(typeName);
- }
- }
- return dataContract;
- }
+ private DataContract? ResolveDataContractFromKnownTypes(XmlQualifiedName typeName) =>
+ PrimitiveDataContract.GetPrimitiveDataContract(typeName.Name, typeName.Namespace) ??
+ scopedKnownTypes.GetDataContract(typeName) ??
+ GetDataContractFromSerializerKnownTypes(typeName);
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
protected DataContract? ResolveDataContractFromKnownTypes(string typeName, string? typeNs, DataContract? memberTypeContract, Type? declaredType)
private object? _getOnlyCollectionValue;
private bool _isGetOnlyCollection;
- private HybridObjectCache DeserializedObjects
- {
- get
- {
- if (_deserializedObjects == null)
- _deserializedObjects = new HybridObjectCache();
- return _deserializedObjects;
- }
- }
+ private HybridObjectCache DeserializedObjects => _deserializedObjects ??= new HybridObjectCache();
private XmlDocument Document => _xmlDocument ??= new XmlDocument();
-
internal override bool IsGetOnlyCollection
{
get { return _isGetOnlyCollection; }
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
internal virtual object? InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract? dataContract, string? name, string? ns)
{
- if (dataContract == null)
- dataContract = GetDataContract(declaredType);
+ dataContract ??= GetDataContract(declaredType);
return InternalDeserialize(xmlReader, name, ns, declaredType, ref dataContract);
}
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
internal void HandleUnknownElement(XmlReaderDelegator xmlReader, ExtensionDataObject extensionData, int memberIndex)
{
- if (extensionData.Members == null)
- extensionData.Members = new List<ExtensionDataMember>();
+ extensionData.Members ??= new List<ExtensionDataMember>();
extensionData.Members.Add(ReadExtensionDataMember(xmlReader, memberIndex));
}
[MemberNotNull(nameof(attributes))]
internal virtual void ReadAttributes(XmlReaderDelegator xmlReader)
{
- if (attributes == null)
- attributes = new Attributes();
+ attributes ??= new Attributes();
attributes.Read(xmlReader);
}
internal void ResetAttributes()
{
- if (attributes != null)
- attributes.Reset();
+ attributes?.Reset();
}
internal string GetObjectId()
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
internal object? ReadIXmlSerializable(XmlReaderDelegator xmlReader, XmlDataContract xmlDataContract, bool isMemberType)
{
- if (_xmlSerializableReader == null)
- _xmlSerializableReader = new XmlSerializableReader();
+ _xmlSerializableReader ??= new XmlSerializableReader();
return ReadIXmlSerializable(_xmlSerializableReader, xmlReader, xmlDataContract, isMemberType);
}
if (nodeType != XmlNodeType.Element)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader));
- if (dataNode.Members == null)
- dataNode.Members = new List<ExtensionDataMember>();
+ dataNode.Members ??= new List<ExtensionDataMember>();
dataNode.Members.Add(ReadExtensionDataMember(xmlReader, memberIndex++));
}
xmlReader.ReadEndElement();
}
if (xmlReader.IsStartElement(dataNode.ItemName, dataNode.ItemNamespace!))
{
- if (dataNode.Items == null)
- dataNode.Items = new List<IDataNode?>();
+ dataNode.Items ??= new List<IDataNode?>();
dataNode.Items.Add(ReadExtensionDataValue(xmlReader));
}
else
var member = new ISerializableDataMember(xmlReader.LocalName);
member.Value = ReadExtensionDataValue(xmlReader);
- if (dataNode.Members == null)
- dataNode.Members = new List<ISerializableDataMember>();
+ dataNode.Members ??= new List<ISerializableDataMember>();
dataNode.Members.Add(member);
}
xmlReader.ReadEndElement();
string ns = xmlReader.NamespaceURI;
if (ns != Globals.SerializationNamespace && ns != Globals.SchemaInstanceNamespace)
{
- if (xmlAttributes == null)
- xmlAttributes = new List<XmlAttribute>();
+ xmlAttributes ??= new List<XmlAttribute>();
xmlAttributes.Add((XmlAttribute)Document.ReadNode(xmlReader.UnderlyingReader)!);
}
}
if (xmlReader.EOF)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.UnexpectedEndOfFile));
- if (xmlChildNodes == null)
- xmlChildNodes = new List<XmlNode>();
+ xmlChildNodes ??= new List<XmlNode>();
xmlChildNodes.Add(Document.ReadNode(xmlReader.UnderlyingReader)!);
}
xmlReader.ReadEndElement();
elementNs = ns;
}
else
+ {
couldBeCollectionData = (string.CompareOrdinal(elementName, name) == 0) &&
(string.CompareOrdinal(elementNs, ns) == 0);
+ }
}
}
else if (xmlReader.EOF)
else if (IsContentNode(xmlReader.NodeType))
couldBeClassData = couldBeISerializableData = couldBeCollectionData = false;
- if (_attributesInXmlData == null) _attributesInXmlData = new Attributes();
+ _attributesInXmlData ??= new Attributes();
_attributesInXmlData.Read(xmlReader);
XmlNode childNode = Document.ReadNode(xmlReader.UnderlyingReader)!;
_unsafeTypeForwardingEnabled = true;
}
- protected ObjectToIdCache SerializedObjects
- {
- get
- {
- if (_serializedObjects == null)
- _serializedObjects = new ObjectToIdCache();
- return _serializedObjects;
- }
- }
+ protected ObjectToIdCache SerializedObjects => _serializedObjects ??= new ObjectToIdCache();
internal override bool IsGetOnlyCollection
{
dataContract = GetDataContract(declaredTypeHandle, declaredType);
if (!WriteClrTypeInfo(xmlWriter, dataContract) && DataContractResolver != null)
{
- if (objectType == null)
- {
- objectType = Type.GetTypeFromHandle(objectTypeHandle)!;
- }
+ objectType ??= Type.GetTypeFromHandle(objectTypeHandle)!;
WriteResolvedTypeInfo(xmlWriter, objectType, declaredType);
}
}
internal void WriteIXmlSerializable(XmlWriterDelegator xmlWriter, object obj)
{
- if (_xmlSerializableWriter == null)
- _xmlSerializableWriter = new XmlSerializableWriter();
+ _xmlSerializableWriter ??= new XmlSerializableWriter();
WriteIXmlSerializable(xmlWriter, obj, _xmlSerializableWriter);
}
private void EnsureBuffers()
{
EnsureByteBuffer();
- if (_chars == null)
- _chars = new char[BufferLength];
+ _chars ??= new char[BufferLength];
}
[MemberNotNull(nameof(_bytes))]
if (id1 is null || id2 is null)
return false;
-#pragma warning suppress 56506 // Microsoft, checks for whether id1 and id2 are null done above.
if (id1.IsGuid && id2.IsGuid)
{
return id1._idLow == id2._idLow && id1._idHigh == id2._idHigh;
}
- private static Base64Encoding Base64Encoding
- {
- get
- {
- if (s_base64Encoding == null)
- s_base64Encoding = new Base64Encoding();
- return s_base64Encoding;
- }
- }
+ private static Base64Encoding Base64Encoding => s_base64Encoding ??= new Base64Encoding();
- private static BinHexEncoding BinHexEncoding
- {
- get
- {
- if (s_binHexEncoding == null)
- s_binHexEncoding = new BinHexEncoding();
- return s_binHexEncoding;
- }
- }
+ private static BinHexEncoding BinHexEncoding => s_binHexEncoding ??= new BinHexEncoding();
protected XmlBufferReader BufferReader
{
}
}
- if (_declarationNode == null)
- {
- _declarationNode = new XmlDeclarationNode(_bufferReader);
- }
+ _declarationNode ??= new XmlDeclarationNode(_bufferReader);
MoveToNode(_declarationNode);
return _declarationNode;
}
}
protected XmlCommentNode MoveToComment()
{
- if (_commentNode == null)
- {
- _commentNode = new XmlCommentNode(_bufferReader);
- }
+ _commentNode ??= new XmlCommentNode(_bufferReader);
MoveToNode(_commentNode);
return _commentNode;
}
protected XmlCDataNode MoveToCData()
{
- if (_cdataNode == null)
- {
- _cdataNode = new XmlCDataNode(_bufferReader);
- }
+ _cdataNode ??= new XmlCDataNode(_bufferReader);
MoveToNode(_cdataNode);
return _cdataNode;
}
protected XmlComplexTextNode MoveToComplexText()
{
- if (_complexTextNode == null)
- {
- _complexTextNode = new XmlComplexTextNode(_bufferReader);
- }
+ _complexTextNode ??= new XmlComplexTextNode(_bufferReader);
MoveToNode(_complexTextNode);
return _complexTextNode;
}
protected XmlTextNode MoveToWhitespaceText()
{
- if (_whitespaceTextNode == null)
- {
- _whitespaceTextNode = new XmlWhitespaceTextNode(_bufferReader);
- }
+ _whitespaceTextNode ??= new XmlWhitespaceTextNode(_bufferReader);
if (_nsMgr.XmlSpace == XmlSpace.Preserve)
_whitespaceTextNode.NodeType = XmlNodeType.SignificantWhitespace;
else
{
ArgumentNullException.ThrowIfNull(localName);
- if (namespaceUri == null)
- namespaceUri = string.Empty;
+ namespaceUri ??= string.Empty;
if (!_node.CanGetAttribute)
return null;
+
XmlAttributeNode[]? attributeNodes = _attributeNodes;
int attributeCount = _attributeCount;
int attributeIndex = _attributeStart;
{
ArgumentNullException.ThrowIfNull(localName);
- if (namespaceUri == null)
- namespaceUri = XmlDictionaryString.Empty;
+ namespaceUri ??= XmlDictionaryString.Empty;
if (!_node.CanGetAttribute)
return null;
+
XmlAttributeNode[]? attributeNodes = _attributeNodes;
int attributeCount = _attributeCount;
int attributeIndex = _attributeStart;
private void CheckAttributes(XmlAttributeNode[] attributeNodes, int attributeCount)
{
// For large numbers of attributes, sorting the attributes (n * lg(n)) is faster
- if (_attributeSorter == null)
- _attributeSorter = new AttributeSorter();
+ _attributeSorter ??= new AttributeSorter();
if (!_attributeSorter.Sort(attributeNodes, attributeCount))
{
_trailCharCount = (charCount % charBlock);
if (_trailCharCount > 0)
{
- if (_trailChars == null)
- _trailChars = new char[4];
+ _trailChars ??= new char[4];
charCount -= _trailCharCount;
Array.Copy(chars, charCount, _trailChars, 0, _trailCharCount);
}
{
if (byteCount < byteBlock)
{
- if (_trailBytes == null)
- _trailBytes = new byte[3];
+ _trailBytes ??= new byte[3];
_trailByteCount = encoding.GetBytes(chars, 0, charCount, _trailBytes, 0);
int actual = Math.Min(_trailByteCount, byteCount);
Buffer.BlockCopy(_trailBytes, 0, buffer, offset, actual);
}
}
- public override string Value
- {
- get
- {
- if (_value == null)
- {
- _value = _node.ValueAsString;
- }
-
- return _value;
- }
- }
+ public override string Value => _value ??= _node.ValueAsString;
public override Type ValueType
{
if (_signing)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlCanonicalizationStarted));
- if (_signingWriter == null)
- _signingWriter = CreateSigningNodeWriter();
+ _signingWriter ??= CreateSigningNodeWriter();
_signingWriter.SetOutput(XmlNodeWriter.Null, stream, includeComments, inclusivePrefixes);
_nsMgr.Sign(_signingWriter);
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlWriterClosed));
}
- private static BinHexEncoding BinHexEncoding
- {
- get
- {
- if (_binhexEncoding == null)
- _binhexEncoding = new BinHexEncoding();
- return _binhexEncoding;
- }
- }
+ private static BinHexEncoding BinHexEncoding => _binhexEncoding ??= new BinHexEncoding();
public override string? XmlLang
{
if (_writeState == WriteState.Attribute)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlInvalidWriteState, "WriteCData", WriteState.ToString())));
- if (text == null)
- text = string.Empty;
+ text ??= string.Empty;
if (text.Length > 0)
{
Element element = EnterScope();
if (ns == null)
{
- if (prefix == null)
- prefix = string.Empty;
+ prefix ??= string.Empty;
ns = _nsMgr.LookupNamespace(prefix);
Element element = EnterScope();
if (ns == null)
{
- if (prefix == null)
- prefix = string.Empty;
+ prefix ??= string.Empty;
ns = _nsMgr.LookupNamespace(prefix);
if (IsClosed)
ThrowClosed();
ArgumentException.ThrowIfNullOrEmpty(localName);
- if (namespaceUri == null)
- namespaceUri = string.Empty;
+ namespaceUri ??= string.Empty;
string prefix = GetQualifiedNamePrefix(namespaceUri, null);
if (prefix.Length != 0)
{
ArgumentNullException.ThrowIfNull(localName);
if (localName.Value.Length == 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.InvalidLocalNameEmpty, nameof(localName)));
- if (namespaceUri == null)
- namespaceUri = XmlDictionaryString.Empty;
+ namespaceUri ??= XmlDictionaryString.Empty;
string prefix = GetQualifiedNamePrefix(namespaceUri.Value, namespaceUri);
FlushBase64();
if (IsClosed)
ThrowClosed();
- if (value == null)
- value = string.Empty;
+ value ??= string.Empty;
if (value.Length > 0 || _inList)
{
if (IsClosed)
ThrowClosed();
- if (value == null)
- value = string.Empty;
+ value ??= string.Empty;
if (value.Length > 0)
{
int totalByteCount = _trailByteCount + count;
int actualByteCount = totalByteCount - (totalByteCount % 3);
- if (_trailBytes == null)
- {
- _trailBytes = new byte[3];
- }
+ _trailBytes ??= new byte[3];
if (actualByteCount >= 3)
{
int totalByteCount = _trailByteCount + count;
int actualByteCount = totalByteCount - (totalByteCount % 3);
- if (_trailBytes == null)
- {
- _trailBytes = new byte[3];
- }
+ _trailBytes ??= new byte[3];
if (actualByteCount >= 3)
{
if (Signing)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlCanonicalizationStarted));
FlushElement();
- if (_signingWriter == null)
- _signingWriter = CreateSigningNodeWriter();
+ _signingWriter ??= CreateSigningNodeWriter();
_signingWriter.SetOutput(_writer, stream, includeComments, inclusivePrefixes);
_writer = _signingWriter;
SignScope(_signingWriter.CanonicalWriter);
xmlString = new XmlDictionaryString(this, value, id);
if (id >= MaxArrayEntries)
{
- if (_stringDict == null)
- _stringDict = new Dictionary<int, XmlDictionaryString>();
+ _stringDict ??= new Dictionary<int, XmlDictionaryString>();
_stringDict.Add(id, xmlString);
}
}
else
{
- if (_captureStream == null)
- _captureStream = new MemoryStream();
+ _captureStream ??= new MemoryStream();
if (trailByteCount > 0)
_captureStream.Write(trailBytes!, 0, trailByteCount);
{
ArgumentNullException.ThrowIfNull(stream);
- if (_writer == null)
- _writer = new XmlBinaryNodeWriter();
+ _writer ??= new XmlBinaryNodeWriter();
_writer.SetOutput(stream, dictionary, session, ownsStream);
SetOutput(_writer);
}
{
if (reader.CanReadValueChunk)
{
- if (_chars == null)
- {
- _chars = new char[256];
- }
+ _chars ??= new char[256];
int count;
while ((count = reader.ReadValueChunk(_chars, 0, _chars.Length)) > 0)
{
if (reader.CanReadBinaryContent)
{
// Its best to read in buffers that are a multiple of 3 so we don't break base64 boundaries when converting text
- if (_bytes == null)
- {
- _bytes = new byte[384];
- }
+ _bytes ??= new byte[384];
int count;
while ((count = reader.ReadValueAsBase64(_bytes, 0, _bytes.Length)) > 0)
{
if (_strings.TryGetValue(s.Value, out key))
{
- if (keys == null)
- {
- keys = AddKeys(s.Dictionary, s.Key + 1);
- }
+ keys ??= AddKeys(s.Dictionary, s.Key + 1);
keys[s.Key] = (key + 1);
return true;
public void SetBuffer(Stream stream, IXmlDictionary? dictionary, XmlBinaryReaderSession? session)
{
- if (_streamBuffer == null)
- {
- _streamBuffer = new byte[128];
- }
+ _streamBuffer ??= new byte[128];
SetBuffer(stream, _streamBuffer, 0, 0, dictionary, session);
_windowOffset = 0;
_windowOffsetMax = _streamBuffer.Length;
public Guid GetGuid(int offset)
{
- if (_guid == null)
- _guid = new byte[16];
+ _guid ??= new byte[16];
System.Buffer.BlockCopy(_buffer, offset, _guid, 0, _guid.Length);
return new Guid(_guid);
}
private void ReadList(ValueHandle value)
{
- if (_listValue == null)
- {
- _listValue = new ValueHandle(this);
- }
+ _listValue ??= new ValueHandle(this);
int count = 0;
int offset = this.Offset;
while (true)
{
ArgumentNullException.ThrowIfNull(stream);
- if (_writer == null)
- {
- _writer = new XmlUTF8NodeWriter(s_isEscapedAttributeChar, s_isEscapedElementChar);
- }
+ _writer ??= new XmlUTF8NodeWriter(s_isEscapedAttributeChar, s_isEscapedElementChar);
_writer.SetOutput(stream, false, null);
- if (_elementStream == null)
- {
- _elementStream = new MemoryStream();
- }
-
- if (_elementWriter == null)
- {
- _elementWriter = new XmlUTF8NodeWriter(s_isEscapedAttributeChar, s_isEscapedElementChar);
- }
+ _elementStream ??= new MemoryStream();
+ _elementWriter ??= new XmlUTF8NodeWriter(s_isEscapedAttributeChar, s_isEscapedElementChar);
_elementWriter.SetOutput(_elementStream, false, null);
if (_xmlnsAttributes == null)
private static Base64Encoding? s_base64Encoding;
- public static Base64Encoding Base64Encoding
- {
- get
- {
- if (s_base64Encoding == null)
- s_base64Encoding = new Base64Encoding();
- return s_base64Encoding;
- }
- }
+ public static Base64Encoding Base64Encoding => s_base64Encoding ??= new Base64Encoding();
- private static UTF8Encoding UTF8Encoding
- {
- get
- {
- if (s_utf8Encoding == null)
- s_utf8Encoding = new UTF8Encoding(false, true);
- return s_utf8Encoding;
- }
- }
+ private static UTF8Encoding UTF8Encoding => s_utf8Encoding ??= new UTF8Encoding(false, true);
- private static UnicodeEncoding UnicodeEncoding
- {
- get
- {
- if (s_unicodeEncoding == null)
- s_unicodeEncoding = new UnicodeEncoding(false, false, true);
- return s_unicodeEncoding;
- }
- }
+ private static UnicodeEncoding UnicodeEncoding => s_unicodeEncoding ??= new UnicodeEncoding(false, false, true);
public static bool ToBoolean(string value)
{
private XmlDictionaryString[]? _strings;
private int _nextId;
- public static IXmlDictionary Empty
- {
- get
- {
- if (s_empty == null)
- s_empty = new EmptyDictionary();
- return s_empty;
- }
- }
+ public static IXmlDictionary Empty => s_empty ??= new EmptyDictionary();
public XmlDictionary()
{
{
ArgumentNullException.ThrowIfNull(reader);
- XmlDictionaryReader? dictionaryReader = reader as XmlDictionaryReader;
-
- if (dictionaryReader == null)
- {
- dictionaryReader = new XmlWrappedReader(reader, null);
- }
-
- return dictionaryReader;
+ return reader as XmlDictionaryReader ?? new XmlWrappedReader(reader, null);
}
public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, XmlDictionaryReaderQuotas quotas)
}
else
{
- if (sb == null)
- sb = new StringBuilder(result);
+ sb ??= new StringBuilder(result);
if (sb.Length > maxStringContentLength - value.Length)
XmlExceptionHelper.ThrowMaxStringContentLengthExceeded(this, maxStringContentLength);
sb.Append(value);
}
else
{
- if (sb == null)
- sb = new StringBuilder(result);
+ sb ??= new StringBuilder(result);
if (sb.Length > maxStringContentLength - value.Length)
XmlExceptionHelper.ThrowMaxStringContentLengthExceeded(this, maxStringContentLength);
sb.Append(value);
internal byte[] ToUTF8()
{
- if (_buffer == null)
- _buffer = System.Text.Encoding.UTF8.GetBytes(_value);
- return _buffer;
+ return _buffer ??= System.Text.Encoding.UTF8.GetBytes(_value);
}
public override string ToString()
{
ArgumentNullException.ThrowIfNull(writer);
- XmlDictionaryWriter? dictionaryWriter = writer as XmlDictionaryWriter;
-
- if (dictionaryWriter == null)
- {
- dictionaryWriter = new XmlWrappedWriter(writer);
- }
-
- return dictionaryWriter;
+ return writer as XmlDictionaryWriter ?? new XmlWrappedWriter(writer);
}
public override Task WriteBase64Async(byte[] buffer, int index, int count)
{
ArgumentNullException.ThrowIfNull(localName);
- if (namespaceUri == null)
- namespaceUri = XmlDictionaryString.Empty;
-#pragma warning suppress 56506 // Microsoft, XmlDictionaryString.Empty is never null
+ namespaceUri ??= XmlDictionaryString.Empty;
WriteQualifiedName(localName.Value, namespaceUri.Value);
}
{
private static XmlNodeWriter? s_nullNodeWriter;
- public static XmlNodeWriter Null
- {
- get
- {
- if (s_nullNodeWriter == null)
- s_nullNodeWriter = new XmlNullNodeWriter();
- return s_nullNodeWriter;
- }
- }
+ public static XmlNodeWriter Null => s_nullNodeWriter ??= new XmlNullNodeWriter();
public abstract void Flush();
public virtual Task FlushAsync()
public void SetOutput(XmlNodeWriter writer, Stream stream, bool includeComments, string[]? inclusivePrefixes)
{
_writer = writer;
- if (_signingWriter == null)
- _signingWriter = new XmlCanonicalWriter();
+ _signingWriter ??= new XmlCanonicalWriter();
_signingWriter.SetOutput(stream, includeComments, inclusivePrefixes);
_chars = new byte[XmlConverter.MaxPrimitiveChars];
_base64Chars = null;
private void WriteBase64Text(byte[] buffer, int offset, int count)
{
- if (_base64Chars == null)
- _base64Chars = new byte[512];
+ _base64Chars ??= new byte[512];
Base64Encoding encoding = XmlConverter.Base64Encoding;
while (count >= 3)
{
private void GetPosition(out int row, out int column)
{
- if (_rowOffsets == null)
- {
- _rowOffsets = BufferReader.GetRows();
- }
+ _rowOffsets ??= BufferReader.GetRows();
int offset = BufferReader.Offset;
stream = new EncodingStreamWrapper(stream, encoding, true);
}
- if (_writer == null)
- {
- _writer = new XmlUTF8NodeWriter();
- }
+ _writer ??= new XmlUTF8NodeWriter();
_writer.SetOutput(stream, ownsStream, encoding);
SetOutput(_writer);
}
_inAttribute = false;
}
- private byte[] GetCharEntityBuffer()
- {
- if (_entityChars == null)
- {
- _entityChars = new byte[maxEntityLength];
- }
- return _entityChars;
- }
+ private byte[] GetCharEntityBuffer() => _entityChars ??= new byte[maxEntityLength];
private char[] GetCharBuffer(int charCount)
{
end = i;
}
- if (res == null)
- {
- res = str.Substring(start, end - start);
- }
+ res ??= str.Substring(start, end - start);
if (res == Localhost || res == Loopback)
{
return false;
}
- if (result is null)
- result = CreateHelper(newUriString!, dontEscape, UriKind.Absolute, ref e);
+ result ??= CreateHelper(newUriString!, dontEscape, UriKind.Absolute, ref e);
result?.DebugSetLeftCtor();
return e is null && result != null && result.IsAbsoluteUri;
}
break;
case XmlNodeType.EndElement:
- if (_currentContainer.content == null)
- {
- _currentContainer.content = string.Empty;
- }
+ _currentContainer.content ??= string.Empty;
if (_currentContainer == rootContainer) return false;
_currentContainer = _currentContainer.parent!;
break;
}
break;
case XmlNodeType.EndElement:
- if (_currentContainer.content == null)
- {
- _currentContainer.content = string.Empty;
- }
+ _currentContainer.content ??= string.Empty;
if (_currentContainer == rootContainer) return false;
_currentContainer = _currentContainer.parent!;
break;
}
case XmlNodeType.EndElement:
{
- if (_currentContainer.content == null)
- {
- _currentContainer.content = string.Empty;
- }
+ _currentContainer.content ??= string.Empty;
// Store the line info of the end element tag.
// Note that since we've got EndElement the current container must be an XElement
XElement? e = _currentContainer as XElement;
}
case XmlNodeType.EndElement:
{
- if (_currentContainer.content == null)
- {
- _currentContainer.content = string.Empty;
- }
+ _currentContainer.content ??= string.Empty;
// Store the line info of the end element tag.
// Note that since we've got EndElement the current container must be an XElement
XElement? e = _currentContainer as XElement;
/// <summary>
/// Gets a comparer that can compare the relative position of two nodes.
/// </summary>
- public static XNodeDocumentOrderComparer DocumentOrderComparer
- {
- get
- {
- if (s_documentOrderComparer == null) s_documentOrderComparer = new XNodeDocumentOrderComparer();
- return s_documentOrderComparer;
- }
- }
+ public static XNodeDocumentOrderComparer DocumentOrderComparer => s_documentOrderComparer ??= new XNodeDocumentOrderComparer();
/// <summary>
/// Gets a comparer that can compare two nodes for value equality.
/// </summary>
- public static XNodeEqualityComparer EqualityComparer
- {
- get
- {
- if (s_equalityComparer == null) s_equalityComparer = new XNodeEqualityComparer();
- return s_equalityComparer;
- }
- }
+ public static XNodeEqualityComparer EqualityComparer => s_equalityComparer ??= new XNodeEqualityComparer();
/// <overloads>
/// Adds the specified content immediately after this node. The
private void Add(object o)
{
- if (_content == null)
- {
- _content = new List<object>();
- }
+ _content ??= new List<object>();
_content.Add(o);
}
{
return false;
}
- XAttribute? a = _source as XAttribute;
- if (a == null)
- {
- a = _parent as XAttribute;
- }
+
+ XAttribute? a =
+ _source as XAttribute ??
+ _parent as XAttribute;
+
if (a != null)
{
if (a.parent != null)
}
return false;
}
- XAttribute? a = _source as XAttribute;
- if (a == null)
- {
- a = _parent as XAttribute;
- }
+
+ XAttribute? a =
+ _source as XAttribute ??
+ _parent as XAttribute;
+
if (a != null)
{
if (a.parent != null && ((XElement)a.parent).lastAttr != a)
private void ReplaceSchemaInfo(XObject o, XmlSchemaInfo schemaInfo)
{
- if (schemaInfos == null)
- {
- schemaInfos = new Dictionary<XmlSchemaInfo, XmlSchemaInfo>(new XmlSchemaInfoEqualityComparer());
- }
+ schemaInfos ??= new Dictionary<XmlSchemaInfo, XmlSchemaInfo>(new XmlSchemaInfoEqualityComparer());
XmlSchemaInfo? si = o.Annotation<XmlSchemaInfo>();
if (si != null)
{
}
break;
case XPathNamespaceScope.All:
- a = GetFirstNamespaceDeclarationGlobal(e);
- if (a == null)
- {
- a = GetXmlNamespaceDeclaration();
- }
+ a = GetFirstNamespaceDeclarationGlobal(e) ??
+ GetXmlNamespaceDeclaration();
break;
}
if (a != null)
{
public static XContainer? GetParent(this XObject obj)
{
- XContainer? ret = obj.Parent;
- if (ret == null)
- {
- ret = obj.Document;
- }
+ XContainer? ret = (XContainer?)obj.Parent ?? obj.Document;
if (ret == obj)
{
return null;
if (_leftOverBytesCount > 0)
{
count -= _leftOverBytesCount;
- if (_leftOverBytes == null)
- {
- _leftOverBytes = new byte[3];
- }
+ _leftOverBytes ??= new byte[3];
for (int i = 0; i < _leftOverBytesCount; i++)
{
_leftOverBytes[i] = buffer[index + count + i];
if (_leftOverBytesCount > 0)
{
count -= _leftOverBytesCount;
- if (_leftOverBytes == null)
- {
- _leftOverBytes = new byte[3];
- }
+ _leftOverBytes ??= new byte[3];
for (int i = 0; i < _leftOverBytesCount; i++)
{
_leftOverBytes[i] = buffer[index + count + i];
while (PeekToken() == BinXmlToken.CData)
{
_pos++; // skip over token byte
- if (sb == null)
- {
- sb = new StringBuilder(value.Length + value.Length / 2);
- sb.Append(value);
- }
+ sb ??= new StringBuilder(value.Length + value.Length / 2).Append(value);
sb.Append(ParseText());
}
if (sb != null)
{
int len;
- if (_bitStack == null)
- {
- _bitStack = new uint[16];
- }
+ _bitStack ??= new uint[16];
// Push current unsigned int (which has been filled) onto a stack
// and initialize this.curr to be used for future pushes.
IDtdAttributeInfo? idAttribute = attrList.LookupIdAttribute();
if (idAttribute != null)
{
- if (_elemIdMap == null)
- _elemIdMap = new Hashtable();
+ _elemIdMap ??= new Hashtable();
// Id was defined in DTD and DTD doesn't have notion of namespace so we should
// use prefix instead of namespace here. Schema already does this for us.
_elemIdMap.Add(new XmlQualifiedName(attrList.LocalName, attrList.Prefix),
- new XmlQualifiedName(idAttribute.LocalName, idAttribute.Prefix));
+ new XmlQualifiedName(idAttribute.LocalName, idAttribute.Prefix));
}
}
}
}
else
{
- if (bldr == null)
- {
- bldr = new StringBuilder();
- bldr.Append(s);
- }
+ bldr ??= new StringBuilder().Append(s);
bldr.Append(value);
}
}
{
base.RawText("<META http-equiv=\"Content-Type\"");
- if (_mediaType == null)
- {
- _mediaType = "text/html";
- }
+ _mediaType ??= "text/html";
base.RawText(" content=\"");
base.RawText(_mediaType);
{
base.RawText("<META http-equiv=\"Content-Type\"");
- if (_mediaType == null)
- {
- _mediaType = "text/html";
- }
+ _mediaType ??= "text/html";
base.RawText(" content=\"");
base.RawText(_mediaType);
public override void WriteWhitespace(string? ws)
{
- if (ws == null)
- {
- ws = string.Empty;
- }
+ ws ??= string.Empty;
// "checkNames" is intentional here; if false, the whitespace is checked in XmlWellformedWriter
if (_checkNames)
{
continue;
}
- if (sb == null)
- {
- sb = new StringBuilder(str.Length + 5);
- }
+ sb ??= new StringBuilder(str.Length + 5);
sb.Append(str, start, i - start);
}
else if (ch == '\r')
continue;
}
- if (sb == null)
- {
- sb = new StringBuilder(str.Length + 5);
- }
-
+ sb ??= new StringBuilder(str.Length + 5);
sb.Append(str, start, i - start);
i++;
}
public override Task WriteWhitespaceAsync(string? ws)
{
- if (ws == null)
- {
- ws = string.Empty;
- }
+ ws ??= string.Empty;
// "checkNames" is intentional here; if false, the whitespace is checked in XmlWellformedWriter
if (_checkNames)
// By default, convert base64 value to string and call WriteString.
public override void WriteBase64(byte[] buffer, int index, int count)
{
- if (_base64Encoder == null)
- {
- _base64Encoder = new XmlRawWriterBase64Encoder(this);
- }
+ _base64Encoder ??= new XmlRawWriterBase64Encoder(this);
// Encode will call WriteRaw to write out the encoded characters
_base64Encoder.Encode(buffer, index, count);
// By default, convert base64 value to string and call WriteString.
public override Task WriteBase64Async(byte[] buffer, int index, int count)
{
- if (_base64Encoder == null)
- {
- _base64Encoder = new XmlRawWriterBase64Encoder(this);
- }
+ _base64Encoder ??= new XmlRawWriterBase64Encoder(this);
+
// Encode will call WriteRaw to write out the encoded characters
return _base64Encoder.EncodeAsync(buffer, index, count);
}
}
else
{
- if (sb == null)
- {
- sb = new StringBuilder();
- sb.Append(value);
- }
+ sb ??= new StringBuilder().Append(value);
sb.Append(Value);
}
break;
}
else
{
- if (sb == null)
- {
- sb = new StringBuilder();
- sb.Append(value);
- }
+ sb ??= new StringBuilder().Append(value);
sb.Append(await GetValueAsync().ConfigureAwait(false));
}
break;
_nsManager.AddNamespace(prefix, ns);
int index = _nsAttrCount++;
- if (_nsAttributes == null)
- {
- _nsAttributes = new NodeData[InitialNamespaceAttributeCount];
- }
+ _nsAttributes ??= new NodeData[InitialNamespaceAttributeCount];
if (index == _nsAttributes.Length)
{
internal XmlTextReaderImpl(string xmlFragment, XmlNodeType fragType, XmlParserContext? context)
: this(null == context || null == context.NameTable ? new NameTable() : context.NameTable)
{
- if (xmlFragment == null)
- {
- xmlFragment = string.Empty;
- }
+ xmlFragment ??= string.Empty;
if (context == null)
{
{
if (_incReadDecoder != _readCharsDecoder)
{ // mixing ReadChars with ReadBase64 or ReadBinHex
- if (_readCharsDecoder == null)
- {
- _readCharsDecoder = new IncrementalReadCharsDecoder();
- }
+ _readCharsDecoder ??= new IncrementalReadCharsDecoder();
_readCharsDecoder.Reset();
_incReadDecoder = _readCharsDecoder;
}
return 0;
}
- if (_readCharsDecoder == null)
- {
- _readCharsDecoder = new IncrementalReadCharsDecoder();
- }
+ _readCharsDecoder ??= new IncrementalReadCharsDecoder();
InitIncrementalRead(_readCharsDecoder);
return IncrementalRead(buffer, index, count);
return 0;
}
- if (_base64Decoder == null)
- {
- _base64Decoder = new Base64Decoder();
- }
+ _base64Decoder ??= new Base64Decoder();
InitIncrementalRead(_base64Decoder);
return IncrementalRead(array, offset, len);
return 0;
}
- if (_binHexDecoder == null)
- {
- _binHexDecoder = new BinHexDecoder();
- }
+ _binHexDecoder ??= new BinHexDecoder();
InitIncrementalRead(_binHexDecoder);
return IncrementalRead(array, offset, len);
}
// detect & setup encoding
- if (encoding == null)
- {
- encoding = DetectEncoding();
- }
-
+ encoding ??= DetectEncoding();
SetupEncoding(encoding);
// eat preamble
}
Debug.Assert(nodeIndex < _nodes.Length);
- NodeData node = _nodes[nodeIndex];
- if (node == null)
- {
- node = new NodeData();
- _nodes[nodeIndex] = node;
- }
+ NodeData node = _nodes[nodeIndex] ??= new NodeData();
node.depth = nodeDepth;
return node;
}
_nameTable = nt;
// make sure we have namespace manager
- if (_namespaceManager == null)
- {
- _namespaceManager = new XmlNamespaceManager(nt);
- }
+ _namespaceManager ??= new XmlNamespaceManager(nt);
// copy xml:space and xml:lang
_xmlContext.xmlSpace = context.XmlSpace;
return uri1Str == uri2Str;
}
- if (uri1 == null)
- {
- uri1 = resolver.ResolveUri(null, uri1Str);
- }
+ uri1 ??= resolver.ResolveUri(null, uri1Str);
Uri uri2 = resolver.ResolveUri(null, uri2Str);
return uri1.Equals(uri2);
}
// detect & setup encoding
- if (encoding == null)
- {
- encoding = DetectEncoding();
- }
+ encoding ??= DetectEncoding();
SetupEncoding(encoding);
// eat preamble
}
else
{
- if (prefix == null)
- {
- prefix = GeneratePrefix(); // need a prefix if
- }
+ prefix ??= GeneratePrefix(); // need a prefix if
PushNamespace(prefix, ns, false);
}
}
if (tempResolver == null && !_coreReaderImpl.IsResolverSet)
{
// it is safe to return valid resolver as it'll be used in the schema validation
- if (s_tempResolver == null)
- s_tempResolver = new XmlUrlResolver();
- return s_tempResolver;
+ return s_tempResolver ??= new XmlUrlResolver();
}
return tempResolver;
{
prefix = LookupPrefix(ns);
}
- if (prefix == null)
- {
- prefix = string.Empty;
- }
+ prefix ??= string.Empty;
}
else if (prefix.Length > 0)
{
CheckNCName(prefix);
- if (ns == null)
- {
- ns = LookupNamespace(prefix);
- }
+ ns ??= LookupNamespace(prefix);
if (ns == null || (ns != null && ns.Length == 0))
{
throw new ArgumentException(SR.Xml_PrefixForEmptyNs);
prefix = LookupPrefix(namespaceName);
}
- if (prefix == null)
- {
- prefix = string.Empty;
- }
+ prefix ??= string.Empty;
}
if (namespaceName == null)
{
{
namespaceName = LookupNamespace(prefix);
}
- if (namespaceName == null)
- {
- namespaceName = string.Empty;
- }
+ namespaceName ??= string.Empty;
}
if (prefix.Length == 0)
{
try
{
- if (text == null)
- {
- text = string.Empty;
- }
+ text ??= string.Empty;
AdvanceState(Token.CData);
_writer.WriteCData(text);
}
{
try
{
- if (text == null)
- {
- text = string.Empty;
- }
+ text ??= string.Empty;
AdvanceState(Token.Comment);
_writer.WriteComment(text);
}
{
prefix = LookupPrefix(ns);
}
- if (prefix == null)
- {
- prefix = string.Empty;
- }
+ prefix ??= string.Empty;
}
else if (prefix.Length > 0)
{
CheckNCName(prefix);
- if (ns == null)
- {
- ns = LookupNamespace(prefix);
- }
+ ns ??= LookupNamespace(prefix);
if (ns == null || (ns != null && ns.Length == 0))
{
throw new ArgumentException(SR.Xml_PrefixForEmptyNs);
if (!(localName == "xmlns" && namespaceName == XmlReservedNs.NsXmlNs))
prefix = LookupPrefix(namespaceName);
}
- if (prefix == null)
- {
- prefix = string.Empty;
- }
+ prefix ??= string.Empty;
}
if (namespaceName == null)
{
namespaceName = LookupNamespace(prefix);
}
- if (namespaceName == null)
- {
- namespaceName = string.Empty;
- }
+ namespaceName ??= string.Empty;
}
if (prefix.Length == 0)
{
try
{
- if (text == null)
- {
- text = string.Empty;
- }
+ text ??= string.Empty;
await AdvanceStateAsync(Token.Comment).ConfigureAwait(false);
await _writer.WriteCommentAsync(text).ConfigureAwait(false);
Array.Copy(_attributeEvents, newAttributeEvents, _attributeEvents.Length);
_attributeEvents = newAttributeEvents;
}
- attInfo = _attributeEvents[attIndex];
- if (attInfo == null)
- {
- attInfo = new ValidatingReaderNodeData(XmlNodeType.Attribute);
- _attributeEvents[attIndex] = attInfo;
- }
- return attInfo;
+ return _attributeEvents[attIndex] ??= new ValidatingReaderNodeData(XmlNodeType.Attribute);
}
private ValidatingReaderNodeData AddContent(XmlNodeType nodeType)
Array.Copy(_contentEvents, newContentEvents, _contentEvents.Length);
_contentEvents = newContentEvents;
}
- contentInfo = _contentEvents[_contentIndex];
- if (contentInfo == null)
- {
- contentInfo = new ValidatingReaderNodeData(nodeType);
- _contentEvents[_contentIndex] = contentInfo;
- }
+ contentInfo = _contentEvents[_contentIndex] ??= new ValidatingReaderNodeData(nodeType);
_contentIndex++;
return contentInfo;
}
private ValidatingReaderNodeData CreateDummyTextNode(string attributeValue, int depth)
{
- if (_textNode == null)
- {
- _textNode = new ValidatingReaderNodeData(XmlNodeType.Text);
- }
+ _textNode ??= new ValidatingReaderNodeData(XmlNodeType.Text);
_textNode.Depth = depth;
_textNode.RawValue = attributeValue;
_attributePSVINodes = newPSVINodes;
}
- attInfo = _attributePSVINodes[attIndex];
- if (attInfo == null)
- {
- attInfo = new AttributePSVIInfo();
- _attributePSVINodes[attIndex] = attInfo;
- }
-
- return attInfo;
+ return _attributePSVINodes[attIndex] ??= new AttributePSVIInfo();
}
private bool IsXSDRoot(string localName, string ns)
private static volatile BooleanSwitch? s_keepTempFiles;
private static volatile BooleanSwitch? s_nonRecursiveTypeLoading;
- public static BooleanSwitch KeepTempFiles
- {
- get
- {
- if (s_keepTempFiles == null)
- {
- s_keepTempFiles = new BooleanSwitch("XmlSerialization.Compilation", "Keep XmlSerialization generated (temp) files.");
- }
+ public static BooleanSwitch KeepTempFiles =>
+ s_keepTempFiles ??= new BooleanSwitch("XmlSerialization.Compilation", "Keep XmlSerialization generated (temp) files.");
- return s_keepTempFiles;
- }
- }
-
- public static BooleanSwitch NonRecursiveTypeLoading
- {
- get
- {
- if (s_nonRecursiveTypeLoading == null)
- {
- s_nonRecursiveTypeLoading = new BooleanSwitch("XmlSerialization.NonRecursiveTypeLoading", "Turn on non-recursive algorithm generating XmlMappings for CLR types.");
- }
-
- return s_nonRecursiveTypeLoading;
- }
- }
+ public static BooleanSwitch NonRecursiveTypeLoading =>
+ s_nonRecursiveTypeLoading ??= new BooleanSwitch("XmlSerialization.NonRecursiveTypeLoading", "Turn on non-recursive algorithm generating XmlMappings for CLR types.");
}
}
CreateValidator(partialValidationType, validationFlags);
if (_psviAugmentation)
{
- if (_schemaInfo == null)
- { //Might have created it during FindSchemaInfo
- _schemaInfo = new XmlSchemaInfo();
- }
+ //Might have created it during FindSchemaInfo
+ _schemaInfo ??= new XmlSchemaInfo();
_attributeSchemaInfo = new XmlSchemaInfo();
}
ValidateNode(nodeToValidate);
return dictionary;
}
- public string? LookupNamespace(string prefix)
- {
- string? namespaceName = _nsManager.LookupNamespace(prefix);
- if (namespaceName == null)
- {
- namespaceName = _startNode!.GetNamespaceOfPrefixStrict(prefix);
- }
-
- return namespaceName;
- }
+ public string? LookupNamespace(string prefix) =>
+ _nsManager.LookupNamespace(prefix) ??
+ _startNode!.GetNamespaceOfPrefixStrict(prefix);
- public string? LookupPrefix(string namespaceName)
- {
- string? prefix = _nsManager.LookupPrefix(namespaceName);
- if (prefix == null)
- {
- prefix = _startNode!.GetPrefixOfNamespaceStrict(namespaceName);
- }
-
- return prefix;
- }
+ public string? LookupPrefix(string namespaceName) =>
+ _nsManager.LookupPrefix(namespaceName) ??
+ _startNode!.GetPrefixOfNamespaceStrict(namespaceName);
private IXmlNamespaceResolver NamespaceResolver
{
public XmlName? GetName(string? prefix, string localName, string? ns, IXmlSchemaInfo? schemaInfo)
{
- if (prefix == null)
- {
- prefix = string.Empty;
- }
- if (ns == null)
- {
- ns = string.Empty;
- }
+ prefix ??= string.Empty;
+ ns ??= string.Empty;
int hashCode = XmlName.GetHashCode(localName);
public XmlName AddName(string? prefix, string localName, string? ns, IXmlSchemaInfo? schemaInfo)
{
- if (prefix == null)
- {
- prefix = string.Empty;
- }
- if (ns == null)
- {
- ns = string.Empty;
- }
+ prefix ??= string.Empty;
+ ns ??= string.Empty;
int hashCode = XmlName.GetHashCode(localName);
//string.Empty) because in DTD, the namespace is not supported
if (_htElementIDAttrDecl == null || _htElementIDAttrDecl[eleName] == null)
{
- if (_htElementIDAttrDecl == null)
- _htElementIDAttrDecl = new Hashtable();
+ _htElementIDAttrDecl ??= new Hashtable();
_htElementIDAttrDecl.Add(eleName, attrName);
return true;
}
{
if (_htElementIdMap == null || !_htElementIdMap.Contains(id))
{
- if (_htElementIdMap == null)
- _htElementIdMap = new Hashtable();
+ _htElementIdMap ??= new Hashtable();
ArrayList elementList = new ArrayList();
elementList.Add(new WeakReference<XmlElement>(elem));
_htElementIdMap.Add(id, elementList);
public XmlSchemaSet Schemas
{
- get
- {
- if (_schemas == null)
- {
- _schemas = new XmlSchemaSet(NameTable);
- }
- return _schemas;
- }
-
- set
- {
- _schemas = value;
- }
+ get => _schemas ??= new XmlSchemaSet(NameTable);
+ set => _schemas = value;
}
internal bool CanReportValidity
internal override bool CanInsertBefore(XmlNode newChild, XmlNode? refChild)
{
- if (refChild == null)
- refChild = FirstChild;
+ refChild ??= FirstChild;
if (refChild == null)
return true;
internal override bool CanInsertAfter(XmlNode newChild, XmlNode? refChild)
{
- if (refChild == null)
- refChild = LastChild;
+ refChild ??= LastChild;
if (refChild == null)
return true;
internal XmlNamedNodeMap Entities
{
- get
- {
- if (_entities == null)
- _entities = new XmlNamedNodeMap(this);
- return _entities;
- }
- set { _entities = value; }
+ get => _entities ??= new XmlNamedNodeMap(this);
+ set => _entities = value;
}
internal bool IsLoading
}
// Gets the collection of XmlEntity nodes declared in the document type declaration.
- public XmlNamedNodeMap Entities
- {
- get
- {
- if (_entities == null)
- _entities = new XmlNamedNodeMap(this);
-
- return _entities;
- }
- }
+ public XmlNamedNodeMap Entities => _entities ??= new XmlNamedNodeMap(this);
// Gets the collection of XmlNotation nodes present in the document type declaration.
- public XmlNamedNodeMap Notations
- {
- get
- {
- if (_notations == null)
- _notations = new XmlNamedNodeMap(this);
-
- return _notations;
- }
- }
+ public XmlNamedNodeMap Notations => _notations ??= new XmlNamedNodeMap(this);
//
// DOM Level 2
{
lock (OwnerDocument.objLock)
{
- if (_attributes == null)
- {
- _attributes = new XmlAttributeCollection(this);
- }
+ _attributes ??= new XmlAttributeCollection(this);
}
}
private XmlNode? PrevElemInPreOrder(XmlNode curNode)
{
Debug.Assert(curNode != null);
+
//For preorder walking, the previous node will be the right-most node in the tree of PreviousSibling of the curNode
XmlNode? retNode = curNode.PreviousSibling;
+
// so if the PreviousSibling is not null, going through the tree down to find the right-most node
while (retNode != null)
{
break;
retNode = retNode.LastChild;
}
+
// if no PreviousSibling, the previous node will be the curNode's parentNode
- if (retNode == null)
- retNode = curNode.ParentNode;
+ retNode ??= curNode.ParentNode;
+
// if the final retNode is rootNode, consider having walked through the tree and no more previous node
if (retNode == _rootNode)
retNode = null;
string n = $"{_prefix}:{_localName}";
lock (ownerDoc.NameTable)
{
- if (_name == null)
- {
- _name = ownerDoc.NameTable.Add(n);
- }
+ _name ??= ownerDoc.NameTable.Add(n);
}
}
else
// Adds the specified node to the end of the list of children of this node.
public virtual XmlNode? AppendChild(XmlNode newChild)
{
- XmlDocument? thisDoc = OwnerDocument;
- if (thisDoc == null)
- {
- thisDoc = this as XmlDocument;
- }
+ XmlDocument? thisDoc = OwnerDocument ?? this as XmlDocument;
if (!IsContainer)
throw new InvalidOperationException(SR.Xdom_Node_Insert_Contain);
}
// construct the name of the xmlns attribute
- string attrName;
- if (prefix == null)
- prefix = string.Empty;
- if (prefix.Length == 0)
- attrName = "xmlns";
- else
- attrName = $"xmlns:{prefix}";
+ prefix ??= string.Empty;
+ string attrName = prefix.Length == 0 ?
+ "xmlns" :
+ $"xmlns:{prefix}";
// walk up the XmlNode parent chain, looking for the xmlns attribute
XmlNode? node = _curNode;
get { return _nameTable; }
}
- protected SchemaNames SchemaNames
- {
- get
- {
- if (_schemaNames == null)
- {
- _schemaNames = new SchemaNames(_nameTable);
- }
- return _schemaNames;
- }
- }
+ protected SchemaNames SchemaNames => _schemaNames ??= new SchemaNames(_nameTable);
protected ValidationEventHandler? EventHandler
{
{
if (transition[i] != -1)
{
- if (names == null)
- {
- names = new ArrayList();
- }
+ names ??= new ArrayList();
XmlSchemaParticle? p = (XmlSchemaParticle?)_symbols.GetParticle(i);
if (p == null)
BitSet curpos = context.CurPos[context.CurrentState.CurPosIndex];
for (int pos = curpos.NextSet(-1); pos != -1; pos = curpos.NextSet(pos))
{
- if (names == null)
- {
- names = new ArrayList();
- }
+ names ??= new ArrayList();
XmlSchemaParticle? p = (XmlSchemaParticle?)_positions[pos].particle;
if (p == null)
{
}
RangePositionInfo newRPosInfo = runningPositions[matchCount];
- if (newRPosInfo.rangeCounters == null)
- {
- newRPosInfo.rangeCounters = new decimal[_minMaxNodesCount];
- }
+ newRPosInfo.rangeCounters ??= new decimal[_minMaxNodesCount];
Array.Copy(rposInfo.rangeCounters, newRPosInfo.rangeCounters, rposInfo.rangeCounters.Length);
decimal count = ++newRPosInfo.rangeCounters[lrNode.Pos];
runningPositions[matchCount] = newRPosInfo;
j = matchCount + 1;
newRPosInfo = runningPositions[j];
- if (newRPosInfo.rangeCounters == null)
- {
- newRPosInfo.rangeCounters = new decimal[_minMaxNodesCount];
- }
+ newRPosInfo.rangeCounters ??= new decimal[_minMaxNodesCount];
Array.Copy(rposInfo.rangeCounters, newRPosInfo.rangeCounters, rposInfo.rangeCounters.Length);
newRPosInfo.curpos = _followpos[cPos];
newRPosInfo.rangeCounters[lrNode.Pos] = 0;
}
for (int pos = expectedPos.NextSet(-1); pos != -1; pos = expectedPos.NextSet(pos))
{
- if (names == null)
- {
- names = new ArrayList();
- }
+ names ??= new ArrayList();
int symbol = _positions[pos].symbol;
if (symbol >= 0)
{ //non range nodes
internal override FacetsChecker FacetsChecker { get { return miscFacetsChecker; } }
- internal override XmlValueConverter ValueConverter
- {
- get
- {
- if (_valueConverter == null)
- {
- _valueConverter = CreateValueConverter(_parentSchemaType!);
- }
- return _valueConverter;
- }
- }
+ internal override XmlValueConverter ValueConverter =>
+ _valueConverter ??= CreateValueConverter(_parentSchemaType!);
public override XmlTokenizedType TokenizedType { get { return XmlTokenizedType.None; } }
} while (simpleType != null && simpleType != DatatypeImplementation.AnySimpleType);
}
- if (listItemType == null)
- { //Get built-in simple type for the typecode
- listItemType = DatatypeImplementation.GetSimpleTypeFromTypeCode(schemaType!.Datatype!.TypeCode);
- }
+ //Get built-in simple type for the typecode
+ listItemType ??= DatatypeImplementation.GetSimpleTypeFromTypeCode(schemaType!.Datatype!.TypeCode);
return XmlListConverter.Create(listItemType.ValueConverter);
}
private void AddUndeclaredNotation(string notationName)
{
- if (_undeclaredNotations == null)
- {
- _undeclaredNotations = new Dictionary<string, UndeclaredNotation>();
- }
+ _undeclaredNotations ??= new Dictionary<string, UndeclaredNotation>();
UndeclaredNotation un = new UndeclaredNotation(notationName, LineNo, LinePos - notationName.Length);
UndeclaredNotation? loggedUn;
if (_undeclaredNotations.TryGetValue(notationName, out loggedUn))
}
if (j > i + 1)
{
- if (norValue == null)
- {
- norValue = new StringBuilder(len);
- }
+ norValue ??= new StringBuilder(len);
norValue.Append(value, startPos, i - startPos + 1);
startPos = j;
i = j - 1;
// Note: It used to be true that we only called this if _fValidate was true,
// but due to the fact that you can now dynamically type somethign as an ID
// that is no longer true.
- if (_IDs == null)
- {
- _IDs = new Hashtable();
- }
-
+ _IDs ??= new Hashtable();
_IDs.Add(name, node);
}
{
try
{
- if (baseUriStr == null)
- {
- baseUriStr = string.Empty;
- }
+ baseUriStr ??= string.Empty;
XmlSchemaDatatype dtype = attdef.Datatype;
if (dtype == null)
{
internal void CompileEnumerationFacet(XmlSchemaFacet facet, IXmlNamespaceResolver nsmgr, XmlNameTable nameTable)
{
CheckProhibitedFlag(facet, RestrictionFlags.Enumeration, SR.Sch_EnumerationFacetProhibited);
- if (_derivedRestriction.Enumeration == null)
- {
- _derivedRestriction.Enumeration = new ArrayList();
- }
+ _derivedRestriction.Enumeration ??= new ArrayList();
_derivedRestriction.Enumeration.Add(ParseFacetValue(_datatype, facet, SR.Sch_EnumerationFacetInvalid, nsmgr, nameTable));
SetFlag(facet, RestrictionFlags.Enumeration);
}
//needs to be converted to a RegEx
if (_firstPattern == false)
{
- if (_derivedRestriction.Patterns == null)
- {
- _derivedRestriction.Patterns = new ArrayList();
- }
+ _derivedRestriction.Patterns ??= new ArrayList();
try
{
_regStr!.Append(')');
if ((_baseFlags & RestrictionFlags.Enumeration) != 0)
{
- if (_derivedRestriction.Enumeration == null)
- {
- _derivedRestriction.Enumeration = baseRestriction.Enumeration;
- }
+ _derivedRestriction.Enumeration ??= baseRestriction.Enumeration;
SetFlag(RestrictionFlags.Enumeration);
}
public XmlSchemaSet InferSchema(XmlReader instanceDocument, XmlSchemaSet schemas)
{
- if (schemas == null)
- {
- schemas = new XmlSchemaSet(_nametable);
- }
+ schemas ??= new XmlSchemaSet(_nametable);
return InferSchema1(instanceDocument, schemas);
}
}
else if (elem.SchemaTypeName != XmlQualifiedName.Empty)
{
- effectiveSchemaType = _schemaSet!.GlobalTypes[elem.SchemaTypeName] as XmlSchemaType;
- if (effectiveSchemaType == null)
- {
- effectiveSchemaType = XmlSchemaType.GetBuiltInSimpleType(elem.SchemaTypeName);
- }
- if (effectiveSchemaType == null)
- {
- effectiveSchemaType = XmlSchemaType.GetBuiltInComplexType(elem.SchemaTypeName);
- }
+ effectiveSchemaType =
+ _schemaSet!.GlobalTypes[elem.SchemaTypeName] as XmlSchemaType ??
+ (XmlSchemaType?)XmlSchemaType.GetBuiltInSimpleType(elem.SchemaTypeName) ??
+ (XmlSchemaType?)XmlSchemaType.GetBuiltInComplexType(elem.SchemaTypeName);
}
}
return effectiveSchemaType;
internal XmlReaderSettings ReaderSettings
{
- get
- {
- if (_readerSettings == null)
- {
- _readerSettings = new XmlReaderSettings();
- _readerSettings.DtdProcessing = DtdProcessing.Prohibit;
- }
- return _readerSettings;
- }
- set
- {
- _readerSettings = value;
- }
+ get => _readerSettings ??= new XmlReaderSettings() { DtdProcessing = DtdProcessing.Prohibit };
+ set => _readerSettings = value;
}
//internal Dictionary<Uri, XmlSchema> SchemaLocations {
}
//Add the schema's targetnamespace
- string? tns = schema.TargetNamespace;
- if (tns == null)
- {
- tns = string.Empty;
- }
+ string tns = schema.TargetNamespace ?? string.Empty;
if (_referenceNamespaces[tns] == null)
{
_referenceNamespaces.Add(tns, tns);
break;
case Compositor.Redefine:
- if (_redefinedList == null)
- {
- _redefinedList = new ArrayList();
- }
+ _redefinedList ??= new ArrayList();
_redefinedList.Add(new RedefineEntry((external as XmlSchemaRedefine)!, _rootSchemaForRedefine!));
if (_processedExternals[includedSchema] != null)
else
{
group.IsProcessing = true;
- if (group.CanonicalParticle == null)
- {
- group.CanonicalParticle = CannonicalizeParticle(group.Particle, true, true);
- }
+ group.CanonicalParticle ??= CannonicalizeParticle(group.Particle, true, true);
Debug.Assert(group.CanonicalParticle != null);
group.IsProcessing = false;
}
internal void AddValue(string value)
{
- if (values == null)
- {
- values = new List<string>();
- }
+ values ??= new List<string>();
values.Add(value);
}
}
if (attdef.Presence == SchemaDeclBase.Use.Default || attdef.Presence == SchemaDeclBase.Use.Fixed)
{ //Not adding RequiredFixed here
- if (_defaultAttdefs == null)
- {
- _defaultAttdefs = new List<IDtdDefaultAttributeInfo>();
- }
+ _defaultAttdefs ??= new List<IDtdDefaultAttributeInfo>();
_defaultAttdefs.Add(attdef);
}
}
get { return _undeclaredElementDecls; }
}
- internal Dictionary<XmlQualifiedName, SchemaEntity> GeneralEntities
- {
- get
- {
- if (_generalEntities == null)
- {
- _generalEntities = new Dictionary<XmlQualifiedName, SchemaEntity>();
- }
- return _generalEntities;
- }
- }
+ internal Dictionary<XmlQualifiedName, SchemaEntity> GeneralEntities =>
+ _generalEntities ??= new Dictionary<XmlQualifiedName, SchemaEntity>();
- internal Dictionary<XmlQualifiedName, SchemaEntity> ParameterEntities
- {
- get
- {
- if (_parameterEntities == null)
- {
- _parameterEntities = new Dictionary<XmlQualifiedName, SchemaEntity>();
- }
- return _parameterEntities;
- }
- }
+ internal Dictionary<XmlQualifiedName, SchemaEntity> ParameterEntities =>
+ _parameterEntities ??= new Dictionary<XmlQualifiedName, SchemaEntity>();
internal SchemaType SchemaType
{
get { return _attributeDecls; }
}
- internal Dictionary<string, SchemaNotation> Notations
- {
- get
- {
- if (_notations == null)
- {
- _notations = new Dictionary<string, SchemaNotation>();
- }
- return _notations;
- }
- }
+ internal Dictionary<string, SchemaNotation> Notations =>
+ _notations ??= new Dictionary<string, SchemaNotation>();
internal int ErrorCount
{
string? tns;
foreach (XmlSchema? schema in _schemasToCompile.Values)
{
- tns = schema!.TargetNamespace;
- if (tns == null)
- {
- tns = string.Empty;
- }
-
+ tns = schema!.TargetNamespace ?? string.Empty;
schemaInfo.TargetNamespaces[tns] = true;
}
{
if (g.Members[j] != element)
{ //Exclude the head
- if (newMembers == null)
- {
- newMembers = new ArrayList();
- }
+ newMembers ??= new ArrayList();
newMembers.Add(g.Members[j]);
}
}
if (redefinedGroup.SelfReferenceCount == 0)
{
- if (baseGroup.CanonicalParticle == null)
- {
- baseGroup.CanonicalParticle = CannonicalizeParticle(baseGroup.Particle, true);
- }
-
- if (redefinedGroup.CanonicalParticle == null)
- {
- redefinedGroup.CanonicalParticle = CannonicalizeParticle(redefinedGroup.Particle, true);
- }
+ baseGroup.CanonicalParticle ??= CannonicalizeParticle(baseGroup.Particle, true);
+ redefinedGroup.CanonicalParticle ??= CannonicalizeParticle(redefinedGroup.Particle, true);
CompileParticleElements(redefinedGroup.CanonicalParticle);
CompileParticleElements(baseGroup.CanonicalParticle);
}
else if (skipEmptableOnly && !IsParticleEmptiable(baseParticle))
{
- if (_restrictionErrorMsg == null)
- { //If restriction failed on previous check, do not overwrite error
- _restrictionErrorMsg = SR.Sch_GroupBaseRestNotEmptiable;
- }
+ //If restriction failed on previous check, do not overwrite error
+ _restrictionErrorMsg ??= SR.Sch_GroupBaseRestNotEmptiable;
return false;
}
}
private static void XDR_InitAttribute(XdrBuilder builder, object obj)
{
- if (builder._BaseDecl == null)
- builder._BaseDecl = new DeclBaseInfo();
+ builder._BaseDecl ??= new DeclBaseInfo();
builder._BaseDecl._MinOccurs = 0;
}
// Note: It used to be true that we only called this if _fValidate was true,
// but due to the fact that you can now dynamically type somethign as an ID
// that is no longer true.
- if (_IDs == null)
- {
- _IDs = new Hashtable();
- }
+ _IDs ??= new Hashtable();
_IDs.Add(name, node);
}
}
[XmlIgnore]
- public XmlSchemaObjectTable Attributes
- {
- get
- {
- if (_attributes == null)
- {
- _attributes = new XmlSchemaObjectTable();
- }
- return _attributes;
- }
- }
+ public XmlSchemaObjectTable Attributes => _attributes ??= new XmlSchemaObjectTable();
[XmlIgnore]
- public XmlSchemaObjectTable AttributeGroups
- {
- get
- {
- if (_attributeGroups == null)
- {
- _attributeGroups = new XmlSchemaObjectTable();
- }
- return _attributeGroups;
- }
- }
+ public XmlSchemaObjectTable AttributeGroups => _attributeGroups ??= new XmlSchemaObjectTable();
[XmlIgnore]
- public XmlSchemaObjectTable SchemaTypes
- {
- get
- {
- if (_types == null)
- {
- _types = new XmlSchemaObjectTable();
- }
- return _types;
- }
- }
+ public XmlSchemaObjectTable SchemaTypes => _types ??= new XmlSchemaObjectTable();
[XmlIgnore]
- public XmlSchemaObjectTable Elements
- {
- get
- {
- if (_elements == null)
- {
- _elements = new XmlSchemaObjectTable();
- }
- return _elements;
- }
- }
+ public XmlSchemaObjectTable Elements => _elements ??= new XmlSchemaObjectTable();
[XmlAttribute("id", DataType = "ID")]
public string? Id
}
[XmlIgnore]
- internal XmlDocument Document
- {
- get { if (_document == null) _document = new XmlDocument(); return _document; }
- }
+ internal XmlDocument Document => _document ??= new XmlDocument();
[XmlIgnore]
internal int ErrorCount
_items.Add(annotation);
}
- internal XmlNameTable NameTable
- {
- get { if (_nameTable == null) _nameTable = new System.Xml.NameTable(); return _nameTable; }
- }
+ internal XmlNameTable NameTable => _nameTable ??= new System.Xml.NameTable();
- internal ArrayList ImportedSchemas
- {
- get
- {
- if (_importedSchemas == null)
- {
- _importedSchemas = new ArrayList();
- }
- return _importedSchemas;
- }
- }
+ internal ArrayList ImportedSchemas => _importedSchemas ??= new ArrayList();
- internal ArrayList ImportedNamespaces
- {
- get
- {
- if (_importedNamespaces == null)
- {
- _importedNamespaces = new ArrayList();
- }
- return _importedNamespaces;
- }
- }
+ internal ArrayList ImportedNamespaces => _importedNamespaces ??= new ArrayList();
internal void GetExternalSchemasList(IList extList, XmlSchema schema)
{
}
[XmlIgnore]
- internal XmlSchemaObjectTable AttributeUses
- {
- get
- {
- if (_attributeUses == null)
- {
- _attributeUses = new XmlSchemaObjectTable();
- }
- return _attributeUses;
- }
- }
+ internal XmlSchemaObjectTable AttributeUses => _attributeUses ??= new XmlSchemaObjectTable();
[XmlIgnore]
internal XmlSchemaAnyAttribute? AttributeWildcard
}
else
{
- if (_schemaNames == null)
- {
- _schemaNames = new SchemaNames(_nameTable);
- }
- return _schemaNames;
+ return _schemaNames ??= new SchemaNames(_nameTable);
}
}
[XmlElement("attribute", typeof(XmlSchemaAttribute)),
XmlElement("attributeGroup", typeof(XmlSchemaAttributeGroupRef))]
- public XmlSchemaObjectCollection Attributes
- {
- get
- {
- if (_attributes == null)
- {
- _attributes = new XmlSchemaObjectCollection();
- }
- return _attributes;
- }
- }
+ public XmlSchemaObjectCollection Attributes =>
+ _attributes ??= new XmlSchemaObjectCollection();
[XmlElement("anyAttribute")]
public XmlSchemaAnyAttribute? AnyAttribute
}
[XmlIgnore]
- public XmlSchemaObjectTable AttributeUses
- {
- get
- {
- if (_attributeUses == null)
- {
- _attributeUses = new XmlSchemaObjectTable();
- }
- return _attributeUses;
- }
- }
+ public XmlSchemaObjectTable AttributeUses =>
+ _attributeUses ??= new XmlSchemaObjectTable();
[XmlIgnore]
public XmlSchemaAnyAttribute? AttributeWildcard
}
[XmlIgnore]
- internal XmlSchemaObjectTable LocalElements
- {
- get
- {
- if (_localElements == null)
- {
- _localElements = new XmlSchemaObjectTable();
- }
- return _localElements;
- }
- }
+ internal XmlSchemaObjectTable LocalElements =>
+ _localElements ??= new XmlSchemaObjectTable();
internal void SetContentTypeParticle(XmlSchemaParticle value)
{
[XmlElement("key", typeof(XmlSchemaKey)),
XmlElement("keyref", typeof(XmlSchemaKeyref)),
XmlElement("unique", typeof(XmlSchemaUnique))]
- public XmlSchemaObjectCollection Constraints
- {
- get
- {
- if (_constraints == null)
- {
- _constraints = new XmlSchemaObjectCollection();
- }
- return _constraints;
- }
- }
+ public XmlSchemaObjectCollection Constraints =>
+ _constraints ??= new XmlSchemaObjectCollection();
[XmlIgnore]
public XmlQualifiedName QualifiedName
[XmlNamespaceDeclarations]
public XmlSerializerNamespaces Namespaces
{
- get
- {
- if (_namespaces == null)
- _namespaces = new XmlSerializerNamespaces();
- return _namespaces;
- }
- set { _namespaces = value; }
+ get => _namespaces ??= new XmlSerializerNamespaces();
+ set => _namespaces = value;
}
internal virtual void OnAdd(XmlSchemaObjectCollection container, object? item) { }
{
_eventHandler -= _internalEventHandler;
_eventHandler += value;
- if (_eventHandler == null)
- {
- _eventHandler = _internalEventHandler;
- }
+ _eventHandler ??= _internalEventHandler;
}
remove
{
_eventHandler -= value;
- if (_eventHandler == null)
- {
- _eventHandler = _internalEventHandler;
- }
+ _eventHandler ??= _internalEventHandler;
}
}
}
}
- public XmlSchemaObjectTable GlobalElements
- {
- get
- {
- if (elements == null)
- {
- elements = new XmlSchemaObjectTable();
- }
- return elements;
- }
- }
+ public XmlSchemaObjectTable GlobalElements => elements ??= new XmlSchemaObjectTable();
- public XmlSchemaObjectTable GlobalAttributes
- {
- get
- {
- if (attributes == null)
- {
- attributes = new XmlSchemaObjectTable();
- }
- return attributes;
- }
- }
+ public XmlSchemaObjectTable GlobalAttributes => attributes ??= new XmlSchemaObjectTable();
- public XmlSchemaObjectTable GlobalTypes
- {
- get
- {
- if (schemaTypes == null)
- {
- schemaTypes = new XmlSchemaObjectTable();
- }
- return schemaTypes;
- }
- }
+ public XmlSchemaObjectTable GlobalTypes => schemaTypes ??= new XmlSchemaObjectTable();
- internal XmlSchemaObjectTable SubstitutionGroups
- {
- get
- {
- if (substitutionGroups == null)
- {
- substitutionGroups = new XmlSchemaObjectTable();
- }
- return substitutionGroups;
- }
- }
+ internal XmlSchemaObjectTable SubstitutionGroups => substitutionGroups ??= new XmlSchemaObjectTable();
/// <summary>
/// Table of all types extensions
/// <summary>
/// Table of all types extensions
/// </summary>
- internal XmlSchemaObjectTable TypeExtensions
- {
- get
- {
- if (_typeExtensions == null)
- {
- _typeExtensions = new XmlSchemaObjectTable();
- }
- return _typeExtensions;
- }
- }
+ internal XmlSchemaObjectTable TypeExtensions => _typeExtensions ??= new XmlSchemaObjectTable();
+
//Public Methods
/// <summary>
lock (InternalSyncObject)
{
//Check if schema from url has already been added
- XmlResolver? tempResolver = _readerSettings.GetXmlResolver();
- if (tempResolver == null)
- {
- tempResolver = new XmlUrlResolver();
- }
+ XmlResolver tempResolver = _readerSettings.GetXmlResolver() ?? new XmlUrlResolver();
Uri tempSchemaUri = tempResolver.ResolveUri(null, schemaUri);
if (IsSchemaLoaded(tempSchemaUri, targetNamespace, out schema))
{
string? tns = null;
foreach (XmlSchema? schema in schemas.SortedSchemas.Values)
{
- tns = schema!.TargetNamespace;
- if (tns == null)
- {
- tns = string.Empty;
- }
+ tns = schema!.TargetNamespace ?? string.Empty;
if (_schemas.ContainsKey(schema.SchemaId) || FindSchemaByNSAndUrl(schema.BaseUri, tns, null) != null)
{ //Do not already existing url
continue;
public bool Contains(string? targetNamespace)
{
- if (targetNamespace == null)
- {
- targetNamespace = string.Empty;
- }
+ targetNamespace ??= string.Empty;
return _targetNamespaces[targetNamespace] != null;
}
{
ArrayList tnsSchemas = new ArrayList();
XmlSchema currentSchema;
- if (targetNamespace == null)
- {
- targetNamespace = string.Empty;
- }
+ targetNamespace ??= string.Empty;
for (int i = 0; i < _schemas.Count; i++)
{
currentSchema = (XmlSchema)_schemas.GetByIndex(i)!;
}
XmlQualifiedName head = element.SubstitutionGroup;
if (!head.IsEmpty) {
- if (substTable == null) {
- substTable = new XmlSchemaObjectTable();
- }
+ substTable ??= new XmlSchemaObjectTable();
XmlSchemaSubstitutionGroup substitutionGroup = (XmlSchemaSubstitutionGroup)substTable[head];
if (substitutionGroup == null) {
substitutionGroup = new XmlSchemaSubstitutionGroup();
{
ArgumentNullException.ThrowIfNull(reader);
- if (targetNamespace == null)
- {
- targetNamespace = string.Empty;
- }
+ targetNamespace ??= string.Empty;
if (validatedNamespaces[targetNamespace] != null)
{
if (FindSchemaByNSAndUrl(new Uri(reader.BaseURI!, UriKind.RelativeOrAbsolute), targetNamespace, null) != null)
for (int i = 0; i < schema.ImportedSchemas.Count; ++i)
{
XmlSchema impSchema = (XmlSchema)schema.ImportedSchemas[i]!;
- tns = impSchema.TargetNamespace;
- if (tns == null)
- {
- tns = string.Empty;
- }
+ tns = impSchema.TargetNamespace ?? string.Empty;
if (validatedNamespaces[tns] != null && (FindSchemaByNSAndUrl(impSchema.BaseUri, tns, oldLocations) == null))
{
RemoveRecursive(schema);
XmlSchemaElement element1 = (XmlSchemaElement)g.Members[j]!;
if (element1 != element)
{ //Exclude the head
- if (newMembers == null)
- {
- newMembers = new List<XmlSchemaElement>();
- }
+ newMembers ??= new List<XmlSchemaElement>();
newMembers.Add(element1);
}
}
}
else
{
- if (_schemaNames == null)
- {
- _schemaNames = new SchemaNames(_nameTable);
- }
- return _schemaNames;
+ return _schemaNames ??= new SchemaNames(_nameTable);
}
}
internal bool IsSchemaLoaded(Uri schemaUri, string? targetNamespace, out XmlSchema? schema)
{
- if (targetNamespace == null)
- {
- targetNamespace = string.Empty;
- }
+ targetNamespace ??= string.Empty;
if (GetSchemaByUri(schemaUri, out schema))
{
if (_schemas.ContainsKey(schema.SchemaId) && (targetNamespace.Length == 0 || targetNamespace == schema.TargetNamespace))
private void VerifyTables()
{
- if (elements == null)
- {
- elements = new XmlSchemaObjectTable();
- }
- if (attributes == null)
- {
- attributes = new XmlSchemaObjectTable();
- }
- if (schemaTypes == null)
- {
- schemaTypes = new XmlSchemaObjectTable();
- }
- if (substitutionGroups == null)
- {
- substitutionGroups = new XmlSchemaObjectTable();
- }
+ elements ??= new XmlSchemaObjectTable();
+ attributes ??= new XmlSchemaObjectTable();
+ schemaTypes ??= new XmlSchemaObjectTable();
+ substitutionGroups ??= new XmlSchemaObjectTable();
}
private void InternalValidationCallback(object? sender, ValidationEventArgs e)
{ //Do not process schema if processInlineSchema is not set
return;
}
- string? tns = schema.TargetNamespace;
- if (tns == null)
- {
- tns = string.Empty;
- }
+ string? tns = schema.TargetNamespace ?? string.Empty;
//Store the previous locations
Hashtable schemaLocations = _schemaSet.SchemaLocations;
DictionaryEntry[] oldLocations = new DictionaryEntry[schemaLocations.Count];
for (int i = 0; i < schema.ImportedSchemas.Count; ++i)
{ //Check for its imports
XmlSchema impSchema = (XmlSchema)schema.ImportedSchemas[i]!;
- tns = impSchema.TargetNamespace;
- if (tns == null)
- {
- tns = string.Empty;
- }
+ tns = impSchema.TargetNamespace ?? string.Empty;
if (_validatedNamespaces[tns] != null && _schemaSet.FindSchemaByNSAndUrl(impSchema.BaseUri, tns, oldLocations) == null)
{
SendValidationEvent(SR.Sch_ComponentAlreadySeenForNS, tns, XmlSeverityType.Error);
Exception? exception = dtype.TryParseValue(parsedValue, _nameTable, _nsResolver, out typedValue);
if (exception != null)
{
- string? stringValue = parsedValue as string;
- if (stringValue == null)
- {
- stringValue = XmlSchemaDatatype.ConcatenatedToString(parsedValue);
- }
+ string stringValue = parsedValue as string ?? XmlSchemaDatatype.ConcatenatedToString(parsedValue);
SendValidationEvent(SR.Sch_ElementValueDataTypeDetailed, new string[] { QNameString(_context.LocalName!, _context.Namespace!), stringValue, GetTypeName(decl), exception.Message }, exception);
return null;
}
else
{
- if (_IDs == null)
- {
- _IDs = new Hashtable();
- }
+ _IDs ??= new Hashtable();
_IDs.Add(name, _context.LocalName);
}
Error:
_attrValid = false;
- if (stringValue == null)
- {
- stringValue = XmlSchemaDatatype.ConcatenatedToString(value);
- }
+ stringValue ??= XmlSchemaDatatype.ConcatenatedToString(value);
SendValidationEvent(SR.Sch_AttributeValueDataTypeDetailed, new string[] { attdef.Name.ToString(), stringValue, GetTypeName(decl), exception.Message }, exception);
return null;
}
{
schemaType = schemaType.BaseXmlSchemaType!;
}
- if (schemaType == null)
- { //Did not find any simple type in the parent chain
- schemaType = XmlSchemaType.GetBuiltInSimpleType(datatype.TypeCode);
- }
+ schemaType ??= XmlSchemaType.GetBuiltInSimpleType(datatype.TypeCode); //Did not find any simple type in the parent chain
Debug.Assert(schemaType.Datatype!.Variety != XmlSchemaDatatypeVariety.List, "schemaType must be list's item type, not list itself");
_schemaType = schemaType;
_reader = reader;
}
- public override string? LookupNamespace(string prefix)
- {
- string? ns = _nsMgr.LookupNamespace(prefix);
-
- if (ns == null)
- {
- ns = _reader.LookupNamespace(prefix);
- }
-
- return ns;
- }
+ public override string? LookupNamespace(string prefix) =>
+ _nsMgr.LookupNamespace(prefix) ?? _reader.LookupNamespace(prefix);
}
//////////////////////////////////////////////////////////////////////////////////////////////
{
if (ns == _schemaNames.NsXmlNs)
{
- if (_namespaces == null)
- {
- _namespaces = new List<XmlQualifiedName>();
- }
+ _namespaces ??= new List<XmlQualifiedName>();
_namespaces.Add(new XmlQualifiedName((name == _schemaNames.QnXmlNs.Name) ? string.Empty : name, value));
}
else
private SchemaElementDecl? ThoroughGetElementDecl(SchemaElementDecl? elementDecl, XmlQualifiedName xsiType, string? xsiNil)
{
- if (elementDecl == null)
- {
- elementDecl = schemaInfo!.GetElementDecl(elementName);
- }
+ elementDecl ??= schemaInfo!.GetElementDecl(elementName);
if (elementDecl != null)
{
if (xsiType.IsEmpty)
// Note: It used to be true that we only called this if _fValidate was true,
// but due to the fact that you can now dynamically type somethign as an ID
// that is no longer true.
- if (_IDs == null)
- {
- _IDs = new Hashtable();
- }
+ _IDs ??= new Hashtable();
_IDs.Add(name, node);
}
internal LocalBuilder? retLocal;
internal Label retLabel;
- internal LocalBuilder ReturnLocal
- {
- get
- {
- if (retLocal == null)
- retLocal = DeclareLocal(_methodBuilder!.ReturnType, "_ret");
- return retLocal;
- }
- }
+ internal LocalBuilder ReturnLocal => retLocal ??= DeclareLocal(_methodBuilder!.ReturnType, "_ret");
internal Label ReturnLabel
{
get { return retLabel; }
memberType = property.PropertyType;
if (property != null)
{
- MethodInfo? getMethod = property.GetMethod;
-
- if (getMethod == null)
- {
- getMethod = GetPropertyMethodFromBaseType(property, true);
- }
+ MethodInfo? getMethod = property.GetMethod ?? GetPropertyMethodFromBaseType(property, true);
System.Diagnostics.Debug.Assert(getMethod != null);
Call(getMethod);
memberType = property.PropertyType;
if (property != null)
{
- MethodInfo? getMethod = property.GetMethod;
-
- if (getMethod == null)
- {
- getMethod = GetPropertyMethodFromBaseType(property, true);
- }
+ MethodInfo? getMethod = property.GetMethod ?? GetPropertyMethodFromBaseType(property, true);
System.Diagnostics.Debug.Assert(getMethod != null);
Call(getMethod);
PropertyInfo property = (PropertyInfo)memberInfo;
if (property != null)
{
- MethodInfo? setMethod = property.SetMethod;
-
- if (setMethod == null)
- {
- setMethod = GetPropertyMethodFromBaseType(property, false);
- }
+ MethodInfo? setMethod = property.SetMethod ?? GetPropertyMethodFromBaseType(property, false);
System.Diagnostics.Debug.Assert(setMethod != null);
Call(setMethod);
internal XmlSerializerImplementation Contract
{
[RequiresUnreferencedCode("calls GetTypeFromAssembly")]
- get
- {
- if (_contract == null)
- {
- _contract = (XmlSerializerImplementation)Activator.CreateInstance(GetTypeFromAssembly(_assembly!, "XmlSerializerContract"))!;
- }
- return _contract;
- }
+ get => _contract ??= (XmlSerializerImplementation)Activator.CreateInstance(GetTypeFromAssembly(_assembly!, "XmlSerializerContract"))!;
}
internal void InitAssemblyMethods(XmlMapping[] xmlMappings)
reader.Init(xmlReader, events, encodingStyle, this);
if (_methods![mapping.Key!].readMethod == null)
{
- if (_readerMethods == null)
- {
- _readerMethods = Contract.ReadMethods;
- }
+ _readerMethods ??= Contract.ReadMethods;
string? methodName = (string?)_readerMethods[mapping.Key!];
if (methodName == null)
{
writer.Init(xmlWriter, namespaces, encodingStyle, id, this);
if (_methods![mapping.Key!].writeMethod == null)
{
- if (_writerMethods == null)
- {
- _writerMethods = Contract.WriteMethods;
- }
+ _writerMethods ??= Contract.WriteMethods;
string? methodName = (string?)_writerMethods[mapping.Key!];
if (methodName == null)
{
internal ImportContext() : this(null, false) { }
- internal SchemaObjectCache Cache
- {
- get
- {
- if (_cache == null)
- _cache = new SchemaObjectCache();
- return _cache;
- }
- }
+ internal SchemaObjectCache Cache => _cache ??= new SchemaObjectCache();
- internal Hashtable Elements
- {
- get
- {
- if (_elements == null)
- _elements = new Hashtable();
- return _elements;
- }
- }
+ internal Hashtable Elements => _elements ??= new Hashtable();
- internal Hashtable Mappings
- {
- get
- {
- if (_mappings == null)
- _mappings = new Hashtable();
- return _mappings;
- }
- }
+ internal Hashtable Mappings => _mappings ??= new Hashtable();
- public CodeIdentifiers TypeIdentifiers
- {
- get
- {
- if (_typeIdentifiers == null)
- _typeIdentifiers = new CodeIdentifiers();
- return _typeIdentifiers;
- }
- }
+ public CodeIdentifiers TypeIdentifiers => _typeIdentifiers ??= new CodeIdentifiers();
public bool ShareTypes
{
private StringCollection? _warnings;
// UNDONE remove me soon, this is debug only code
internal Hashtable looks = new Hashtable();
- private Hashtable Graph
- {
- get
- {
- if (_graph == null)
- _graph = new Hashtable();
- return _graph;
- }
- }
+ private Hashtable Graph => _graph ??= new Hashtable();
- private Hashtable Hash
- {
- get
- {
- if (_hash == null)
- _hash = new Hashtable();
- return _hash;
- }
- }
+ private Hashtable Hash => _hash ??= new Hashtable();
- private Hashtable ObjectCache
- {
- get
- {
- if (_objectCache == null)
- _objectCache = new Hashtable();
- return _objectCache;
- }
- }
+ private Hashtable ObjectCache => _objectCache ??= new Hashtable();
- internal StringCollection Warnings
- {
- get
- {
- if (_warnings == null)
- _warnings = new StringCollection();
- return _warnings;
- }
- }
+ internal StringCollection Warnings => _warnings ??= new StringCollection();
internal XmlSchemaObject? AddItem(XmlSchemaObject? item, XmlQualifiedName? qname, XmlSchemas schemas)
{
return true;
if (o1.GetType() != o2.GetType())
return false;
- if (Hash[o1] == null)
- Hash[o1] = GetHash(o1);
+
+ Hash[o1] ??= GetHash(o1);
int hash1 = (int)Hash[o1]!;
int hash2 = GetHash(o2);
if (hash1 != hash2)
get { return _baseMapping != null && Members != null; }
}
- internal NameTable LocalElements
- {
- get
- {
- if (_elements == null)
- _elements = new NameTable();
- return _elements;
- }
- }
- internal NameTable LocalAttributes
- {
- get
- {
- if (_attributes == null)
- _attributes = new NameTable();
- return _attributes;
- }
- }
+ internal NameTable LocalElements => _elements ??= new NameTable();
+ internal NameTable LocalAttributes => _attributes ??= new NameTable();
object? INameScope.this[string? name, string? ns]
{
get
internal CodeIdentifiers Scope
{
- get
- {
- if (_scope == null)
- _scope = new CodeIdentifiers();
- return _scope;
- }
- set { _scope = value; }
+ get => _scope ??= new CodeIdentifiers();
+ set => _scope = value;
}
internal MemberMapping? FindDeclaringMapping(MemberMapping member, out StructMapping? declaringMapping, string? parent)
if (_getSchemaMethod != null)
{
// get the type info
- if (_schemas == null)
- _schemas = new XmlSchemaSet();
+ _schemas ??= new XmlSchemaSet();
object? typeInfo = _getSchemaMethod.Invoke(null, new object[] { _schemas });
_xsiType = XmlQualifiedName.Empty;
}
else
{
- if (collection == null)
- {
- collection = ReflectionCreateObject(collectionType)!;
- }
+ collection ??= ReflectionCreateObject(collectionType)!;
AddObjectsIntoTargetCollection(collection, collectionMember, collectionType);
}
{
member.Source = (item) =>
{
- if (member.Collection == null)
- {
- member.Collection = new CollectionMember();
- }
+ member.Collection ??= new CollectionMember();
member.Collection.Add(item);
};
{
anyCount++;
if (element.Name != null && element.Name.Length > 0)
+ {
namedAnys.Add(element);
- else if (unnamedAny == null)
- unnamedAny = element;
+ }
+ else
+ {
+ unnamedAny ??= element;
+ }
}
else if (choice != null)
{
Schemas.SetCache(Context.Cache, Context.ShareTypes);
}
- internal ImportContext Context
- {
- get
- {
- if (_context == null)
- _context = new ImportContext();
- return _context;
- }
- }
+ internal ImportContext Context => _context ??= new ImportContext();
internal Hashtable ImportedElements
{
get { return Context.TypeIdentifiers; }
}
- internal XmlSchemas Schemas
- {
- get
- {
- if (_schemas == null)
- _schemas = new XmlSchemas();
- return _schemas;
- }
- }
+ internal XmlSchemas Schemas => _schemas ??= new XmlSchemas();
- internal TypeScope Scope
- {
- get
- {
- if (_scope == null)
- _scope = new TypeScope();
- return _scope;
- }
- }
+ internal TypeScope Scope => _scope ??= new TypeScope();
- internal NameTable GroupsInUse
- {
- get
- {
- if (_groupsInUse == null)
- _groupsInUse = new NameTable();
- return _groupsInUse;
- }
- }
+ internal NameTable GroupsInUse => _groupsInUse ??= new NameTable();
- internal NameTable TypesInUse
- {
- get
- {
- if (_typesInUse == null)
- _typesInUse = new NameTable();
- return _typesInUse;
- }
- }
+ internal NameTable TypesInUse => _typesInUse ??= new NameTable();
internal CodeGenerationOptions Options
{
}
[RequiresUnreferencedCode("calls CreateRootMapping")]
- internal StructMapping GetRootMapping()
- {
- if (_root == null)
- _root = CreateRootMapping();
- return _root;
- }
+ internal StructMapping GetRootMapping() => _root ??= CreateRootMapping();
[RequiresUnreferencedCode("calls GetRootMapping")]
internal StructMapping ImportRootMapping()
public SoapReflectionImporter(SoapAttributeOverrides? attributeOverrides, string? defaultNamespace)
{
- if (defaultNamespace == null)
- defaultNamespace = string.Empty;
- if (attributeOverrides == null)
- attributeOverrides = new SoapAttributeOverrides();
- _attributeOverrides = attributeOverrides;
- _defaultNs = defaultNamespace;
+ _defaultNs = defaultNamespace ?? string.Empty;
+ _attributeOverrides = attributeOverrides ?? new SoapAttributeOverrides();
_typeScope = new TypeScope();
_modelScope = new ModelScope(_typeScope);
}
typeNs = baseAttributes.SoapType.Namespace;
TypeDesc valueTypeDesc = string.IsNullOrEmpty(dataType) ? model.TypeDesc.BaseTypeDesc! : TypeScope.GetTypeDesc(dataType, XmlSchema.Namespace)!;
string xsdTypeName = string.IsNullOrEmpty(dataType) ? model.TypeDesc.BaseTypeDesc!.Name : dataType;
- TypeMapping? baseMapping = GetTypeMapping(xsdTypeName, typeNs, valueTypeDesc);
- if (baseMapping == null)
- baseMapping = ImportTypeMapping(_modelScope.GetTypeModel(baseTypeDesc.Type!), dataType, limiter);
+ TypeMapping baseMapping =
+ GetTypeMapping(xsdTypeName, typeNs, valueTypeDesc) ??
+ ImportTypeMapping(_modelScope.GetTypeModel(baseTypeDesc.Type!), dataType, limiter);
return CreateNullableMapping(baseMapping, model.TypeDesc.Type!);
}
else
members.Add(member);
}
mapping.Members = members.ToArray();
- if (mapping.BaseMapping == null) mapping.BaseMapping = GetRootMapping();
+ mapping.BaseMapping ??= GetRootMapping();
IncludeTypes(model.Type, limiter);
return true;
if (a.SoapIgnore) return null;
if ((a.GetSoapFlags() & ~SoapAttributeFlags.Enum) != 0)
throw new InvalidOperationException(SR.XmlInvalidEnumAttribute);
- if (a.SoapEnum == null)
- a.SoapEnum = new SoapEnumAttribute();
+ a.SoapEnum ??= new SoapEnumAttribute();
ConstantMapping constant = new ConstantMapping();
constant.XmlName = a.SoapEnum.Name.Length == 0 ? model.Name : a.SoapEnum.Name;
get { return _fullName; }
}
- internal string CSharpName
- {
- get
- {
- if (_cSharpName == null)
- {
- _cSharpName = _type == null ? CodeIdentifier.GetCSharpName(_fullName) : CodeIdentifier.GetCSharpName(_type);
- }
- return _cSharpName;
- }
- }
+ internal string CSharpName =>
+ _cSharpName ??= _type == null ? CodeIdentifier.GetCSharpName(_fullName) : CodeIdentifier.GetCSharpName(_type);
internal XmlSchemaType? DataType
{
get { return _weight; }
}
- internal TypeDesc CreateArrayTypeDesc()
- {
- if (_arrayTypeDesc == null)
- _arrayTypeDesc = new TypeDesc(null, $"{_name}[]", $"{_fullName}[]", TypeKind.Array, null, TypeFlags.Reference | (_flags & TypeFlags.UseReflection), this);
- return _arrayTypeDesc;
- }
+ internal TypeDesc CreateArrayTypeDesc() => _arrayTypeDesc ??= new TypeDesc(null, $"{_name}[]", $"{_fullName}[]", TypeKind.Array, null, TypeFlags.Reference | (_flags & TypeFlags.UseReflection), this);
internal TypeDesc? BaseTypeDesc
{
{
throw new InvalidOperationException(SR.Format(SR.XmlUnsupportedOpenGenericType, type));
}
- TypeDesc? typeDesc = (TypeDesc?)s_primitiveTypes[type];
- if (typeDesc == null)
- {
- typeDesc = (TypeDesc?)_typeDescs[type];
- if (typeDesc == null)
- {
- typeDesc = ImportTypeDesc(type, source, directReference);
- }
- }
+
+ TypeDesc typeDesc =
+ (TypeDesc?)s_primitiveTypes[type] ??
+ (TypeDesc?)_typeDescs[type] ??
+ ImportTypeDesc(type, source, directReference);
+
if (throwOnError)
typeDesc.CheckSupported();
-
return typeDesc;
}
{
kind = TypeKind.Enum;
flags |= TypeFlags.Unsupported;
- if (exception == null)
- {
- exception = new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, type.FullName));
- }
+ exception ??= new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, type.FullName));
}
else if (type == typeof(void))
{
if (type.GetArrayRank() > 1)
{
flags |= TypeFlags.Unsupported;
- if (exception == null)
- {
- exception = new NotSupportedException(SR.Format(SR.XmlUnsupportedRank, type.FullName));
- }
+ exception ??= new NotSupportedException(SR.Format(SR.XmlUnsupportedRank, type.FullName));
}
arrayElementType = type.GetElementType();
flags |= TypeFlags.HasDefaultConstructor;
{
kind = TypeKind.Primitive;
flags |= TypeFlags.Unsupported;
- if (exception == null)
- {
- exception = new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, type.FullName));
- }
+ exception ??= new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, type.FullName));
}
else if (type.IsEnum)
{
{
if (ShouldBeReplaced(pair.Value, structMapping.TypeDesc!.Type!, out replacedInfo))
{
- if (replaceList == null)
- {
- replaceList = new Dictionary<string, MemberInfo>();
- }
+ replaceList ??= new Dictionary<string, MemberInfo>();
replaceList.Add(pair.Key, replacedInfo);
}
internal static string GenerateKey(Type type, XmlRootAttribute? root, string? ns)
{
- if (root == null)
- {
- root = (XmlRootAttribute?)XmlAttributes.GetAttr(type, typeof(XmlRootAttribute));
- }
+ root ??= (XmlRootAttribute?)XmlAttributes.GetAttr(type, typeof(XmlRootAttribute));
return $"{type.FullName}:{(root == null ? string.Empty : root.GetKey())}:{ns ?? string.Empty}";
}
/// </devdoc>
public XmlReflectionImporter(XmlAttributeOverrides? attributeOverrides, string? defaultNamespace)
{
- if (defaultNamespace == null)
- defaultNamespace = string.Empty;
- if (attributeOverrides == null)
- attributeOverrides = new XmlAttributeOverrides();
- _attributeOverrides = attributeOverrides;
- _defaultNs = defaultNamespace;
+ _defaultNs = defaultNamespace ?? string.Empty;
+ _attributeOverrides = attributeOverrides ?? new XmlAttributeOverrides();
_typeScope = new TypeScope();
_modelScope = new ModelScope(_typeScope);
}
{
XmlAttributes a = GetAttributes(model.Type, true);
- if (root == null)
- root = a.XmlRoot;
- string? ns = root?.Namespace;
- if (ns == null) ns = defaultNamespace;
- if (ns == null) ns = _defaultNs;
+ root ??= a.XmlRoot;
+ string ns = root?.Namespace ?? defaultNamespace ?? _defaultNs;
_arrayNestingLevel = -1;
_savedArrayItemAttributes = null;
}
}
- if (a == null)
- a = GetAttributes(model.Type, false);
+ a ??= GetAttributes(model.Type, false);
if ((a.XmlFlags & ~(XmlAttributeFlags.Type | XmlAttributeFlags.Root)) != 0)
throw new InvalidOperationException(SR.Format(SR.XmlInvalidTypeAttributes, model.Type.FullName));
{
TypeDesc valueTypeDesc = string.IsNullOrEmpty(dataType) ? model.TypeDesc.BaseTypeDesc! : TypeScope.GetTypeDesc(dataType, XmlSchema.Namespace)!;
string? xsdTypeName = valueTypeDesc.DataType == null ? valueTypeDesc.Name : valueTypeDesc.DataType.Name;
- TypeMapping? baseMapping = GetTypeMapping(xsdTypeName, ns, valueTypeDesc, _types, null);
- if (baseMapping == null)
- baseMapping = ImportTypeMapping(_modelScope.GetTypeModel(model.TypeDesc.BaseTypeDesc!.Type!), ns, context, dataType, null, repeats, openModel, limiter);
+ TypeMapping baseMapping =
+ GetTypeMapping(xsdTypeName, ns, valueTypeDesc, _types, null) ??
+ ImportTypeMapping(_modelScope.GetTypeModel(model.TypeDesc.BaseTypeDesc!.Type!), ns, context, dataType, null, repeats, openModel, limiter);
return CreateNullableMapping(baseMapping, model.TypeDesc.Type!);
}
else
[RequiresUnreferencedCode("calls IncludeTypes")]
private SpecialMapping ImportSpecialMapping(Type type, TypeDesc typeDesc, string? ns, ImportContext context, RecursionLimiter limiter)
{
- if (_specials == null)
- _specials = new Hashtable();
+ _specials ??= new Hashtable();
SpecialMapping? mapping = (SpecialMapping?)_specials[type];
if (mapping != null)
{
XmlQualifiedName? qname = serializableMapping.XsiType;
if (qname != null && !qname.IsEmpty)
{
- if (_serializables == null)
- _serializables = new NameTable();
+ _serializables ??= new NameTable();
SerializableMapping? existingMapping = (SerializableMapping?)_serializables[qname];
if (existingMapping != null)
{
private StructMapping ImportStructLikeMapping(StructModel model, string? ns, bool openModel, XmlAttributes? a, RecursionLimiter limiter)
{
if (model.TypeDesc.Kind == TypeKind.Root) return GetRootMapping();
- if (a == null)
- a = GetAttributes(model.Type, false);
+ a ??= GetAttributes(model.Type, false);
string? typeNs = ns;
if (a.XmlType != null && a.XmlType.Namespace != null)
}
mapping.Members = members.ToArray();
- if (mapping.BaseMapping == null) mapping.BaseMapping = GetRootMapping();
+ mapping.BaseMapping ??= GetRootMapping();
if (mapping.XmlnsMember != null && mapping.BaseMapping.HasXmlnsMember)
throw new InvalidOperationException(SR.Format(SR.XmlMultipleXmlns, model.Type.FullName));
name = $"Choice{(_choiceNum++)}";
}
- if (name == null)
- name = "Any";
+ name ??= "Any";
if (element != null)
ns = element.Namespace;
- if (ns == null)
- ns = defaultNs;
+ ns ??= defaultNs;
string uniqueName = name = generateTypeName ? $"ArrayOf{CodeIdentifier.MakePascal(name)}" : name;
int i = 1;
ArrayMapping mapping = new ArrayMapping();
mapping.TypeDesc = model.TypeDesc;
- if (_savedArrayItemAttributes == null)
- _savedArrayItemAttributes = new XmlArrayItemAttributes();
+ _savedArrayItemAttributes ??= new XmlArrayItemAttributes();
if (CountAtLevel(_savedArrayItemAttributes, _arrayNestingLevel) == 0)
_savedArrayItemAttributes.Add(CreateArrayItemAttribute(_typeScope.GetTypeDesc(model.Element.Type), _arrayNestingLevel));
CreateArrayElementsFromAttributes(mapping, _savedArrayItemAttributes, model.Element.Type, _savedArrayNamespace ?? ns, limiter);
if (a.XmlIgnore) return null;
if ((a.XmlFlags & ~XmlAttributeFlags.Enum) != 0)
throw new InvalidOperationException(SR.XmlInvalidConstantAttribute);
- if (a.XmlEnum == null)
- a.XmlEnum = new XmlEnumAttribute();
+ a.XmlEnum ??= new XmlEnumAttribute();
ConstantMapping constant = new ConstantMapping();
constant.XmlName = a.XmlEnum.Name ?? model.Name;
attribute.Any = (a.XmlAnyAttribute != null);
if (attribute.Form == XmlSchemaForm.Qualified && attribute.Namespace != ns)
{
- if (_xsdAttributes == null)
- _xsdAttributes = new NameTable();
+ _xsdAttributes ??= new NameTable();
attribute = (AttributeAccessor)ReconcileAccessor(attribute, _xsdAttributes);
}
accessor.Attribute = attribute;
}
TypeDesc arrayElementTypeDesc = _typeScope.GetTypeDesc(arrayElementType);
- if (a.XmlArray == null)
- a.XmlArray = CreateArrayAttribute(accessor.TypeDesc);
+ a.XmlArray ??= CreateArrayAttribute(accessor.TypeDesc);
if (CountAtLevel(a.XmlArrayItems, _arrayNestingLevel) == 0)
a.XmlArrayItems.Add(CreateArrayItemAttribute(arrayElementTypeDesc, _arrayNestingLevel));
ElementAccessor arrayElement = new ElementAccessor();
attribute.Any = a.XmlAnyAttribute != null;
if (attribute.Form == XmlSchemaForm.Qualified && attribute.Namespace != ns)
{
- if (_xsdAttributes == null)
- _xsdAttributes = new NameTable();
+ _xsdAttributes ??= new NameTable();
attribute = (AttributeAccessor)ReconcileAccessor(attribute, _xsdAttributes);
}
accessor.Attribute = attribute;
internal bool IsExceededLimit { get { return _depth > _maxDepth; } }
internal int Depth { get { return _depth; } set { _depth = value; } }
- internal WorkItems DeferredWorkItems
- {
- get
- {
- if (_deferredWorkItems == null)
- {
- _deferredWorkItems = new WorkItems();
- }
- return _deferredWorkItems;
- }
- }
+ internal WorkItems DeferredWorkItems => _deferredWorkItems ??= new WorkItems();
}
}
private void AddSchemaItem(XmlSchemaObject item, string? ns, string? referencingNs)
{
- XmlSchema? schema = _schemas[ns];
- if (schema == null)
- {
- schema = AddSchema(ns);
- }
+ XmlSchema schema = _schemas[ns] ?? AddSchema(ns);
if (item is XmlSchemaElement e)
{
{
if (referencingNs == null) return;
if (NamespacesEqual(ns, referencingNs)) return;
- XmlSchema? schema = _schemas[referencingNs];
- if (schema == null)
- {
- schema = AddSchema(referencingNs);
- }
+ XmlSchema schema = _schemas[referencingNs] ?? AddSchema(referencingNs);
if (FindImport(schema, ns) == null)
{
XmlSchemaImport import = new XmlSchemaImport();
break;
typeDescs[i] = ((ElementAccessor)enumerator.Current).Mapping!.TypeDesc!;
}
- member.TypeDesc = TypeDesc.FindCommonBaseTypeDesc(typeDescs);
- if (member.TypeDesc == null) member.TypeDesc = Scope.GetTypeDesc(typeof(object));
+ member.TypeDesc =
+ TypeDesc.FindCommonBaseTypeDesc(typeDescs) ??
+ Scope.GetTypeDesc(typeof(object));
}
if (groupRepeats)
if (membersScope != null)
{
member.Name = membersScope.AddUnique(groupRepeats ? "Items" : "Item", member);
- if (members != null)
- {
- members.Add(member.Name, member);
- }
+ members?.Add(member.Name, member);
}
if (duplicateTypes)
return (IList)SchemaSet.Schemas(ns);
}
- internal SchemaObjectCache Cache
- {
- get
- {
- if (_cache == null)
- _cache = new SchemaObjectCache();
- return _cache;
- }
- }
+ internal SchemaObjectCache Cache => _cache ??= new SchemaObjectCache();
- internal Hashtable MergedSchemas
- {
- get
- {
- if (_mergedSchemas == null)
- _mergedSchemas = new Hashtable();
- return _mergedSchemas;
- }
- }
+ internal Hashtable MergedSchemas => _mergedSchemas ??= new Hashtable();
- internal Hashtable References
- {
- get
- {
- if (_references == null)
- _references = new Hashtable();
- return _references;
- }
- }
+ internal Hashtable References => _references ??= new Hashtable();
internal XmlSchemaSet SchemaSet
{
return;
}
- internal static XmlSchema XsdSchema
- {
- get
- {
- if (s_xsd == null)
- {
- s_xsd = CreateFakeXsdSchema(XmlSchema.Namespace, "schema");
- }
- return s_xsd;
- }
- }
+ internal static XmlSchema XsdSchema =>
+ s_xsd ??= CreateFakeXsdSchema(XmlSchema.Namespace, "schema");
- internal static XmlSchema XmlSchema
- {
- get
- {
- if (s_xml == null)
- {
- s_xml = XmlSchema.Read(new StringReader(xmlSchema), null)!;
- }
- return s_xml;
- }
- }
+ internal static XmlSchema XmlSchema =>
+ s_xml ??= XmlSchema.Read(new StringReader(xmlSchema), null)!;
private static XmlSchema CreateFakeXsdSchema(string ns, string name)
{
protected bool GetNullAttr()
{
- string? isNull = _r.GetAttribute(_nilID, _instanceNsID);
- if (isNull == null)
- isNull = _r.GetAttribute(_nullID, _instanceNsID);
- if (isNull == null)
- {
- isNull = _r.GetAttribute(_nullID, _instanceNs2000ID);
- if (isNull == null)
- isNull = _r.GetAttribute(_nullID, _instanceNs1999ID);
- }
+ string? isNull =
+ _r.GetAttribute(_nilID, _instanceNsID) ??
+ _r.GetAttribute(_nullID, _instanceNsID) ??
+ _r.GetAttribute(_nullID, _instanceNs2000ID) ??
+ _r.GetAttribute(_nullID, _instanceNs1999ID);
+
if (isNull == null || !XmlConvert.ToBoolean(isNull)) return false;
return true;
}
{
if (id == null)
{
- if (_targetsWithoutIds == null)
- _targetsWithoutIds = new ArrayList();
+ _targetsWithoutIds ??= new ArrayList();
if (o != null)
_targetsWithoutIds.Add(o);
}
else
{
- if (_targets == null) _targets = new Hashtable();
+ _targets ??= new Hashtable();
if (!_targets.Contains(id))
_targets.Add(id, o);
}
protected void AddFixup(Fixup? fixup)
{
- if (_fixups == null) _fixups = new ArrayList();
+ _fixups ??= new ArrayList();
_fixups.Add(fixup);
}
protected void AddFixup(CollectionFixup? fixup)
{
- if (_collectionFixups == null) _collectionFixups = new ArrayList();
+ _collectionFixups ??= new ArrayList();
_collectionFixups.Add(fixup);
}
protected void Referenced(object? o)
{
if (o == null) return;
- if (_referencedTargets == null) _referencedTargets = new Hashtable();
+ _referencedTargets ??= new Hashtable();
_referencedTargets[o] = o;
}
private int _nextCreateMethodNumber;
private int _nextIdNumber;
- internal Hashtable Enums
- {
- get
- {
- if (_enums == null)
- {
- _enums = new Hashtable();
- }
- return _enums;
- }
- }
+ internal Hashtable Enums => _enums ??= new Hashtable();
private sealed class CreateCollectionInfo
{
private Dictionary<string, EnumMapping>? _enums;
private int _nextIdNumber;
- internal Dictionary<string, EnumMapping> Enums
- {
- get
- {
- if (_enums == null)
- {
- _enums = new Dictionary<string, EnumMapping>();
- }
- return _enums;
- }
- }
+ internal Dictionary<string, EnumMapping> Enums => _enums ??= new Dictionary<string, EnumMapping>();
private sealed class Member
{
[RequiresUnreferencedCode("calls WriteArray")]
private void WriteReferencedElement(string? name, string? ns, object o, Type? ambientType)
{
- if (name == null) name = string.Empty;
+ name ??= string.Empty;
Type t = o.GetType();
if (t.IsArray || typeof(IEnumerable).IsAssignableFrom(t))
{
{
anyCount++;
if (element.Name != null && element.Name.Length > 0)
+ {
namedAnys.Add(element);
- else if (unnamedAny == null)
- unnamedAny = element;
+ }
+ else
+ {
+ unnamedAny ??= element;
+ }
}
else if (choice != null)
{
{
anyCount++;
if (element.Name != null && element.Name.Length > 0)
+ {
namedAnys.Add(element);
- else if (unnamedAny == null)
- unnamedAny = element;
+ }
+ else
+ {
+ unnamedAny ??= element;
+ }
}
else if (choice != null)
{
XmlSerializerNamespaces nss = new XmlSerializerNamespaces();
nss.AddInternal("xsi", XmlSchema.InstanceNamespace);
nss.AddInternal("xsd", XmlSchema.Namespace);
- if (s_defaultNamespaces == null)
- {
- s_defaultNamespaces = nss;
- }
+ s_defaultNamespaces ??= nss;
}
return s_defaultNamespaces;
}
s_cache.Add(defaultNamespace, type, _tempAssembly);
}
}
- if (_mapping == null)
- {
- _mapping = XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace);
- }
+
+ _mapping ??= XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace);
}
[RequiresUnreferencedCode(TrimSerializationWarning)]
internal Dictionary<string, XmlQualifiedName>.ValueCollection Namespaces => NamespacesInternal.Values;
- private Dictionary<string, XmlQualifiedName> NamespacesInternal
- {
- get
- {
- if (_namespaces == null)
- _namespaces = new Dictionary<string, XmlQualifiedName>();
- return _namespaces;
- }
- }
+ private Dictionary<string, XmlQualifiedName> NamespacesInternal => _namespaces ??= new Dictionary<string, XmlQualifiedName>();
internal ArrayList? NamespaceList
{
XsltContext? xsltContext = nsResolver as XsltContext;
if (xsltContext == null)
{
- if (nsResolver == null)
- {
- nsResolver = new XmlNamespaceManager(new NameTable());
- }
+ nsResolver ??= new XmlNamespaceManager(new NameTable());
xsltContext = new UndefinedXsltContext(nsResolver);
}
_query.SetXsltContext(xsltContext);
{
if (currentNode == null)
{
- if (_nextInput == null)
- {
- _nextInput = FetchInput(); // This can happen at the beginning and at the end
- }
+ _nextInput ??= FetchInput(); // This can happen at the beginning and at the end
if (_elementStk.Count == 0)
{
if (_nextInput == null)
{
qyInput = ((DocumentOrderQuery)qyInput).input;
}
- if (_firstInput == null)
- {
- _firstInput = qyInput as BaseAxisQuery;
- }
+ _firstInput ??= qyInput as BaseAxisQuery;
bool merge = (qyInput.Properties & QueryProps.Merge) != 0;
bool reverse = (qyInput.Properties & QueryProps.Reverse) != 0;
{
Debug.Assert(pageElem[idxElem].NodeType == XPathNodeType.Element && pageNmsp[idxNmsp].NodeType == XPathNodeType.Namespace);
- if (_mapNmsp == null)
- _mapNmsp = new Dictionary<XPathNodeRef, XPathNodeRef>();
+ _mapNmsp ??= new Dictionary<XPathNodeRef, XPathNodeRef>();
_mapNmsp.Add(new XPathNodeRef(pageElem, idxElem), new XPathNodeRef(pageNmsp, idxNmsp));
}
/// </summary>
internal void AddIdElement(string id, XPathNode[] pageElem, int idxElem)
{
- if (_idValueMap == null)
- _idValueMap = new Dictionary<string, XPathNodeRef>();
+ _idValueMap ??= new Dictionary<string, XPathNodeRef>();
if (!_idValueMap.ContainsKey(id))
_idValueMap.Add(id, new XPathNodeRef(pageElem, idxElem));
try
{
string message = args == null ? res : string.Format(res, args);
- if (message == null)
- message = $"UNKNOWN({res})";
- return message;
- }
- catch (MissingManifestResourceException)
- {
- return $"UNKNOWN({res})";
+ if (message != null)
+ {
+ return message;
+ }
}
+ catch (MissingManifestResourceException) { }
+
+ return $"UNKNOWN({res})";
}
public override string Message
{
if (schemaInfo.Validity == XmlSchemaValidity.Valid)
{
- schemaType = schemaInfo.MemberType;
- if (schemaType == null)
- {
- schemaType = schemaInfo.SchemaType;
- }
+ schemaType = schemaInfo.MemberType ?? schemaInfo.SchemaType;
if (schemaType != null)
{
datatype = schemaType.Datatype;
}
}
}
- if (value == null)
- {
- value = XmlUntypedConverter.Untyped.ToString(typedValue, this);
- }
+ value ??= XmlUntypedConverter.Untyped.ToString(typedValue, this);
SetValue(value);
}
{
if (schemaInfo.Validity == XmlSchemaValidity.Valid)
{
- schemaType = schemaInfo.MemberType;
- if (schemaType == null)
- {
- schemaType = schemaInfo.SchemaType;
- }
+ schemaType = schemaInfo.MemberType ?? schemaInfo.SchemaType;
if (schemaType != null)
{
datatype = schemaType.Datatype;
{
if (schemaInfo.Validity == XmlSchemaValidity.Valid)
{
- schemaType = schemaInfo.MemberType;
- if (schemaType == null)
- {
- schemaType = schemaInfo.SchemaType;
- }
+ schemaType = schemaInfo.MemberType ?? schemaInfo.SchemaType;
if (schemaType != null)
{
return schemaType.ValueConverter.ToBoolean(Value);
{
if (schemaInfo.Validity == XmlSchemaValidity.Valid)
{
- schemaType = schemaInfo.MemberType;
- if (schemaType == null)
- {
- schemaType = schemaInfo.SchemaType;
- }
+ schemaType = schemaInfo.MemberType ?? schemaInfo.SchemaType;
if (schemaType != null)
{
return schemaType.ValueConverter.ToDateTime(Value);
{
if (schemaInfo.Validity == XmlSchemaValidity.Valid)
{
- schemaType = schemaInfo.MemberType;
- if (schemaType == null)
- {
- schemaType = schemaInfo.SchemaType;
- }
+ schemaType = schemaInfo.MemberType ?? schemaInfo.SchemaType;
if (schemaType != null)
{
return schemaType.ValueConverter.ToDouble(Value);
{
if (schemaInfo.Validity == XmlSchemaValidity.Valid)
{
- schemaType = schemaInfo.MemberType;
- if (schemaType == null)
- {
- schemaType = schemaInfo.SchemaType;
- }
+ schemaType = schemaInfo.MemberType ?? schemaInfo.SchemaType;
if (schemaType != null)
{
return schemaType.ValueConverter.ToInt32(Value);
{
if (schemaInfo.Validity == XmlSchemaValidity.Valid)
{
- schemaType = schemaInfo.MemberType;
- if (schemaType == null)
- {
- schemaType = schemaInfo.SchemaType;
- }
+ schemaType = schemaInfo.MemberType ?? schemaInfo.SchemaType;
if (schemaType != null)
{
return schemaType.ValueConverter.ToInt64(Value);
{
if (schemaInfo.Validity == XmlSchemaValidity.Valid)
{
- schemaType = schemaInfo.MemberType;
- if (schemaType == null)
- {
- schemaType = schemaInfo.SchemaType;
- }
+ schemaType = schemaInfo.MemberType ?? schemaInfo.SchemaType;
if (schemaType != null)
{
return schemaType.ValueConverter.ChangeType(Value, returnType, nsResolver);
Query query = Query.Clone(cexpr.QueryTree);
query.Reset();
- if (context == null)
- {
- context = new XPathSingletonIterator(this.Clone(), /*moved:*/true);
- }
+ context ??= new XPathSingletonIterator(this.Clone(), moved: true);
object result = query.Evaluate(context);
{
}
- public static XmlEmptyNavigator Singleton
- {
- get
- {
- if (XmlEmptyNavigator.s_singleton == null)
- XmlEmptyNavigator.s_singleton = new XmlEmptyNavigator();
- return XmlEmptyNavigator.s_singleton;
- }
- }
+ public static XmlEmptyNavigator Singleton => XmlEmptyNavigator.s_singleton ??= new XmlEmptyNavigator();
//-----------------------------------------------
// XmlReader
}
if (j > i + 1 || value[i] != 0x20)
{
- if (norValue == null)
- {
- norValue = new StringBuilder(len);
- }
+ norValue ??= new StringBuilder(len);
norValue.Append(value, startPos, i - startPos);
norValue.Append((char)0x20);
startPos = j;
continue;
}
- if (norValue == null)
- {
- norValue = new StringBuilder(len);
- }
+ norValue ??= new StringBuilder(len);
if (startPos < i)
{
norValue.Append(value, startPos, i - startPos);
(!local && !XmlCharType.IsNameCharXml4e(name[position])) ||
(matchPos == position))
{
- if (bufBld == null)
- {
- bufBld = new StringBuilder(length + 20);
- }
+ bufBld ??= new StringBuilder(length + 20);
if (matchPos == position)
if (en!.MoveNext())
{
char ch = value[i];
if ((int)ch < 0x20 || ch == '"')
{
- if (sb == null)
- {
- sb = new StringBuilder(value.Length + 4);
- }
+ sb ??= new StringBuilder(value.Length + 4);
if (i - start > 0)
{
sb.Append(value, start, i - start);
public void CallSyncToNavigator()
{
// Get helper method from module
- if (_methSyncToNav == null)
- _methSyncToNav = _module.FindMethod("SyncToNavigator");
+ _methSyncToNav ??= _module.FindMethod("SyncToNavigator");
Call(_methSyncToNav!);
}
/// </summary>
public int DeclareName(string name)
{
- if (_uniqueNames == null)
- _uniqueNames = new UniqueList<string>();
+ _uniqueNames ??= new UniqueList<string>();
return _uniqueNames.Add(name);
}
/// </summary>
public int DeclareNameFilter(string locName, string nsUri)
{
- if (_uniqueFilters == null)
- _uniqueFilters = new UniqueList<Int32Pair>();
+ _uniqueFilters ??= new UniqueList<Int32Pair>();
return _uniqueFilters.Add(new Int32Pair(DeclareName(locName), DeclareName(nsUri)));
}
}
// Add mappings to list and return index
- if (_prefixMappingsList == null)
- _prefixMappingsList = new List<StringPair[]>();
+ _prefixMappingsList ??= new List<StringPair[]>();
_prefixMappingsList.Add(prefixMappings);
return _prefixMappingsList.Count - 1;
{
int idx;
- if (_globalNames == null)
- _globalNames = new List<string>();
+ _globalNames ??= new List<string>();
idx = _globalNames.Count;
_globalNames.Add(name);
/// </summary>
public int DeclareEarlyBound(string namespaceUri, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type ebType)
{
- if (_earlyInfo == null)
- _earlyInfo = new UniqueList<EarlyBoundInfo>();
+ _earlyInfo ??= new UniqueList<EarlyBoundInfo>();
return _earlyInfo.Add(new EarlyBoundInfo(namespaceUri, ebType));
}
/// <summary>
/// Return an array of all early bound information that is used by the query (null if none is used).
/// </summary>
- public EarlyBoundInfo[]? EarlyBound
- {
- get
- {
- if (_earlyInfo != null)
- return _earlyInfo.ToArray();
-
- return null;
- }
- }
+ public EarlyBoundInfo[]? EarlyBound => _earlyInfo?.ToArray();
/// <summary>
/// Add "type" to the list of unique types that are used by this query. Return the index of
/// </summary>
public int DeclareXmlType(XmlQueryType type)
{
- if (_uniqueXmlTypes == null)
- _uniqueXmlTypes = new UniqueList<XmlQueryType>();
+ _uniqueXmlTypes ??= new UniqueList<XmlQueryType>();
XmlQueryTypeFactory.CheckSerializability(type);
return _uniqueXmlTypes.Add(type);
/// </summary>
public int DeclareCollation(string collation)
{
- if (_uniqueCollations == null)
- _uniqueCollations = new UniqueList<XmlCollation>();
+ _uniqueCollations ??= new UniqueList<XmlCollation>();
return _uniqueCollations.Add(XmlCollation.Create(collation));
}
/// This annotation is only applicable to Function nodes. It contains a list of XmlILConstructInfo annotations
/// for all QilInvoke nodes which call the annotated function.
/// </summary>
- public ArrayList CallersInfo
- {
- get
- {
- if (_callersInfo == null)
- _callersInfo = new ArrayList();
-
- return _callersInfo;
- }
- }
+ public ArrayList CallersInfo => _callersInfo ??= new ArrayList();
/// <summary>
/// Return name of this annotation.
/// </summary>
protected override QilNode VisitReference(QilNode oldNode)
{
- QilNode? newNode = _subs.FindReplacement(oldNode);
-
- if (newNode == null)
- newNode = oldNode;
+ QilNode? newNode = _subs.FindReplacement(oldNode) ?? oldNode;
// Fold reference to constant value
// This is done here because "p" currently cannot match references
newNode = FindClonedReference(oldNode);
}
- if (newNode == null)
- newNode = oldNode.ShallowClone(_fac);
+ newNode ??= oldNode.ShallowClone(_fac);
return base.Visit(newNode);
}
parent[i] = VisitReference(child);
// If no substutition found, then use original child
- if (parent[i] == null)
- parent[i] = child;
+ parent[i] ??= child;
}
else
{
protected override QilNode VisitReference(QilNode node)
{
QilReference reference = (QilReference)node;
- string name = _ngen.NameOf(node);
- if (name == null)
- name = "OUT-OF-SCOPE REFERENCE";
+ string name = _ngen.NameOf(node) ?? "OUT-OF-SCOPE REFERENCE";
this.writer.WriteStartElement("RefTo");
this.writer.WriteAttributeString("id", name);
}
// Use this.roots to impose stable ordering
- if (_roots == null)
- _roots = new List<XPathNavigator>();
+ _roots ??= new List<XPathNavigator>();
Debug.Assert(GetDocumentIndex(navThis) != GetDocumentIndex(navThat));
return GetDocumentIndex(navThis) < GetDocumentIndex(navThat) ? -1 : 1;
XPathNavigator navRoot;
// Use this.roots to impose stable ordering
- if (_roots == null)
- _roots = new List<XPathNavigator>();
+ _roots ??= new List<XPathNavigator>();
// Position navigator to root
navRoot = nav.Clone();
if (_shouldStrip)
{
// Save whitespace until it can be determined whether it will be stripped
- if (ws == null)
- ws = base.Value;
- else
- ws = string.Concat(ws, base.Value);
+ ws = ws == null ?
+ base.Value :
+ string.Concat(ws, base.Value);
// Read next event
continue;
{
XmlExtensionFunction func;
- if (_funcCached == null)
- _funcCached = new XmlExtensionFunction();
+ _funcCached ??= new XmlExtensionFunction();
// If the extension function already exists in the table, then binding has already been performed
_funcCached.Init(name, namespaceUri, numArgs, objectType, flags);
throw new XslTransformException(SR.XmlIl_UnknownExtObj, namespaceUri);
// Bind to a method on the instance object
- if (_extFuncsLate == null)
- _extFuncsLate = new XmlExtensionFunctionTable();
+ _extFuncsLate ??= new XmlExtensionFunctionTable();
// Bind to the instance, looking for a matching method (throws if no matching method)
XmlExtensionFunction extFunc = _extFuncsLate.Bind(name, namespaceUri, args.Length, instance.GetType(), XmlQueryRuntime.LateBoundFlags);
WriteNamespaceDeclarationUnchecked(prefix, ns);
// Cache attributes in order to detect duplicates
- if (_attrCache == null)
- _attrCache = new XmlAttributeCache();
+ _attrCache ??= new XmlAttributeCache();
_attrCache.Init(Writer);
Writer = _attrCache;
string genPrefix;
Debug.Assert(prefix != null && ns != null && ns.Length != 0);
- if (_conflictPrefixes == null)
- _conflictPrefixes = new Dictionary<string, string>(16);
+ _conflictPrefixes ??= new Dictionary<string, string>(16);
if (_nsmgr == null)
{
private void PushElementNames(string prefix, string localName, string ns)
{
// Push the name parts onto a stack
- if (_stkNames == null)
- _stkNames = new Stack<string>(15);
+ _stkNames ??= new Stack<string>(15);
_stkNames.Push(prefix);
_stkNames.Push(localName);
/// <summary>
/// Return the object that manages the state needed to implement various Xslt functions.
/// </summary>
- public XsltLibrary XsltFunctions
- {
- get
- {
- if (_xsltLib == null)
- {
- _xsltLib = new XsltLibrary(this);
- }
-
- return _xsltLib;
- }
- }
+ public XsltLibrary XsltFunctions => _xsltLib ??= new XsltLibrary(this);
/// <summary>
/// Get the early-bound extension object identified by "index". If it does not yet exist, create an instance using the
/// </summary>
public void Create()
{
- if (_keys == null)
- _keys = new XmlSortKey[DefaultSortKeyCount];
+ _keys ??= new XmlSortKey[DefaultSortKeyCount];
_pos = 0;
_keys[0] = null;
{
// Space was previous character or this is a non-space character
if (sb == null)
+ {
sb = new StringBuilder(value.Length);
+ }
else
+ {
sb.Append(' ');
+ }
// Copy non-space characters into string builder
- if (idxSpace == idx)
- sb.Append(value, idxStart, idx - idxStart - 1);
- else
- sb.Append(value, idxStart, idx - idxStart);
+ sb.Append(value, idxStart, idxSpace == idx ? idx - idxStart - 1 : idx - idxStart);
idxStart = idx + 1;
}
public int RegisterDecimalFormat(XmlQualifiedName name, string infinitySymbol, string nanSymbol, string characters)
{
- if (_decimalFormats == null)
- {
- _decimalFormats = new Dictionary<XmlQualifiedName, DecimalFormat>();
- }
+ _decimalFormats ??= new Dictionary<XmlQualifiedName, DecimalFormat>();
_decimalFormats.Add(name, CreateDecimalFormat(infinitySymbol, nanSymbol, characters));
return 0; // have to return something
}
public double RegisterDecimalFormatter(string formatPicture, string infinitySymbol, string nanSymbol, string characters)
{
- if (_decimalFormatters == null)
- {
- _decimalFormatters = new List<DecimalFormatter>();
- }
+ _decimalFormatters ??= new List<DecimalFormatter>();
_decimalFormatters.Add(new DecimalFormatter(formatPicture, CreateDecimalFormat(infinitySymbol, nanSymbol, characters)));
return _decimalFormatters.Count - 1;
}
Debug.Assert(results != null);
// Ensure that dataSources is always non-null
- if (dataSources == null)
- dataSources = XmlNullResolver.Singleton;
+ dataSources ??= XmlNullResolver.Singleton;
_delExec(new XmlQueryRuntime(_staticData, defaultDocument, dataSources, argumentList, results));
}
XPathScanner scanner;
QilNode result;
- if (_keyMatchBuilder == null)
- {
- _keyMatchBuilder = new KeyMatchBuilder((IXPathEnvironment)this);
- }
+ _keyMatchBuilder ??= new KeyMatchBuilder((IXPathEnvironment)this);
SetEnvironmentFlags(/*allowVariables:*/false, /*allowCurrent:*/false, /*allowKey:*/false);
if (pttrn == null)
{
}
else
{
- if (_generalKey == null)
- {
- _generalKey = CreateGeneralKeyFunction();
- }
+ _generalKey ??= CreateGeneralKeyFunction();
QilIterator i = _f.Let(name);
QilNode resolvedName = ResolveQNameDynamic(/*ignoreDefaultNs:*/true, i);
result = _f.Invoke(_generalKey, _f.ActualParameterList(i, resolvedName, key, env.GetCurrent()!));
private void FlushBuilder()
{
- if (_concat == null)
- {
- _concat = _f.BaseFactory.Sequence();
- }
+ _concat ??= _f.BaseFactory.Sequence();
if (_builder.Length != 0)
{
_concat.Add(_f.String(_builder.ToString()));
public void AddContent(XslNode node)
{
Debug.Assert(node != null);
- if (_content == null)
- {
- _content = new List<XslNode>();
- }
+ _content ??= new List<XslNode>();
_content.Add(node);
}
}
}
- if (scriptNs == null)
- {
- scriptNs = _compiler.CreatePhantomNamespace();
- }
+ scriptNs ??= _compiler.CreatePhantomNamespace();
ParseStringAttribute(1, "language");
if (!_compiler.Settings.EnableScript)
{
ContextInfo ctxInfo = _input.GetAttributes(_applyTemplatesAttributes);
- string? select = ParseStringAttribute(0, "select");
- if (select == null)
- {
- select = "node()";
- }
+ string select = ParseStringAttribute(0, "select") ?? "node()";
QilName mode = ParseModeAttribute(1);
List<XslNode> content = LoadWithParams(InstructionFlags.AllowSort);
string? groupingSize = ParseStringAttribute(10, "grouping-size");
// Default values for xsl:number : level="single" format="1"
- if (format == null)
- {
- format = "1";
- }
+ format ??= "1";
CheckNoContent();
return SetInfo(
string select = ParseStringAttribute(0, "select");
string regex = ParseStringAttribute(1, "regex" );
- string flags = ParseStringAttribute(2, "flags" );
- if (flags == null) {
- flags = "";
- }
+ string flags = ParseStringAttribute(2, "flags" ) ?? "";
ReportNYI("xsl:analyze-string");
if (format != null) ReportNYI("xsl:result-document/@format");
- if (href == null) {
- href = string.Empty;
- }
+ href ??= string.Empty;
// attHref is a BaseUri of new output tree. It should be resolved relative to "base output URI"
}
else
{
- namespaceName = _input.LookupXmlNamespace(prefix);
- if (namespaceName == null)
- {
- namespaceName = _compiler.CreatePhantomNamespace();
- }
+ namespaceName = _input.LookupXmlNamespace(prefix) ?? _compiler.CreatePhantomNamespace();
}
int index = (
(localName == null ? 1 : 0) +
// NOTE: XmlNodeType.SignificantWhitespace is not allowed here
if (_input.NodeType != XmlNodeType.Whitespace)
{
- if (result == null)
- {
- result = _input.BuildNameLineInfo();
- }
+ result ??= _input.BuildNameLineInfo();
_input.SkipNode();
}
} while (_input.MoveToNextSibling());
internal void SetParameter(XmlQualifiedName name, object value)
{
- if (_withParams == null)
- {
- _withParams = new Hashtable();
- }
+ _withParams ??= new Hashtable();
Debug.Assert(!_withParams.Contains(name), "We should check duplicate params at compile time");
_withParams[name] = value;
}
internal void ResetParams()
{
- if (_withParams != null)
- _withParams.Clear();
+ _withParams?.Clear();
}
internal object? GetParameter(XmlQualifiedName name)
{
- if (_withParams != null)
- {
- return _withParams[name];
- }
- return null;
+ return _withParams?[name];
}
internal void InitNodeSet(XPathNodeIterator nodeSet)
internal void AddNamespaceAlias(string StylesheetURI, NamespaceInfo AliasInfo)
{
- if (_globalNamespaceAliasTable == null)
- {
- _globalNamespaceAliasTable = new Hashtable();
- }
+ _globalNamespaceAliasTable ??= new Hashtable();
NamespaceInfo? duplicate = _globalNamespaceAliasTable[StylesheetURI] as NamespaceInfo;
if (duplicate == null || AliasInfo.stylesheetId <= duplicate.stylesheetId)
{
input.ToParent();
}
info.NegativeInfinitySymbol = string.Concat(info.NegativeSign, info.PositiveInfinitySymbol);
- if (Name == null)
- {
- Name = new XmlQualifiedName();
- }
+ Name ??= new XmlQualifiedName();
compiler.AddDecimalFormat(Name, format);
CheckEmpty(compiler);
}
internal void AddAction(Action? action)
{
- if (this.containedActions == null)
- {
- this.containedActions = new ArrayList();
- }
+ this.containedActions ??= new ArrayList();
this.containedActions.Add(action);
lastCopyCodeAction = null;
}
if (Ref.Equal(input.NamespaceURI, input.Atoms.UriXsl) &&
Ref.Equal(input.LocalName, input.Atoms.Sort))
{
- if (_sortContainer == null)
- {
- _sortContainer = new ContainerAction();
- }
+ _sortContainer ??= new ContainerAction();
_sortContainer.AddAction(compiler.CreateSortAction());
continue;
}
internal void InsertExtensionNamespace(string nspace)
{
- if (_extensionNamespaces == null)
- {
- _extensionNamespaces = new Hashtable();
- }
+ _extensionNamespaces ??= new Hashtable();
_extensionNamespaces[nspace] = null;
}
internal void InsertExcludedNamespace(string nspace)
{
- if (_excludedNamespaces == null)
- {
- _excludedNamespaces = new Hashtable();
- }
+ _excludedNamespaces ??= new Hashtable();
_excludedNamespaces[nspace] = null;
}
{
Debug.Assert(variable != null);
- if (_variables == null)
- {
- _variables = new Hashtable();
- }
+ _variables ??= new Hashtable();
_variables[variable.Name!] = variable;
}
}
#pragma warning restore CA1822
- internal ArrayList NumberList
- {
- get
- {
- if (_numberList == null)
- {
- _numberList = new ArrayList();
- }
- return _numberList;
- }
- }
+ internal ArrayList NumberList => _numberList ??= new ArrayList();
internal IXsltDebugger? Debugger
{
return expr;
}
- private XsltCompileContext GetValueOfContext()
- {
- if (_valueOfContext == null)
- {
- _valueOfContext = new XsltCompileContext();
- }
- return _valueOfContext;
- }
+ private XsltCompileContext GetValueOfContext() =>
+ _valueOfContext ??= new XsltCompileContext();
[Conditional("DEBUG")]
private void RecycleValueOfContext()
{
- if (_valueOfContext != null)
- {
- _valueOfContext.Recycle();
- }
+ _valueOfContext?.Recycle();
}
- private XsltCompileContext GetMatchesContext()
- {
- if (_matchesContext == null)
- {
- _matchesContext = new XsltCompileContext();
- }
- return _matchesContext;
- }
+ private XsltCompileContext GetMatchesContext() => _matchesContext ??= new XsltCompileContext();
[Conditional("DEBUG")]
private void RecycleMatchesContext()
{
- if (_matchesContext != null)
- {
- _matchesContext.Recycle();
- }
+ _matchesContext?.Recycle();
}
internal string? ValueOf(ActionFrame context, int key)
string? value = null;
if (objValue != null)
value = XmlConvert.ToXPathString(objValue);
- if (value == null)
- value = string.Empty;
- return value;
+ return value ?? string.Empty;
}
internal bool EvaluateBoolean(ActionFrame context, int key)
}
else
{
- if (sb == null)
- {
- sb = new StringBuilder(result);
- }
+ sb ??= new StringBuilder(result);
sb.Append(this.Value);
}
if (!Read())
private bool FindAttribute(string? localName, string? namespaceURI, out int attrIndex)
{
- if (namespaceURI == null)
- {
- namespaceURI = string.Empty;
- }
- if (localName == null)
- {
- localName = string.Empty;
- }
+ namespaceURI ??= string.Empty;
+ localName ??= string.Empty;
for (int index = 0; index < _attributeCount; index++)
{
private bool FindAttribute(string? name, out int attrIndex)
{
- if (name == null)
- {
- name = string.Empty;
- }
+ name ??= string.Empty;
for (int index = 0; index < _attributeCount; index++)
{
if (minus)
{
if (newComment == null)
+ {
newComment = new StringBuilder(comment, begin, index, 2 * comment.Length);
+ }
else
+ {
newComment.Append(comment, begin, index - begin);
+ }
newComment.Append(s_SpaceMinus);
begin = index + 1;
public void AddKey(XPathNavigator root, Hashtable table)
{
- if (_keyNodes == null)
- {
- _keyNodes = new ArrayList();
- }
+ _keyNodes ??= new ArrayList();
_keyNodes.Add(new DocumentKeyList(root, table));
}
private List<Key>? _keyList;
private XsltOutput? _output;
- internal XsltOutput Output
- {
- get
- {
- if (_output == null)
- {
- _output = new XsltOutput();
- }
- return _output;
- }
- }
+ internal XsltOutput Output => _output ??= new XsltOutput();
/*
* Compile
internal void InsertKey(XmlQualifiedName name, int MatchKey, int UseKey)
{
- if (_keyList == null)
- {
- _keyList = new List<Key>();
- }
+ _keyList ??= new List<Key>();
_keyList.Add(new Key(name, MatchKey, UseKey));
}
private void CacheRecord(RecordBuilder record)
{
- if (_outputCache == null)
- {
- _outputCache = new ArrayList();
- }
+ _outputCache ??= new ArrayList();
_outputCache.Add(record.MainNode.Clone());
}
internal void AddAttributeSet(AttributeSetAction attributeSet)
{
Debug.Assert(attributeSet.Name != null);
- if (_attributeSetTable == null)
- {
- _attributeSetTable = new Hashtable();
- }
- Debug.Assert(_attributeSetTable != null);
+ _attributeSetTable ??= new Hashtable();
if (_attributeSetTable.ContainsKey(attributeSet.Name) == false)
{
if (template.MatchKey != Compiler.InvalidQueryKey)
{
- if (_modeManagers == null)
- {
- _modeManagers = new Hashtable();
- }
- Debug.Assert(_modeManagers != null);
-
- if (mode == null)
- {
- mode = XmlQualifiedName.Empty;
- }
+ _modeManagers ??= new Hashtable();
+ mode ??= XmlQualifiedName.Empty;
TemplateManager? manager = (TemplateManager?)_modeManagers[mode];
// If unsuccessful, search in imported documents from backwards
//
- if (action == null)
- {
- action = FindTemplateImports(processor, navigator, mode);
- }
-
- return action;
+ return action ?? FindTemplateImports(processor, navigator, mode);
}
internal TemplateAction? FindTemplateImports(Processor processor, XPathNavigator navigator, XmlQualifiedName mode)
}
// Built-int template rules
- if (action == null)
- {
- action = BuiltInTemplate(frame.Node!);
- }
+ action ??= BuiltInTemplate(frame.Node!);
// Jump
if (action != null)
}
// Built-int template rules
- if (action == null)
- {
- action = BuiltInTemplate(frame.Node!);
- }
+ action ??= BuiltInTemplate(frame.Node!);
// Jump
if (action != null)
_mode.Equals(template.Mode)
);
- if (this.templates == null)
- {
- this.templates = new ArrayList();
- }
+ this.templates ??= new ArrayList();
this.templates.Add(template);
}
{
string[] qnames = XmlConvert.SplitString(value);
- if (_cdataElements == null)
- {
- _cdataElements = new Hashtable(qnames.Length);
- }
+ _cdataElements ??= new Hashtable(qnames.Length);
for (int i = 0; i < qnames.Length; i++)
{
if (matchingProperties.Count == 0)
return null;
- if (binder == null)
- binder = Type.DefaultBinder;
+ binder ??= Type.DefaultBinder;
return binder.SelectProperty(bindingAttr, matchingProperties.ToArray(), returnType, types, modifiers);
}
{
Debug.Assert(getPropertySetter && types != null && types.Length == 1);
- if (binder == null)
- binder = Type.DefaultBinder;
+ binder ??= Type.DefaultBinder;
return (MethodInfo?)binder.SelectMethod(bindingAttr, matchingMethods.ToArray(), types, modifiers);
}
}
- private IEnumerable<PropertyInfo> NewProperties
- {
- get
- {
- if (_newProperties == null)
- {
- _newProperties = ReflectionContext.GetNewPropertiesForType(this);
- }
-
- return _newProperties;
- }
- }
+ private IEnumerable<PropertyInfo> NewProperties => _newProperties ??= ReflectionContext.GetNewPropertiesForType(this);
}
}
// Gets or creates the ConstructorInfo for the IgnoresAccessChecksAttribute.
// This attribute is both defined and referenced in the dynamic assembly to
// allow access to internal types in other assemblies.
- internal ConstructorInfo IgnoresAccessChecksAttributeConstructor
- {
- get
- {
- if (_ignoresAccessChecksToAttributeConstructor == null)
- {
- _ignoresAccessChecksToAttributeConstructor = IgnoreAccessChecksToAttributeBuilder.AddToModule(_mb);
- }
-
- return _ignoresAccessChecksToAttributeConstructor;
- }
- }
+ internal ConstructorInfo IgnoresAccessChecksAttributeConstructor =>
+ _ignoresAccessChecksToAttributeConstructor ??= IgnoreAccessChecksToAttributeBuilder.AddToModule(_mb);
public GeneratedTypeInfo GetProxyType(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type baseType,
ValidateLabel(handlerStart, nameof(handlerStart));
ValidateLabel(handlerEnd, nameof(handlerEnd));
- if (_lazyExceptionHandlers == null)
- {
- _lazyExceptionHandlers = ImmutableArray.CreateBuilder<ExceptionHandlerInfo>();
- }
+ _lazyExceptionHandlers ??= ImmutableArray.CreateBuilder<ExceptionHandlerInfo>();
_lazyExceptionHandlers.Add(new ExceptionHandlerInfo(kind, tryStart, tryEnd, handlerStart, handlerEnd, filterStart, catchType));
}
Debug.Assert(data.Namespaces!.Count == 0);
data.MergeInto(existingRecord);
- if (remaps == null)
- {
- remaps = new List<KeyValuePair<NamespaceDefinitionHandle, NamespaceDataBuilder>>();
- }
+ remaps ??= new List<KeyValuePair<NamespaceDefinitionHandle, NamespaceDataBuilder>>();
remaps.Add(new KeyValuePair<NamespaceDefinitionHandle, NamespaceDataBuilder>(group.Key, existingRecord));
}
else
Throw.ArgumentNull(nameof(metadata));
}
- if (utf8Decoder == null)
- {
- utf8Decoder = MetadataStringDecoder.DefaultUTF8;
- }
+ utf8Decoder ??= MetadataStringDecoder.DefaultUTF8;
if (!(utf8Decoder.Encoding is UTF8Encoding))
{
break;
case MethodSemanticsAttributes.Other:
- if (other == null)
- other = ImmutableArray.CreateBuilder<MethodDefinitionHandle>();
+ other ??= ImmutableArray.CreateBuilder<MethodDefinitionHandle>();
other.Add(_reader.MethodSemanticsTable.GetMethod(rowId));
break;
break;
case MethodSemanticsAttributes.Other:
- if (other == null)
- other = ImmutableArray.CreateBuilder<MethodDefinitionHandle>();
+ other ??= ImmutableArray.CreateBuilder<MethodDefinitionHandle>();
other.Add(_reader.MethodSemanticsTable.GetMethod(rowId));
break;
return false;
}
- private static MethodInfo? GetAccessorMethod(PropertyInfo property)
- {
- MethodInfo? accessor = property.GetMethod;
- if (accessor == null)
- {
- accessor = property.SetMethod;
- }
-
- return accessor;
- }
+ private static MethodInfo? GetAccessorMethod(PropertyInfo property) =>
+ property.GetMethod ?? property.SetMethod;
}
}
}
else
{
- if (exceptions == null)
- {
- exceptions = new List<Exception>();
- }
+ exceptions ??= new List<Exception>();
exceptions.Add(exception!);
}
}
Func<Assembly?, string, bool, Type?> typeResolver =
delegate (Assembly? assembly, string fullName, bool ignoreCase2)
{
- if (assembly == null)
- assembly = defaultAssembly;
+ assembly ??= defaultAssembly;
Debug.Assert(assembly is RoAssembly);
RoAssembly roAssembly = (RoAssembly)assembly;
for (int position = -1; position < numParameters; position++)
{
Type parameterType = position == -1 ? sig.ReturnType : sig.ParameterTypes[position];
- if (methodSig[position] == null)
- methodSig[position] = new RoThinMethodParameter(roMethodBase, position, parameterType);
+ methodSig[position] ??= new RoThinMethodParameter(roMethodBase, position, parameterType);
}
return methodSig;
if ((bindingAttr & BindingFlags.ExactBinding) != 0)
return System.DefaultBinder.ExactBinding(candidates.ToArray(), types, modifiers) as ConstructorInfo;
- if (binder == null)
- binder = Loader.GetDefaultBinder();
+ binder ??= Loader.GetDefaultBinder();
return binder.SelectMethod(bindingAttr, candidates.ToArray(), types, modifiers) as ConstructorInfo;
}
if (types.Length == 0 && candidates.Count == 1)
return candidates[0];
- if (binder == null)
- binder = Loader.GetDefaultBinder();
+ binder ??= Loader.GetDefaultBinder();
return binder.SelectMethod(bindingAttr, candidates.ToArray(), types, modifiers) as MethodInfo;
}
}
if ((bindingAttr & BindingFlags.ExactBinding) != 0)
return System.DefaultBinder.ExactPropertyBinding(candidates.ToArray(), returnType, types, modifiers);
- if (binder == null)
- binder = Loader.GetDefaultBinder();
+ binder ??= Loader.GetDefaultBinder();
return binder.SelectProperty(bindingAttr, candidates.ToArray(), returnType, types, modifiers);
}
#pragma warning disable SYSLIB0011
private object ReadBinaryFormattedObject()
{
- if (_formatter == null)
+ _formatter ??= new BinaryFormatter()
{
- _formatter = new BinaryFormatter()
- {
- Binder = new UndoTruncatedTypeNameSerializationBinder()
- };
- }
+ Binder = new UndoTruncatedTypeNameSerializationBinder()
+ };
return _formatter.Deserialize(_store.BaseStream);
}
set { _absExpiry = value; }
}
- public Collection<ChangeMonitor> ChangeMonitors
- {
- get
- {
- if (_changeMonitors == null)
- {
- _changeMonitors = new Collection<ChangeMonitor>();
- }
- return _changeMonitors;
- }
- }
+ public Collection<ChangeMonitor> ChangeMonitors => _changeMonitors ??= new Collection<ChangeMonitor>();
public CacheItemPriority Priority
{
{
lock (s_initLock)
{
- if (s_defaultCache == null)
- {
- s_defaultCache = new MemoryCache();
- }
+ s_defaultCache ??= new MemoryCache();
}
}
return s_defaultCache;
// Ensure the sentinel depends on its updatable entry
string[] cacheKeys = { key };
ChangeMonitor expensiveObjectDep = CreateCacheEntryChangeMonitor(cacheKeys);
- if (changeMonitors == null)
- {
- changeMonitors = new Collection<ChangeMonitor>();
- }
+ changeMonitors ??= new Collection<ChangeMonitor>();
changeMonitors.Add(expensiveObjectDep);
// Insert sentinel entry for the updatable cache entry
object value = GetInternal(key, null);
if (value != null)
{
- if (values == null)
- {
- values = new Dictionary<string, object>();
- }
+ values ??= new Dictionary<string, object>();
values[key] = value;
}
}
{
return;
}
- if (_fields == null)
- {
- _fields = new SeldomUsedFields();
- }
- if (_fields._cache == null)
- {
- _fields._cache = cache;
- }
- if (_fields._dependents == null)
- {
- _fields._dependents = new Dictionary<MemoryCacheEntryChangeMonitor, MemoryCacheEntryChangeMonitor>();
- }
+
+ _fields ??= new SeldomUsedFields();
+ _fields._cache ??= cache;
+ _fields._dependents ??= new Dictionary<MemoryCacheEntryChangeMonitor, MemoryCacheEntryChangeMonitor>();
_fields._dependents[dependent] = dependent;
}
}
{
lock (this)
{
- if (_fields == null)
- {
- _fields = new SeldomUsedFields();
- }
+ _fields ??= new SeldomUsedFields();
_fields._updateSentinel = Tuple.Create(sentinelStore, sentinelEntry);
}
}
private static async Task<Solution> AddDisableRuntimeMarshallingAttributeApplicationToProject(Project project, CancellationToken cancellationToken)
{
- Document? assemblyInfo = project.Documents.FirstOrDefault(IsPropertiesAssemblyInfo);
-
- if (assemblyInfo is null)
- {
- assemblyInfo = project.AddDocument(AssemblyInfoFileName, "", folders: new[] { PropertiesFolderName });
- }
+ Document? assemblyInfo =
+ project.Documents.FirstOrDefault(IsPropertiesAssemblyInfo) ??
+ project.AddDocument(AssemblyInfoFileName, "", folders: new[] { PropertiesFolderName });
DocumentEditor editor = await DocumentEditor.CreateAsync(assemblyInfo, cancellationToken).ConfigureAwait(false);
var generatorDiagnostics = new GeneratorDiagnostics();
// Process the LibraryImport attribute
- LibraryImportData? libraryImportData = ProcessLibraryImportAttribute(generatedDllImportAttr!);
-
- if (libraryImportData is null)
- {
- libraryImportData = new LibraryImportData("INVALID_CSHARP_SYNTAX");
- }
+ LibraryImportData libraryImportData =
+ ProcessLibraryImportAttribute(generatedDllImportAttr!) ??
+ new LibraryImportData("INVALID_CSHARP_SYNTAX");
if (libraryImportData.IsUserDefined.HasFlag(InteropAttributeMember.StringMarshalling))
{
return false;
var namedArguments = attr.NamedArguments.ToImmutableDictionary();
- CustomTypeMarshallerData? inMarshaller = GetNamedArgumentAsMarshallerData(namedArguments, MarshallersProperties.InMarshaller, MarshallingDirection.ManagedToUnmanaged, managedTypeOnAttr, compilation);
- if (inMarshaller is null)
- inMarshaller = GetMarshallerDataForType(entryPointType, MarshallingDirection.ManagedToUnmanaged, managedTypeOnAttr, compilation);
+ CustomTypeMarshallerData? inMarshaller =
+ GetNamedArgumentAsMarshallerData(namedArguments, MarshallersProperties.InMarshaller, MarshallingDirection.ManagedToUnmanaged, managedTypeOnAttr, compilation) ??
+ GetMarshallerDataForType(entryPointType, MarshallingDirection.ManagedToUnmanaged, managedTypeOnAttr, compilation);
- CustomTypeMarshallerData? refMarshaller = GetNamedArgumentAsMarshallerData(namedArguments, MarshallersProperties.RefMarshaller, MarshallingDirection.Bidirectional, managedTypeOnAttr, compilation);
- if (refMarshaller is null)
- refMarshaller = GetMarshallerDataForType(entryPointType, MarshallingDirection.Bidirectional, managedTypeOnAttr, compilation);
+ CustomTypeMarshallerData? refMarshaller =
+ GetNamedArgumentAsMarshallerData(namedArguments, MarshallersProperties.RefMarshaller, MarshallingDirection.Bidirectional, managedTypeOnAttr, compilation) ??
+ GetMarshallerDataForType(entryPointType, MarshallingDirection.Bidirectional, managedTypeOnAttr, compilation);
- CustomTypeMarshallerData? outMarshaller = GetNamedArgumentAsMarshallerData(namedArguments, MarshallersProperties.OutMarshaller, MarshallingDirection.UnmanagedToManaged, managedTypeOnAttr, compilation);
- if (outMarshaller is null)
- outMarshaller = GetMarshallerDataForType(entryPointType, MarshallingDirection.UnmanagedToManaged, managedTypeOnAttr, compilation);
+ CustomTypeMarshallerData? outMarshaller =
+ GetNamedArgumentAsMarshallerData(namedArguments, MarshallersProperties.OutMarshaller, MarshallingDirection.UnmanagedToManaged, managedTypeOnAttr, compilation) ??
+ GetMarshallerDataForType(entryPointType, MarshallingDirection.UnmanagedToManaged, managedTypeOnAttr, compilation);
if (inMarshaller is null && refMarshaller is null && outMarshaller is null)
return false;
// For each method find if attribute is present, the return type is void and the method is not virtual
if (m.IsDefined(attribute, false))
{
- if (mi == null) mi = new List<MethodInfo>();
+ mi ??= new List<MethodInfo>();
mi.Add(m);
}
}
/// <summary>
/// Gets the collection of Properties associated with the <see cref="Claim"/>.
/// </summary>
- public IDictionary<string, string> Properties
- {
- get
- {
- if (_properties == null)
- {
- _properties = new Dictionary<string, string>();
- }
- return _properties;
- }
- }
+ public IDictionary<string, string> Properties => _properties ??= new Dictionary<string, string>();
/// <summary>
/// Gets the subject of the <see cref="Claim"/>.
/// Allow the association of claims with this instance of <see cref="ClaimsIdentity"/>.
/// The claims will not be serialized or added in Clone(). They will be included in searches, finds and returned from the call to <see cref="ClaimsIdentity.Claims"/>.
/// </summary>
- internal List<List<Claim>> ExternalClaims
- {
- get
- {
- if (_externalClaims == null)
- {
- _externalClaims = new List<List<Claim>>();
- }
- return _externalClaims;
- }
- }
+ internal List<List<Claim>> ExternalClaims => _externalClaims ??= new List<List<Claim>>();
/// <summary>
/// Gets or sets the label for this <see cref="ClaimsIdentity"/>
byte[] encrypted = safeContents.Encrypt(ReadOnlySpan<char>.Empty, passwordBytes, pbeParameters);
- if (_contents == null)
- {
- _contents = new List<ContentInfoAsn>();
- }
+ _contents ??= new List<ContentInfoAsn>();
_contents.Add(
new ContentInfoAsn
byte[] encrypted = safeContents.Encrypt(password, ReadOnlySpan<byte>.Empty, pbeParameters);
- if (_contents == null)
- {
- _contents = new List<ContentInfoAsn>();
- }
+ _contents ??= new List<ContentInfoAsn>();
_contents.Add(
new ContentInfoAsn
if (IsSealed)
throw new InvalidOperationException(SR.Cryptography_Pkcs12_PfxIsSealed);
- if (_contents == null)
- {
- _contents = new List<ContentInfoAsn>();
- }
+ _contents ??= new List<ContentInfoAsn>();
_contents.Add(safeContents.EncodeToContentInfo());
}
public Oid GetCertificateType()
{
- if (_certTypeOid == null)
- {
- _certTypeOid = new Oid(_decoded.CertId);
- }
+ _certTypeOid ??= new Oid(_decoded.CertId);
return _certTypeOid.CopyOid();
}
{
get
{
- if (_attributes == null)
- {
- _attributes = new CryptographicAttributeObjectCollection();
- }
+ _attributes ??= new CryptographicAttributeObjectCollection();
return _attributes;
}
public Oid GetBagId()
{
- if (_bagOid == null)
- {
- _bagOid = new Oid(_bagIdValue);
- }
+ _bagOid ??= new Oid(_bagIdValue);
return _bagOid.CopyOid();
}
if (IsReadOnly)
throw new InvalidOperationException(SR.Cryptography_Pkcs12_SafeContentsIsReadOnly);
- if (_bags == null)
- {
- _bags = new List<Pkcs12SafeBag>();
- }
+ _bags ??= new List<Pkcs12SafeBag>();
_bags.Add(safeBag);
}
{
}
- if (bag == null)
- {
- bag = new Pkcs12SafeBag.UnknownBag(serializedBags[i].BagId, bagValue);
- }
+ bag ??= new Pkcs12SafeBag.UnknownBag(serializedBags[i].BagId, bagValue);
bag.Attributes = SignerInfo.MakeAttributeCollection(serializedBags[i].BagAttributes);
bags.Add(bag);
public Oid GetSecretType()
{
- if (_secretTypeOid == null)
- {
- _secretTypeOid = new Oid(_decoded.SecretTypeId);
- }
+ _secretTypeOid ??= new Oid(_decoded.SecretTypeId);
return _secretTypeOid.CopyOid();
}
_document = ownerDocument;
}
- public CryptographicAttributeObjectCollection SignedAttributes
- {
- get
- {
- if (_parsedSignedAttrs == null)
- {
- _parsedSignedAttrs = MakeAttributeCollection(_signedAttributes);
- }
-
- return _parsedSignedAttrs;
- }
- }
-
- public CryptographicAttributeObjectCollection UnsignedAttributes
- {
- get
- {
- if (_parsedUnsignedAttrs == null)
- {
- _parsedUnsignedAttrs = MakeAttributeCollection(_unsignedAttributes);
- }
+ public CryptographicAttributeObjectCollection SignedAttributes =>
+ _parsedSignedAttrs ??= MakeAttributeCollection(_signedAttributes);
- return _parsedUnsignedAttrs;
- }
- }
+ public CryptographicAttributeObjectCollection UnsignedAttributes =>
+ _parsedUnsignedAttrs ??= MakeAttributeCollection(_unsignedAttributes);
internal ReadOnlyMemory<byte> GetSignatureMemory() => _signature;
public byte[] GetSignature() => _signature.ToArray();
- public X509Certificate2? Certificate
- {
- get
- {
- if (_signerCertificate == null)
- {
- _signerCertificate = FindSignerCertificate();
- }
-
- return _signerCertificate;
- }
- }
+ public X509Certificate2? Certificate =>
+ _signerCertificate ??= FindSignerCertificate();
public SignerInfoCollection CounterSignerInfos
{
public string Recipient
{
- get
- {
- // an unspecified value for an XmlAttribute is string.Empty
- if (_recipient == null)
- _recipient = string.Empty;
- return _recipient;
- }
+ get => _recipient ??= string.Empty; // an unspecified value for an XmlAttribute is string.Empty
set
{
_recipient = value;
}
}
- public ReferenceList ReferenceList
- {
- get
- {
- if (_referenceList == null)
- _referenceList = new ReferenceList();
- return _referenceList;
- }
- }
+ public ReferenceList ReferenceList => _referenceList ??= new ReferenceList();
public void AddReference(DataReference dataReference)
{
public TransformChain TransformChain
{
- get
- {
- if (_transformChain == null)
- _transformChain = new TransformChain();
- return _transformChain;
- }
+ get => _transformChain ??= new TransformChain();
set
{
_transformChain = value;
public KeyInfo KeyInfo
{
- get
- {
- if (_keyInfo == null)
- _keyInfo = new KeyInfo();
- return _keyInfo;
- }
- set { _keyInfo = value; }
+ get => _keyInfo ??= new KeyInfo();
+ set => _keyInfo = value;
}
public virtual EncryptionMethod EncryptionMethod
}
}
- public virtual EncryptionPropertyCollection EncryptionProperties
- {
- get
- {
- if (_props == null)
- _props = new EncryptionPropertyCollection();
- return _props;
- }
- }
+ public virtual EncryptionPropertyCollection EncryptionProperties => _props ??= new EncryptionPropertyCollection();
public void AddProperty(EncryptionProperty ep)
{
public virtual CipherData CipherData
{
- get
- {
- if (_cipherData == null)
- _cipherData = new CipherData();
-
- return _cipherData;
- }
+ get => _cipherData ??= new CipherData();
set
{
if (value == null)
// when an EncyptedData references an EncryptedKey using a CarriedKeyName and Recipient
public string Recipient
{
- get
- {
- // an unspecified value for an XmlAttribute is string.Empty
- if (_recipient == null)
- _recipient = string.Empty;
- return _recipient;
- }
- set { _recipient = value; }
+ get => _recipient ??= string.Empty; // an unspecified value for an XmlAttribute is string.Empty
+ set => _recipient = value;
}
//
KeyInfoClause keyInfoClause = CryptoHelpers.CreateFromName<KeyInfoClause>(kicString);
// if we don't know what kind of KeyInfoClause we're looking at, use a generic KeyInfoNode:
- if (keyInfoClause == null)
- keyInfoClause = new KeyInfoNode();
+ keyInfoClause ??= new KeyInfoNode();
// Ask the create clause to fill itself with the corresponding XML
keyInfoClause.LoadXml(elem);
throw new ArgumentNullException(nameof(certificate));
}
- if (_certificates == null)
- _certificates = new ArrayList();
+ _certificates ??= new ArrayList();
X509Certificate2 x509 = new X509Certificate2(certificate);
_certificates.Add(x509);
public void AddSubjectKeyId(byte[] subjectKeyId)
{
- if (_subjectKeyIds == null)
- _subjectKeyIds = new ArrayList();
+ _subjectKeyIds ??= new ArrayList();
_subjectKeyIds.Add(subjectKeyId);
}
public void AddSubjectKeyId(string subjectKeyId)
{
- if (_subjectKeyIds == null)
- _subjectKeyIds = new ArrayList();
+ _subjectKeyIds ??= new ArrayList();
_subjectKeyIds.Add(Utils.DecodeHexString(subjectKeyId));
}
public void AddSubjectName(string subjectName)
{
- if (_subjectNames == null)
- _subjectNames = new ArrayList();
+ _subjectNames ??= new ArrayList();
_subjectNames.Add(subjectName);
}
if (!BigInteger.TryParse(serialNumber, NumberStyles.AllowHexSpecifier, NumberFormatInfo.CurrentInfo, out h))
throw new ArgumentException(SR.Cryptography_Xml_InvalidX509IssuerSerialNumber, nameof(serialNumber));
- if (_issuerSerials == null)
- _issuerSerials = new ArrayList();
+ _issuerSerials ??= new ArrayList();
_issuerSerials.Add(Utils.CreateX509IssuerSerial(issuerName, h.ToString()));
}
// When we load an X509Data from Xml, we know the serial number is in decimal representation.
internal void InternalAddIssuerSerial(string issuerName, string serialNumber)
{
- if (_issuerSerials == null)
- _issuerSerials = new ArrayList();
+ _issuerSerials ??= new ArrayList();
_issuerSerials.Add(Utils.CreateX509IssuerSerial(issuerName, serialNumber));
}
public TransformChain TransformChain
{
- get
- {
- if (_transformChain == null)
- _transformChain = new TransformChain();
- return _transformChain;
- }
+ get => _transformChain ??= new TransformChain();
set
{
_transformChain = value;
public KeyInfo KeyInfo
{
- get
- {
- if (_keyInfo == null)
- _keyInfo = new KeyInfo();
- return _keyInfo;
- }
- set { _keyInfo = value; }
+ get => _keyInfo ??= new KeyInfo();
+ set => _keyInfo = value;
}
public IList ObjectList
public EncryptedXml EncryptedXml
{
- get
- {
- if (_exml == null)
- _exml = new EncryptedXml(_containingDocument); // default processing rules
- return _exml;
- }
- set { _exml = value; }
+ get => _exml ??= new EncryptedXml(_containingDocument); // default processing rules
+ set => _exml = value;
}
public Signature Signature
m_signature.LoadXml(value);
- if (_context == null)
- {
- _context = value;
- }
+ _context ??= value;
_bCacheValid = false;
}
else if (key is RSA)
{
// Default to RSA-SHA256
- if (SignedInfo.SignatureMethod == null)
- SignedInfo.SignatureMethod = XmlDsigRSASHA256Url;
+ SignedInfo.SignatureMethod ??= XmlDsigRSASHA256Url;
}
else
{
return key;
}
- if (_keyInfoEnum == null)
- _keyInfoEnum = KeyInfo.GetEnumerator();
+ _keyInfoEnum ??= KeyInfo.GetEnumerator();
// In our implementation, we move to the next KeyInfo clause which is an RSAKeyValue, DSAKeyValue or KeyInfoX509Data
while (_keyInfoEnum.MoveNext())
{
- RSAKeyValue rsaKeyValue = _keyInfoEnum.Current as RSAKeyValue;
- if (rsaKeyValue != null)
- return rsaKeyValue.Key;
+ switch (_keyInfoEnum.Current)
+ {
+ case RSAKeyValue rsaKeyValue:
+ return rsaKeyValue.Key;
- DSAKeyValue dsaKeyValue = _keyInfoEnum.Current as DSAKeyValue;
- if (dsaKeyValue != null)
- return dsaKeyValue.Key;
+ case DSAKeyValue dsaKeyValue:
+ return dsaKeyValue.Key;
- KeyInfoX509Data x509Data = _keyInfoEnum.Current as KeyInfoX509Data;
- if (x509Data != null)
- {
- _x509Collection = Utils.BuildBagOfCerts(x509Data, CertUsageType.Verification);
- if (_x509Collection.Count > 0)
- {
- _x509Enum = _x509Collection.GetEnumerator();
- AsymmetricAlgorithm key = GetNextCertificatePublicKey();
- if (key != null)
- return key;
- }
+ case KeyInfoX509Data x509Data:
+ _x509Collection = Utils.BuildBagOfCerts(x509Data, CertUsageType.Verification);
+ if (_x509Collection.Count > 0)
+ {
+ _x509Enum = _x509Collection.GetEnumerator();
+ AsymmetricAlgorithm key = GetNextCertificatePublicKey();
+ if (key != null)
+ return key;
+ }
+ break;
}
}
{
foreach (KeyInfoClause clause in KeyInfo)
{
- KeyInfoX509Data x509Data = clause as KeyInfoX509Data;
- if (x509Data != null)
+ if (clause is KeyInfoX509Data x509Data)
+ {
collection.AddRange(Utils.BuildBagOfCerts(x509Data, CertUsageType.Verification));
+ }
}
}
foreach (Reference reference in sortedReferences)
{
// If no DigestMethod has yet been set, default it to sha1
- if (reference.DigestMethod == null)
- reference.DigestMethod = Reference.DefaultDigestMethod;
+ reference.DigestMethod ??= Reference.DefaultDigestMethod;
SignedXmlDebugLog.LogSigningReference(this, reference);
Algorithm = SignedXml.XmlDecryptionTransformUrl;
}
- private ArrayList ExceptUris
- {
- get
- {
- if (_arrayListUri == null)
- _arrayListUri = new ArrayList();
- return _arrayListUri;
- }
- }
+ private ArrayList ExceptUris => _arrayListUri ??= new ArrayList();
protected virtual bool IsTargetElement(XmlElement inputElement, string idValue)
{
{
if (type == typeof(XmlNodeList) || type.IsSubclassOf(typeof(XmlNodeList)))
{
- if (_inputNodeList == null)
- {
- _inputNodeList = Utils.AllDescendantNodes(_containingDocument, true);
- }
+ _inputNodeList ??= Utils.AllDescendantNodes(_containingDocument, true);
return (XmlNodeList)GetOutput();
}
else if (type == typeof(XmlDocument) || type.IsSubclassOf(typeof(XmlDocument)))
if (nameOrOid == null)
return CapiHelper.CALG_SHA1;
- string? oidValue = CryptoConfig.MapNameToOID(nameOrOid);
- if (oidValue == null)
- oidValue = nameOrOid; // we were probably passed an OID value directly
+ string oidValue = CryptoConfig.MapNameToOID(nameOrOid) ?? nameOrOid; // we were probably passed an OID value directly
int algId = GetAlgIdFromOid(oidValue, oidGroup);
if (algId == 0 || algId == -1)
{
ArgumentNullException.ThrowIfNull(algorithm);
- if (creationParameters == null)
- creationParameters = new CngKeyCreationParameters();
+ creationParameters ??= new CngKeyCreationParameters();
SafeNCryptProviderHandle providerHandle = creationParameters.Provider!.OpenStorageProvider();
SafeNCryptKeyHandle keyHandle;
public Oid(string oid)
{
// If we were passed the friendly name, retrieve the value String.
- string? oidValue = OidLookup.ToOid(oid, OidGroup.All, fallBackToAllGroups: false);
- if (oidValue == null)
- {
- oidValue = oid;
- }
- this.Value = oidValue;
+ this.Value = OidLookup.ToOid(oid, OidGroup.All, fallBackToAllGroups: false) ?? oid;
_group = OidGroup.All;
}
get
{
// If we were passed the friendly name, retrieve the value String.
- string? oidValue = OidLookup.ToOid(oid, OidGroup.All, fallBackToAllGroups: false);
- if (oidValue == null)
- {
- oidValue = oid;
- }
+ string? oidValue = OidLookup.ToOid(oid, OidGroup.All, fallBackToAllGroups: false) ?? oid;
for (int i = 0; i < _count; i++)
{
Oid entry = _oids[i];
private static SafeProvHandle AcquireSafeProviderHandle(CspParameters? cspParams)
{
- if (cspParams == null)
- {
- cspParams = new CspParameters(CapiHelper.DefaultRsaProviderType);
- }
+ cspParams ??= new CspParameters(CapiHelper.DefaultRsaProviderType);
CapiHelper.AcquireCsp(cspParams, out SafeProvHandle safeProvHandle);
return safeProvHandle;
public override void AppendHashData(ReadOnlySpan<byte> data)
{
- if (buffer == null)
- {
- buffer = new MemoryStream(1000);
- }
+ buffer ??= new MemoryStream(1000);
buffer.Write(data);
}
e = value;
break;
default:
- if (firstRdn == null)
- {
- firstRdn = value;
- }
-
+ firstRdn ??= value;
break;
}
}
AddUniqueStatus(overallStatus, ref statusToSet);
for (int i = index; i >= 0; i--)
{
- if (statuses[i] == null)
- {
- statuses[i] = new List<X509ChainStatus>();
- }
+ statuses[i] ??= new List<X509ChainStatus>();
AddUniqueStatus(statuses[i], ref statusToSet);
}
break;
}
- if (downloadedCerts == null)
- {
- downloadedCerts = new List<X509Certificate2>();
- }
+ downloadedCerts ??= new List<X509Certificate2>();
AddToStackAndUpRef(downloaded.Handle, _untrustedLookup);
downloadedCerts.Add(downloaded);
if (failsPolicyChecks)
{
- if (overallStatus == null)
- {
- overallStatus = new List<X509ChainStatus>();
- }
+ overallStatus ??= new List<X509ChainStatus>();
X509ChainStatus chainStatus = new X509ChainStatus
{
private void Decrypt(ReadOnlySpan<char> password, ReadOnlyMemory<byte> authSafeContents)
{
- if (_safeContentsValues == null)
- {
- _safeContentsValues = DecodeSafeContents(authSafeContents);
- }
+ _safeContentsValues ??= DecodeSafeContents(authSafeContents);
// The average PFX contains one cert, and one key.
// The next most common PFX contains 3 certs, and one key.
_lazyDistinguishedName = distinguishedName;
}
- public string Name
- {
- get
- {
- string? name = _lazyDistinguishedName;
- if (name == null)
- {
- name = _lazyDistinguishedName = Decode(X500DistinguishedNameFlags.Reversed);
- }
- return name;
- }
- }
+ public string Name => _lazyDistinguishedName ??= Decode(X500DistinguishedNameFlags.Reversed);
public string Decode(X500DistinguishedNameFlags flag)
{
if (!HasPrivateKey)
return null;
- if (_lazyPrivateKey == null)
+ _lazyPrivateKey ??= GetKeyAlgorithm() switch
{
- _lazyPrivateKey = GetKeyAlgorithm() switch
- {
- Oids.Rsa => Pal.GetRSAPrivateKey(),
- Oids.Dsa => Pal.GetDSAPrivateKey(),
-
- // This includes ECDSA, because an Oids.EcPublicKey key can be
- // many different algorithm kinds, not necessarily with mutual exclusion.
- // Plus, .NET Framework only supports RSA and DSA in this property.
- _ => throw new NotSupportedException(SR.NotSupported_KeyAlgorithm),
- };
- }
+ Oids.Rsa => Pal.GetRSAPrivateKey(),
+ Oids.Dsa => Pal.GetDSAPrivateKey(),
+
+ // This includes ECDSA, because an Oids.EcPublicKey key can be
+ // many different algorithm kinds, not necessarily with mutual exclusion.
+ // Plus, .NET Framework only supports RSA and DSA in this property.
+ _ => throw new NotSupportedException(SR.NotSupported_KeyAlgorithm),
+ };
return _lazyPrivateKey;
}
return new X509Chain();
}
- public X509ChainElementCollection ChainElements
- {
- get
- {
- if (_chainElements == null)
- _chainElements = new X509ChainElementCollection();
- return _chainElements;
- }
- }
+ public X509ChainElementCollection ChainElements => _chainElements ??= new X509ChainElementCollection();
public X509ChainPolicy ChainPolicy
{
- get
- {
- if (_chainPolicy == null)
- _chainPolicy = new X509ChainPolicy();
- return _chainPolicy;
- }
+ get => _chainPolicy ??= new X509ChainPolicy();
set
{
ArgumentNullException.ThrowIfNull(value);
get
{
// We give the user a reference to the array since we'll never access it.
- X509ChainStatus[]? chainStatus = _lazyChainStatus;
- if (chainStatus == null)
- chainStatus = _lazyChainStatus = (_pal == null ? Array.Empty<X509ChainStatus>() : _pal.ChainStatus!);
- return chainStatus;
+ return _lazyChainStatus ??= (_pal == null ? Array.Empty<X509ChainStatus>() : _pal.ChainStatus!);
}
}
{
private PublicKey? _publicKey;
- public PublicKey PublicKey
- {
- get
- {
- if (_publicKey == null)
- {
- _publicKey = BuildPublicKey();
- }
-
- return _publicKey;
- }
- }
+ public PublicKey PublicKey => _publicKey ??= BuildPublicKey();
public abstract byte[] GetSignatureAlgorithmIdentifier(HashAlgorithmName hashAlgorithm);
public abstract byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm);
return null;
}
- if (_enumerator == null)
- {
- _enumerator = _enumerable.GetEnumerator();
- }
+ _enumerator ??= _enumerable.GetEnumerator();
int origIdx = _index;
int idx = origIdx;
}
if (addToNewIDRoles)
{
- if (idroles == null)
- idroles = new List<IDRole>();
+ idroles ??= new List<IDRole>();
idroles.Add(new IDRole(newAuthenticated, newID, newRole));
}
}
base.GetObjectData(serializationInfo, streamingContext);
}
- public IdentityReferenceCollection UnmappedIdentities
- {
- get
- {
- if (_unmappedIdentities == null)
- {
- _unmappedIdentities = new IdentityReferenceCollection();
- }
- return _unmappedIdentities;
- }
- }
+ public IdentityReferenceCollection UnmappedIdentities => _unmappedIdentities ??= new IdentityReferenceCollection();
}
}
{
if (_isAuthenticated == -1)
{
- if (s_authenticatedUserRid is null)
- {
- s_authenticatedUserRid = new SecurityIdentifier(
- IdentifierAuthority.NTAuthority,
- new int[] { Interop.SecurityIdentifier.SECURITY_AUTHENTICATED_USER_RID }
- );
- }
+ s_authenticatedUserRid ??= new SecurityIdentifier(
+ IdentifierAuthority.NTAuthority,
+ new int[] { Interop.SecurityIdentifier.SECURITY_AUTHENTICATED_USER_RID }
+ );
+
// This approach will not work correctly for domain guests (will return false
// instead of true). This is a corner-case that is not very interesting.
_isAuthenticated = CheckNtTokenForSid(s_authenticatedUserRid) ? 1 : 0;
if (_safeTokenHandle.IsInvalid)
return false;
- if (s_domainRid is null)
- {
- s_domainRid = new SecurityIdentifier(
- IdentifierAuthority.NTAuthority,
- new int[] { Interop.SecurityIdentifier.SECURITY_BUILTIN_DOMAIN_RID, (int)WindowsBuiltInRole.Guest }
- );
- }
+ s_domainRid ??= new SecurityIdentifier(
+ IdentifierAuthority.NTAuthority,
+ new int[] { Interop.SecurityIdentifier.SECURITY_BUILTIN_DOMAIN_RID, (int)WindowsBuiltInRole.Guest }
+ );
return CheckNtTokenForSid(s_domainRid);
}
if (_safeTokenHandle.IsInvalid)
return false;
- if (s_localSystemRid is null)
- {
- s_localSystemRid = new SecurityIdentifier(
- IdentifierAuthority.NTAuthority,
- new int[] { Interop.SecurityIdentifier.SECURITY_LOCAL_SYSTEM_RID }
- );
- }
+ s_localSystemRid ??= new SecurityIdentifier(
+ IdentifierAuthority.NTAuthority,
+ new int[] { Interop.SecurityIdentifier.SECURITY_LOCAL_SYSTEM_RID }
+ );
return User == s_localSystemRid;
}
if (_safeTokenHandle.IsInvalid)
return true;
- if (s_anonymousRid is null)
- {
- s_anonymousRid = new SecurityIdentifier(
- IdentifierAuthority.NTAuthority,
- new int[] { Interop.SecurityIdentifier.SECURITY_ANONYMOUS_LOGON_RID }
- );
- }
+ s_anonymousRid ??= new SecurityIdentifier(
+ IdentifierAuthority.NTAuthority,
+ new int[] { Interop.SecurityIdentifier.SECURITY_ANONYMOUS_LOGON_RID }
+ );
return User == s_anonymousRid;
}
if (preserveAttributeExtensions)
{
string value = reader.Value;
- if (attrs == null)
- {
- attrs = new Dictionary<XmlQualifiedName, string>();
- }
+ attrs ??= new Dictionary<XmlQualifiedName, string>();
attrs.Add(new XmlQualifiedName(name, ns), value);
}
}
{
SyndicationCategory category = CreateCategory(inlineCategories);
Atom10FeedFormatter.ReadCategory(reader, category, version, preserveAttributeExtensions: true, preserveElementExtensions: true, maxExtensionSize);
- if (category.Scheme == null)
- {
- category.Scheme = inlineCategories.Scheme;
- }
+ category.Scheme ??= inlineCategories.Scheme;
inlineCategories.Categories.Add(category);
}
else if (!TryParseElement(reader, inlineCategories, version))
_extensions.LoadElementExtensions(buffer);
}
- private static IEnumerable<string> CreateSingleEmptyAccept()
- {
- if (s_singleEmptyAccept == null)
- {
- s_singleEmptyAccept = new List<string>(1) { string.Empty }.AsReadOnly();
- }
-
- return s_singleEmptyAccept;
- }
+ private static IEnumerable<string> CreateSingleEmptyAccept() =>
+ s_singleEmptyAccept ??= new List<string>(1) { string.Empty }.AsReadOnly();
}
}
{
if (item.Links[i].RelationshipType == Atom10Constants.AlternateTag)
{
- if (firstAlternateLink == null)
- {
- firstAlternateLink = item.Links[i];
- }
+ firstAlternateLink ??= item.Links[i];
if (guid == FeedUtils.GetUriString(item.Links[i].Uri))
{
isPermalink = true;
throw new ArgumentException(SR.OuterNameOfElementExtensionEmpty, nameof(outerName));
}
- if (dataContractSerializer == null)
- {
- dataContractSerializer = new DataContractSerializer(dataContractExtension.GetType());
- }
+ dataContractSerializer ??= new DataContractSerializer(dataContractExtension.GetType());
_outerName = outerName;
_outerNamespace = outerNamespace;
_extensionData = dataContractExtension;
throw new ArgumentNullException(nameof(xmlSerializerExtension));
}
- if (serializer == null)
- {
- serializer = new XmlSerializer(xmlSerializerExtension.GetType());
- }
+ serializer ??= new XmlSerializer(xmlSerializerExtension.GetType());
_extensionData = xmlSerializerExtension;
_extensionDataWriter = new ExtensionDataWriter(_extensionData, serializer);
}
throw new ArgumentNullException(nameof(dataContractExtension));
}
- if (dataContractSerializer == null)
- {
- dataContractSerializer = new DataContractSerializer(dataContractExtension.GetType());
- }
+ dataContractSerializer ??= new DataContractSerializer(dataContractExtension.GetType());
base.Add(new SyndicationElementExtension(outerName, outerNamespace, dataContractExtension, dataContractSerializer));
}
throw new ArgumentNullException(nameof(xmlSerializerExtension));
}
- if (serializer == null)
- {
- serializer = new XmlSerializer(xmlSerializerExtension.GetType());
- }
+ serializer ??= new XmlSerializer(xmlSerializerExtension.GetType());
base.Add(new SyndicationElementExtension(xmlSerializerExtension, serializer));
}
Debug.Assert((dcSerializer == null) != (xmlSerializer == null), "exactly one serializer should be supplied");
// normalize the null and empty namespace
- if (extensionNamespace == null)
- {
- extensionNamespace = string.Empty;
- }
+ extensionNamespace ??= string.Empty;
Collection<TExtension> results = new Collection<TExtension>();
for (int i = 0; i < Count; ++i)
{
public TContent ReadContent<TContent>(XmlObjectSerializer dataContractSerializer)
{
- if (dataContractSerializer == null)
- {
- dataContractSerializer = new DataContractSerializer(typeof(TContent));
- }
+ dataContractSerializer ??= new DataContractSerializer(typeof(TContent));
if (Extension != null)
{
return Extension.GetObject<TContent>(dataContractSerializer);
public TContent ReadContent<TContent>(XmlSerializer serializer)
{
- if (serializer == null)
- {
- serializer = new XmlSerializer(typeof(TContent));
- }
+ serializer ??= new XmlSerializer(typeof(TContent));
if (Extension != null)
{
return Extension.GetObject<TContent>(serializer);
/// can be used to write notification of service command calls, such as Start and Stop, to the Application event log. This property is read-only.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- public virtual EventLog EventLog
- {
- get
+ public virtual EventLog EventLog =>
+ _eventLog ??= new EventLog("Application")
{
- if (_eventLog == null)
- {
- _eventLog = new EventLog("Application")
- {
- Source = ServiceName
- };
- }
-
- return _eventLog;
- }
- }
+ Source = ServiceName
+ };
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected IntPtr ServiceHandle
}
// get a handle to SCM with connect access and store it in serviceManagerHandle field.
- if (_serviceManagerHandle == null)
- {
- _serviceManagerHandle = GetDataBaseHandleWithAccess(_machineName, Interop.Advapi32.ServiceControllerOptions.SC_MANAGER_CONNECT);
- }
+ _serviceManagerHandle ??= GetDataBaseHandleWithAccess(_machineName, Interop.Advapi32.ServiceControllerOptions.SC_MANAGER_CONNECT);
}
/// <summary>
public string Name
{
get { return _grammarName; }
- set
- {
-#pragma warning disable 6507
-#pragma warning disable 6526
- if (value == null) { value = string.Empty; }
- _grammarName = value;
-#pragma warning restore 6507
-#pragma warning restore 6526
- }
+ set { _grammarName = value ?? string.Empty; }
}
public string RuleName
{
void IRecognizerInternal.SetDictationContext(Grammar grammar, string precedingText, string subsequentText)
{
- if (precedingText == null) { precedingText = string.Empty; }
- if (subsequentText == null) { subsequentText = string.Empty; }
+ precedingText ??= string.Empty;
+ subsequentText ??= string.Empty;
SPTEXTSELECTIONINFO selectionInfo = new(0, 0, (uint)precedingText.Length, 0);
string textString = precedingText + subsequentText + "\0\0";
}
}
[EditorBrowsable(EditorBrowsableState.Advanced)]
- public IDictionary<string, string> AdditionalInfo
- {
- get
- {
- if (_attributes == null)
- _attributes = new ReadOnlyDictionary<string, string>(new Dictionary<string, string>(0));
- return _attributes;
- }
- }
-
+ public IDictionary<string, string> AdditionalInfo => _attributes ??= new ReadOnlyDictionary<string, string>(new Dictionary<string, string>(0));
#endregion
#region Internal Methods
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();
}
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void PushToArray(bool value)
{
- if (_array == null)
- {
- _array = new int[DefaultInitialArraySize];
- }
+ _array ??= new int[DefaultInitialArraySize];
int index = _currentDepth - AllocationFreeMaxDepth;
}
else
{
- JsonNode? jNode = value as JsonNode;
- if (jNode == null)
- {
- jNode = new JsonValueNotTrimmable<T>(value);
- }
+ JsonNode jNode = value as JsonNode ?? new JsonValueNotTrimmable<T>(value);
// Call the IList.Add() implementation.
Add(jNode);
{
var wrappedValue = new ReferenceEqualsWrapper(value);
- if (_stackForCycleDetection is null)
- {
- _stackForCycleDetection = new Stack<ReferenceEqualsWrapper>();
- }
+ _stackForCycleDetection ??= new Stack<ReferenceEqualsWrapper>();
Debug.Assert(!_stackForCycleDetection.Contains(wrappedValue));
_stackForCycleDetection.Push(wrappedValue);
}
// Priority 3: Attempt to get built-in converter.
- if (converter == null)
- {
- converter = DefaultJsonTypeInfoResolver.GetDefaultConverter(typeToConvert);
- }
+ converter ??= DefaultJsonTypeInfoResolver.GetDefaultConverter(typeToConvert);
// Allow redirection for generic types or the enum converter.
if (converter is JsonConverterFactory factory)
// Check again to append the cache up to the threshold.
if (cacheCount < PropertyNameCountCacheThreshold)
{
- if (frame.PropertyRefCache == null)
- {
- frame.PropertyRefCache = new List<PropertyRef>();
- }
+ frame.PropertyRefCache ??= new List<PropertyRef>();
Debug.Assert(info != null);
// Check again to append the cache up to the threshold.
if (cacheCount < ParameterNameCountCacheThreshold)
{
- if (frame.CtorArgumentState.ParameterRefCache == null)
- {
- frame.CtorArgumentState.ParameterRefCache = new List<ParameterRef>();
- }
+ frame.CtorArgumentState.ParameterRefCache ??= new List<ParameterRef>();
parameterRef = new ParameterRef(key, info!, utf8PropertyName);
frame.CtorArgumentState.ParameterRefCache.Add(parameterRef);
// Task final state: Faulted
case ReceiveCoreByLinkingCleanupReason.SourceCompletion:
- if (_receivedException == null) _receivedException = CreateExceptionForSourceCompletion();
+ _receivedException ??= CreateExceptionForSourceCompletion();
goto case ReceiveCoreByLinkingCleanupReason.SourceProtocolError;
case ReceiveCoreByLinkingCleanupReason.Timer:
- if (_receivedException == null) _receivedException = CreateExceptionForTimeout();
+ _receivedException ??= CreateExceptionForTimeout();
goto case ReceiveCoreByLinkingCleanupReason.SourceProtocolError;
case ReceiveCoreByLinkingCleanupReason.SourceProtocolError:
case ReceiveCoreByLinkingCleanupReason.ErrorDuringCleanup:
if (sendAsyncTask.Status != TaskStatus.RanToCompletion)
{
// Ensure the SendAsyncTaskList is instantiated
- if (_tempSendAsyncTaskList == null) _tempSendAsyncTaskList = new List<Task<bool>>();
+ _tempSendAsyncTaskList ??= new List<Task<bool>>();
// Add the task to the list
_tempSendAsyncTaskList.Add(sendAsyncTask);
catch (Exception e)
{
if (throwOnFirstException) throw;
- if (exceptions == null) exceptions = new List<Exception>(1);
+ exceptions ??= new List<Exception>(1);
exceptions.Add(e);
}
}
// This avoids the cost of updating it once per output item (since each update requires synchronization).
// Even if we're not bounding, we still want to determine whether the item is trusted so that we
// can immediately dump it out once we take the lock if we're the next item.
- IList<TOutput>? itemAsTrustedList = item as TOutput[];
- if (itemAsTrustedList == null) itemAsTrustedList = item as List<TOutput>;
+ IList<TOutput>? itemAsTrustedList = (IList<TOutput>?)(item as TOutput[]) ?? item as List<TOutput>;
if (itemAsTrustedList != null && isBounded)
{
UpdateBoundingCountWithOutputCount(count: itemAsTrustedList.Count);
Debug.Assert(exObj is Exception);
Exception ex = (Exception)exObj;
- if (first == null)
- first = ex;
+ first ??= ex;
// If mismatch found, fail-fast:
OperationCanceledException? ocEx = ex as OperationCanceledException;
internal override void Aborted(InternalEnlistment enlistment, Exception? e)
{
- if (enlistment.Transaction._innerException == null)
- {
- enlistment.Transaction._innerException = e;
- }
+ enlistment.Transaction._innerException ??= e;
// Transition to the ended state
DurableEnlistmentEnded.EnterState(enlistment);
// Transition to the ended state
DurableEnlistmentEnded.EnterState(enlistment);
- if (enlistment.Transaction._innerException == null)
- {
- enlistment.Transaction._innerException = e;
- }
+ enlistment.Transaction._innerException ??= e;
Debug.Assert(enlistment.Transaction.State != null);
// Make the transaction in dobut
// Transition to the ended state
DurableEnlistmentEnded.EnterState(enlistment);
- if (enlistment.Transaction._innerException == null)
- {
- enlistment.Transaction._innerException = e;
- }
+ enlistment.Transaction._innerException ??= e;
Debug.Assert(enlistment.Transaction.State != null);
// Start the transaction aborting
// Transition to the ended state
DurableEnlistmentEnded.EnterState(enlistment);
- if (enlistment.Transaction._innerException == null)
- {
- enlistment.Transaction._innerException = e;
- }
+ enlistment.Transaction._innerException ??= e;
Debug.Assert(enlistment.Transaction.State != null);
// Tell the transaction that the enlistment is InDoubt. Note that
[AllowNull]
internal static ContextData TLSCurrentData
{
- get
- {
- ContextData? data = t_staticData;
- if (data == null)
- {
- data = new ContextData(false);
- t_staticData = data;
- }
-
- return data;
- }
+ get => t_staticData ??= new ContextData(false);
set
{
if (value == null && t_staticData != null)
private static DefaultSettingsSection? s_defaultSettings;
- private static DefaultSettingsSection DefaultSettings
- {
- get
- {
- if (s_defaultSettings == null)
- {
- s_defaultSettings = DefaultSettingsSection.GetSection();
- }
-
- return s_defaultSettings;
- }
- }
+ private static DefaultSettingsSection DefaultSettings => s_defaultSettings ??= DefaultSettingsSection.GetSection();
private static MachineSettingsSection? s_machineSettings;
- private static MachineSettingsSection MachineSettings
- {
- get
- {
- if (s_machineSettings == null)
- {
- s_machineSettings = MachineSettingsSection.GetSection();
- }
-
- return s_machineSettings;
- }
- }
+ private static MachineSettingsSection MachineSettings => s_machineSettings ??= MachineSettingsSection.GetSection();
private static bool s_defaultTimeoutValidated;
private static TimeSpan s_defaultTimeout;
// Something must have gone wrong trying to clean up a bad scope
// stack previously.
// Make a best effort to abort the active transaction.
- Transaction? rollbackTransaction = _committableTransaction;
- if (rollbackTransaction == null)
- {
- rollbackTransaction = _dependentTransaction;
- }
+ Transaction? rollbackTransaction = (Transaction?)_committableTransaction ?? _dependentTransaction;
Debug.Assert(rollbackTransaction != null);
rollbackTransaction.Rollback();
// Note: Rollback is not called on expected current because someone could conceiveably
// dispose expectedCurrent out from under the transaction scope.
//
- Transaction? rollbackTransaction = _committableTransaction;
- if (rollbackTransaction == null)
- {
- rollbackTransaction = _dependentTransaction;
- }
+ Transaction? rollbackTransaction = (Transaction?)_committableTransaction ?? _dependentTransaction;
Debug.Assert(rollbackTransaction != null);
rollbackTransaction.Rollback();
}
private void SaveTLSContextData()
{
- if (_savedTLSContextData == null)
- {
- _savedTLSContextData = new ContextData(false);
- }
+ _savedTLSContextData ??= new ContextData(false);
_savedTLSContextData.CurrentScope = ContextData.TLSCurrentData.CurrentScope;
_savedTLSContextData.CurrentTransaction = ContextData.TLSCurrentData.CurrentTransaction;
// Start the process for abort. From the active state we can transition directly
// to the aborted state.
- if (tx._innerException == null)
- {
- tx._innerException = e;
- }
+ tx._innerException ??= e;
TransactionStateAborted.EnterState(tx);
}
// Start the process for abort. From the active state we can transition directly
// to the aborted state.
- if (tx._innerException == null)
- {
- tx._innerException = e;
- }
+ tx._innerException ??= e;
Debug.Assert(tx._promoter != null);
((ISimpleTransactionSuperior)tx._promoter).Rollback();
internal override void ChangeStateTransactionAborted(InternalTransaction tx, Exception? e)
{
- if (tx._innerException == null)
- {
- tx._innerException = e;
- }
+ tx._innerException ??= e;
TransactionStateAborted.EnterState(tx);
}
internal override void ChangeStateTransactionAborted(InternalTransaction tx, Exception? e)
{
- if (tx._innerException == null)
- {
- tx._innerException = e;
- }
+ tx._innerException ??= e;
TransactionStateAborted.EnterState(tx);
}
internal override void ChangeStateTransactionAborted(InternalTransaction tx, Exception? e)
{
- if (tx._innerException == null)
- {
- tx._innerException = e;
- }
+ tx._innerException ??= e;
// The durable enlistment must have aborted. Go to the aborted state.
TransactionStateAborted.EnterState(tx);
internal override void ChangeStateTransactionAborted(InternalTransaction tx, Exception? e)
{
- if (tx._innerException == null)
- {
- tx._innerException = e;
- }
+ tx._innerException ??= e;
// The durable enlistment must have aborted. Go to the aborted state.
TransactionStateAborted.EnterState(tx);
Debug.Assert(tx.PromotedTransaction != null, "Promoted state not valid for transaction.");
// Forward this on to the promoted transaction.
- if (tx._innerException == null)
- {
- tx._innerException = e;
- }
+ tx._innerException ??= e;
// Don't hold locks while calling into the promoted tx
Monitor.Exit(tx);
// LTM gives up the ability to control Tx timeout when it promotes.
try
{
- if (tx._innerException == null)
- {
- tx._innerException = new TimeoutException(SR.TraceTransactionTimeout);
- }
+ tx._innerException ??= new TimeoutException(SR.TraceTransactionTimeout);
Debug.Assert(tx.PromotedTransaction != null);
DistributedTransaction.Rollback();
// In this state we don't want a transaction exception from BeginCommit to randomly
// bubble up to the application or go unhandled. So catch the exception and if the
// inner exception for the transaction has not already been set then set it.
- if (tx._innerException == null)
- {
- tx._innerException = e;
- }
+ tx._innerException ??= e;
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
internal override void ChangeStateTransactionAborted(InternalTransaction tx, Exception? e)
{
- if (tx._innerException == null)
- {
- tx._innerException = e;
- }
+ tx._innerException ??= e;
// This change state event at this point would be caused by one of the enlistments
// aborting. Really change to P0Aborting
internal override void ChangeStateTransactionAborted(InternalTransaction tx, Exception? e)
{
- if (tx._innerException == null)
- {
- tx._innerException = e;
- }
+ tx._innerException ??= e;
// This change state event at this point would be caused by one of the enlistments
// aborting. Really change to P0Aborting
internal override void ChangeStateTransactionAborted(InternalTransaction tx, Exception? e)
{
- if (tx._innerException == null)
- {
- tx._innerException = e;
- }
+ tx._innerException ??= e;
// This change state event at this point would be caused by one of the enlistments
// aborting. Really change to P1Aborting
// Pass the Rollback through the promotable single phase enlistment to be
// certain it is notified.
- if (tx._innerException == null)
- {
- tx._innerException = e;
- }
+ tx._innerException ??= e;
TransactionStateDelegatedAborting.EnterState(tx);
}
// transaction promoter will get notified of the abort.
Debug.Assert(tx._durableEnlistment != null, "PromotedNonMSDTC state is not valid for transaction");
- if (tx._innerException == null)
- {
- tx._innerException = e;
- }
+ tx._innerException ??= e;
TransactionStateAborted.EnterState(tx);
}
// Just transition to Aborted. The PSPE will be told to rollback thru the durableEnlistment.
// This is also overridden in TransactionStatePromotedNonMSDTCSinglePhaseCommit
// that does something slightly differently.
- if (tx._innerException == null)
- {
- tx._innerException = e;
- }
+ tx._innerException ??= e;
TransactionStateAborted.EnterState(tx);
}
internal override void ChangeStateTransactionAborted(InternalTransaction tx, Exception? e)
{
- if (tx._innerException == null)
- {
- tx._innerException = e;
- }
+ tx._innerException ??= e;
// The durable enlistment must have aborted. Go to the aborted state.
TransactionStatePromotedNonMSDTCAborted.EnterState(tx);
// Pass the Rollback through the promotable single phase enlistment to be
// certain it is notified.
- if (tx._innerException == null)
- {
- tx._innerException = e;
- }
+ tx._innerException ??= e;
Debug.Assert(tx.PromotedTransaction != null);
DistributedTransaction.Rollback();
{
VolatileEnlistmentEnded.EnterState(enlistment);
- if (enlistment.Transaction._innerException == null)
- {
- enlistment.Transaction._innerException = e;
- }
+ enlistment.Transaction._innerException ??= e;
Debug.Assert(enlistment.Transaction.State != null);
enlistment.Transaction.State.InDoubtFromEnlistment(enlistment.Transaction);
// to the string builder when special characters are detected.
if (CharRequiresJavaScriptEncoding(c))
{
- if (b == null)
- {
- b = new StringBuilder(value.Length + 5);
- }
+ b ??= new StringBuilder(value.Length + 5);
if (count > 0)
{
else
*/
{
- if (_byteBuffer == null)
- {
- _byteBuffer = new byte[_bufferSize];
- }
+ _byteBuffer ??= new byte[_bufferSize];
_byteBuffer[_numBytes++] = b;
}
get => _soundLocation;
set
{
- if (value == null)
- {
- value = string.Empty;
- }
+ value ??= string.Empty;
if (_soundLocation.Equals(value))
{
object? target = _target;
- if (data is null)
- data = CreateDelegateData();
+ data ??= CreateDelegateData();
// replace all Type.Missing with default values defined on parameters of the delegate if any
MethodInfo? invoke = GetType().GetMethod("Invoke");
return false;
if ((obj is Type))
return true;
- if (corlib == null)
- corlib = typeof(int).Assembly;
+
+ corlib ??= typeof(int).Assembly;
return obj.GetType().Assembly != corlib;
}
{
AttributeUsageAttribute? usageAttribute;
/* Usage a thread-local cache to speed this up, since it is called a lot from GetCustomAttributes () */
- if (usage_cache == null)
- usage_cache = new Dictionary<Type, AttributeUsageAttribute>();
+ usage_cache ??= new Dictionary<Type, AttributeUsageAttribute>();
if (usage_cache.TryGetValue(attributeType, out usageAttribute))
return usageAttribute;
usageAttribute = RetrieveAttributeUsageNoCache(attributeType);
private DynamicMethod(string name, MethodAttributes attributes, CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes, Type? owner, Module? m, bool skipVisibility, bool anonHosted, bool typeOwner)
{
ArgumentNullException.ThrowIfNull(name);
- if (returnType == null)
- returnType = typeof(void);
+ returnType ??= typeof(void);
if (typeOwner)
ArgumentNullException.ThrowIfNull(owner);
if (!anonHosted)
throw new ArgumentException("Owner can't be an array or an interface.");
}
- if (m == null)
- m = AnonHostModuleHolder.AnonHostModule;
+ m ??= AnonHostModuleHolder.AnonHostModule;
this.name = name;
this.attributes = attributes | MethodAttributes.Static;
return (object[])Array.CreateInstance(attributeType.IsValueType || attributeType.ContainsGenericParameters ? typeof(object) : attributeType, 0);
}
- public DynamicILInfo GetDynamicILInfo()
- {
- if (il_info == null)
- il_info = new DynamicILInfo(this);
- return il_info;
- }
+ public DynamicILInfo GetDynamicILInfo() => il_info ??= new DynamicILInfo(this);
public ILGenerator GetILGenerator()
{
/*
public override object Invoke (object obj, object[] parameters) {
CreateDynMethod ();
- if (method == null)
- method = new RuntimeMethodInfo (mhandle);
+ method ??= new RuntimeMethodInfo (mhandle);
return method.Invoke (obj, parameters);
}
*/
public virtual Label DefineLabel()
{
if (labels == null)
+ {
labels = new LabelData[defaultLabelsSize];
+ }
else if (num_labels >= labels.Length)
{
LabelData[] t = new LabelData[labels.Length * 2];
labels[label.m_label].maxStack = cur_stack;
if (fixups == null)
+ {
fixups = new LabelFixup[defaultFixupSize];
+ }
else if (num_fixups >= fixups.Length)
{
LabelFixup[] newf = new LabelFixup[fixups.Length * 2];
emit_int(count);
if (fixups == null)
+ {
fixups = new LabelFixup[defaultFixupSize + count];
+ }
else if (num_fixups + count >= fixups.Length)
{
LabelFixup[] newf = new LabelFixup[count + fixups.Length * 2];
throw new ArgumentOutOfRangeException(nameof(position));
ParameterBuilder pb = new ParameterBuilder(this, position, attributes, strParamName);
- if (pinfo == null)
- pinfo = new ParameterBuilder[parameters.Length + 1];
+ pinfo ??= new ParameterBuilder[parameters.Length + 1];
pinfo[position] = pb;
return pb;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern object GetRegisteredToken(int token);
- internal ITokenGenerator GetTokenGenerator()
- {
- if (token_gen == null)
- token_gen = new ModuleBuilderTokenGenerator(this);
- return token_gen;
- }
+ internal ITokenGenerator GetTokenGenerator() => token_gen ??= new ModuleBuilderTokenGenerator(this);
// Called from the runtime to return the corresponding finished reflection object
internal static object RuntimeResolve(object obj)
internal void CreateGlobalType()
{
- if (global_type == null)
- global_type = new TypeBuilder(this, 0, 1);
+ global_type ??= new TypeBuilder(this, 0, 1);
}
public override Assembly Assembly
if (mod != null && !(mod is ModuleBuilder))
throw new ArgumentException("ModuleBuilder is expected");
- if (returnType == null)
- returnType = typeof(void);
+ returnType ??= typeof(void);
if (returnType.IsUserType)
throw new NotSupportedException("User defined subclasses of System.Type are not yet supported.");
!(((attributes & MethodAttributes.Static) != 0)))
throw new ArgumentException("Interface method must be abstract and virtual.");
- if (returnType == null)
- returnType = typeof(void);
+ returnType ??= typeof(void);
MethodBuilder res = new MethodBuilder(this, name, attributes,
callingConvention, returnType,
returnTypeRequiredCustomModifiers,
internal override MethodInfo GetMethod(MethodInfo fromNoninstanciated)
{
- if (methods == null)
- methods = new Dictionary<MethodInfo, MethodInfo>();
- if (!methods.ContainsKey(fromNoninstanciated))
- methods[fromNoninstanciated] = new MethodOnTypeBuilderInst(this, fromNoninstanciated);
- return methods[fromNoninstanciated]!;
+ methods ??= new Dictionary<MethodInfo, MethodInfo>();
+ if (!methods.TryGetValue(fromNoninstanciated, out MethodInfo? mi))
+ {
+ methods[fromNoninstanciated] = mi = new MethodOnTypeBuilderInst(this, fromNoninstanciated);
+ }
+ return mi;
}
internal override ConstructorInfo GetConstructor(ConstructorInfo fromNoninstanciated)
{
- if (ctors == null)
- ctors = new Dictionary<ConstructorInfo, ConstructorInfo>();
- if (!ctors.ContainsKey(fromNoninstanciated))
- ctors[fromNoninstanciated] = new ConstructorOnTypeBuilderInst(this, fromNoninstanciated);
- return ctors[fromNoninstanciated]!;
+ ctors ??= new Dictionary<ConstructorInfo, ConstructorInfo>();
+ if (!ctors.TryGetValue(fromNoninstanciated, out ConstructorInfo? ci))
+ {
+ ctors[fromNoninstanciated] = ci = new ConstructorOnTypeBuilderInst(this, fromNoninstanciated);
+ }
+ return ci;
}
internal override FieldInfo GetField(FieldInfo fromNoninstanciated)
{
- if (fields == null)
- fields = new Dictionary<FieldInfo, FieldInfo>();
- if (!fields.ContainsKey(fromNoninstanciated))
- fields[fromNoninstanciated] = new FieldOnTypeBuilderInst(this, fromNoninstanciated);
- return fields[fromNoninstanciated]!;
+ fields ??= new Dictionary<FieldInfo, FieldInfo>();
+ if (!fields.TryGetValue(fromNoninstanciated, out FieldInfo? fi))
+ {
+ fields[fromNoninstanciated] = fi = new FieldOnTypeBuilderInst(this, fromNoninstanciated);
+ }
+ return fi;
}
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)]
{
MonoEventInfo info = GetEventInfo(this);
- MethodInfo method = info.add_method;
- if (method == null)
- method = info.remove_method;
- if (method == null)
- method = info.raise_method;
+ MethodInfo method = info.add_method ?? info.remove_method ?? info.raise_method;
return RuntimeType.FilterPreCalculate(method != null && method.IsPublic, GetDeclaringTypeInternal() != ReflectedType, method != null && method.IsStatic);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern Type ResolveType();
- public override Type FieldType
- {
- get
- {
- if (type == null)
- type = ResolveType();
- return type;
- }
- }
+ public override Type FieldType => type ??= ResolveType();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern Type GetParentType(bool declaring);
}
if (IsLiteral)
throw new FieldAccessException("Cannot set a constant field");
- if (binder == null)
- binder = Type.DefaultBinder;
+
+ binder ??= Type.DefaultBinder;
CheckGeneric();
if (val != null)
{
}
}
- 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) 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);
- if (binder == null)
- binder = DefaultBinder;
+ binder ??= DefaultBinder;
return binder.SelectProperty(bindingAttr, candidates.ToArray(), returnType, types, modifiers);
}
StringComparison nameComparison = ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
foreach (RuntimeType t in GetInterfaces())
{
-
if (!string.Equals(t.Name, name, nameComparison))
{
continue;
}
- if (list == null)
- list = new List<RuntimeType>(2);
+ list ??= new List<RuntimeType>(2);
list.Add(t);
}
Type[]? types = null;
var this_type = this;
GetGenericArgumentsInternal(new QCallTypeHandle(ref this_type), ObjectHandleOnStack.Create(ref types), false);
- if (types == null)
- types = Type.EmptyTypes;
- return types;
+ return types ?? Type.EmptyTypes;
}
[RequiresUnreferencedCode("If some of the generic arguments are annotated (either with DynamicallyAccessedMembersAttribute, or generic constraints), trimming can't validate that the requirements of those annotations are met.")]
int argCnt = args.Length;
// Without a binder we need to do use the default binder...
- if (binder == 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
pos++;
isbyref = true;
isptr = false;
- if (res.Modifiers == null)
- res.Modifiers = new List<int>();
+ res.Modifiers ??= new List<int>();
res.Modifiers.Add(0);
break;
case '*':
if (isbyref)
return null;
pos++;
- if (res.Modifiers == null)
- res.Modifiers = new List<int>();
+ res.Modifiers ??= new List<int>();
res.Modifiers.Add(-1);
isptr = true;
break;
if (bounded && rank > 1)
return null;
/* n.b. bounded needs both modifiers: -2 == bounded, 1 == rank 1 array */
- if (res.Modifiers == null)
- res.Modifiers = new List<int>();
+ res.Modifiers ??= new List<int>();
if (bounded)
res.Modifiers.Add(-2);
res.Modifiers.Add(rank);
return sb;
}
- internal string DisplayFullName
- {
- get
- {
- if (display_fullname == null)
- display_fullname = GetDisplayFullName(DisplayNameFormat.Default);
- return display_fullname;
- }
- }
+ internal string DisplayFullName => display_fullname ??= GetDisplayFullName(DisplayNameFormat.Default);
internal static TypeSpec Parse(string typeName)
{
}
else
{
- if (nested == null)
- nested = new List<ITypeIdentifier>();
+ nested ??= new List<ITypeIdentifier>();
nested.Add(ParsedTypeIdentifier(type_name));
}
}
- private void AddModifier(IModifierSpec md)
- {
- if (modifier_spec == null)
- modifier_spec = new List<IModifierSpec>();
- modifier_spec.Add(md);
- }
+ private void AddModifier(IModifierSpec md) => modifier_spec ??= new List<IModifierSpec>();
private static void SkipSpace(string name, ref int pos)
{