diff --git a/src/libraries/System.Text.Json/src/System/ReflectionExtensions.cs b/src/libraries/System.Text.Json/src/System/ReflectionExtensions.cs index 7d86bb22a98888..a8acfb552f2f99 100644 --- a/src/libraries/System.Text.Json/src/System/ReflectionExtensions.cs +++ b/src/libraries/System.Text.Json/src/System/ReflectionExtensions.cs @@ -45,7 +45,7 @@ public static bool IsInSubtypeRelationshipWith(this Type type, Type other) => type.IsAssignableFromInternal(other) || other.IsAssignableFromInternal(type); private static bool HasJsonConstructorAttribute(ConstructorInfo constructorInfo) - => constructorInfo.GetCustomAttribute() != null; + => constructorInfo.GetCustomAttribute() is not null; public static bool HasRequiredMemberAttribute(this MemberInfo memberInfo) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/BitStack.cs b/src/libraries/System.Text.Json/src/System/Text/Json/BitStack.cs index e96622e16952d6..29966557351c7b 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/BitStack.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/BitStack.cs @@ -141,7 +141,7 @@ public bool Pop() private readonly bool PeekInArray() { int index = _currentDepth - AllocationFreeMaxDepth - 1; - Debug.Assert(_array != null); + Debug.Assert(_array is not null); Debug.Assert(index >= 0, $"Get - Negative - index: {index}, arrayLength: {_array.Length}"); int elementIndex = Div32Rem(index, out int extraBits); @@ -161,7 +161,7 @@ public readonly bool Peek() private void DoubleArray(int minSize) { - Debug.Assert(_array != null); + Debug.Assert(_array is not null); Debug.Assert(_array.Length < int.MaxValue / 2, $"Array too large - arrayLength: {_array.Length}"); Debug.Assert(minSize >= 0 && minSize >= _array.Length); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.DbRow.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.DbRow.cs index 5b1451521cd125..9fdd89ce3309b1 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.DbRow.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.DbRow.cs @@ -54,7 +54,7 @@ internal readonly struct DbRow internal DbRow(JsonTokenType jsonTokenType, int location, int sizeOrLength) { - Debug.Assert(jsonTokenType > JsonTokenType.None && jsonTokenType <= JsonTokenType.Null); + Debug.Assert(jsonTokenType is > JsonTokenType.None and <= JsonTokenType.Null); Debug.Assert((byte)jsonTokenType < 1 << 4); Debug.Assert(location >= 0); Debug.Assert(sizeOrLength >= UnknownSize); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.MetadataDb.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.MetadataDb.cs index 87ee6ca78d751c..1a4ef8f52c78be 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.MetadataDb.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.MetadataDb.cs @@ -130,7 +130,7 @@ internal static MetadataDb CreateRented(int payloadLength, bool convertToAlloc) // were more frequent anyways. const int OneMegabyte = 1024 * 1024; - if (initialSize > OneMegabyte && initialSize <= 4 * OneMegabyte) + if (initialSize is > OneMegabyte and <= 4 * OneMegabyte) { initialSize = OneMegabyte; } @@ -151,7 +151,7 @@ internal static MetadataDb CreateLocked(int payloadLength) public void Dispose() { byte[]? data = Interlocked.Exchange(ref _data, null!); - if (data == null) + if (data is null) { return; } @@ -175,7 +175,7 @@ internal void CompleteAllocations() { if (_convertToAlloc) { - Debug.Assert(_data != null); + Debug.Assert(_data is not null); byte[] returnBuf = _data; _data = _data.AsSpan(0, Length).ToArray(); _isLocked = true; @@ -217,7 +217,7 @@ internal void Append(JsonTokenType tokenType, int startLocation, int length) { // StartArray or StartObject should have length -1, otherwise the length should not be -1. Debug.Assert( - (tokenType == JsonTokenType.StartArray || tokenType == JsonTokenType.StartObject) == + (tokenType is JsonTokenType.StartArray or JsonTokenType.StartObject) == (length == DbRow.UnknownSize)); if (Length >= _data.Length - DbRow.Size) @@ -275,7 +275,7 @@ internal void SetLength(int index, int length) internal void SetNumberOfRows(int index, int numberOfRows) { AssertValidIndex(index); - Debug.Assert(numberOfRows >= 1 && numberOfRows <= 0x0FFFFFFF); + Debug.Assert(numberOfRows is >= 1 and <= 0x0FFFFFFF); Span dataPos = _data.AsSpan(index + NumberOfRowsOffset); int current = MemoryMarshal.Read(dataPos); @@ -299,7 +299,7 @@ internal void SetHasComplexChildren(int index) internal int FindIndexOfFirstUnsetSizeOrLength(JsonTokenType lookupType) { - Debug.Assert(lookupType == JsonTokenType.StartObject || lookupType == JsonTokenType.StartArray); + Debug.Assert(lookupType is JsonTokenType.StartObject or JsonTokenType.StartArray); return FindOpenElement(lookupType); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.Parse.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.Parse.cs index 04e0ac0ccb6559..71e356c2936bec 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.Parse.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.Parse.cs @@ -124,7 +124,7 @@ public static JsonDocument Parse(Stream utf8Json, JsonDocumentOptions options = ArgumentNullException.ThrowIfNull(utf8Json); ArraySegment drained = ReadToEnd(utf8Json); - Debug.Assert(drained.Array != null); + Debug.Assert(drained.Array is not null); try { return Parse( @@ -154,10 +154,10 @@ internal static JsonDocument ParseRented(PooledByteBufferWriter utf8Json, JsonDo internal static JsonDocument ParseValue(Stream utf8Json, JsonDocumentOptions options) { - Debug.Assert(utf8Json != null); + Debug.Assert(utf8Json is not null); ArraySegment drained = ReadToEnd(utf8Json); - Debug.Assert(drained.Array != null); + Debug.Assert(drained.Array is not null); byte[] owned = new byte[drained.Count]; Buffer.BlockCopy(drained.Array, 0, owned, 0, drained.Count); @@ -185,7 +185,7 @@ internal static JsonDocument ParseValue(ReadOnlySpan utf8Json, JsonDocumen internal static JsonDocument ParseValue(string json, JsonDocumentOptions options) { - Debug.Assert(json != null); + Debug.Assert(json is not null); return ParseValue(json.AsSpan(), options); } @@ -221,7 +221,7 @@ private static async Task ParseAsyncCore( CancellationToken cancellationToken = default) { ArraySegment drained = await ReadToEndAsync(utf8Json, cancellationToken).ConfigureAwait(false); - Debug.Assert(drained.Array != null); + Debug.Assert(drained.Array is not null); try { return Parse( @@ -245,7 +245,7 @@ internal static async Task ParseAsyncCoreUnrented( CancellationToken cancellationToken = default) { ArraySegment drained = await ReadToEndAsync(utf8Json, cancellationToken).ConfigureAwait(false); - Debug.Assert(drained.Array != null); + Debug.Assert(drained.Array is not null); byte[] owned = new byte[drained.Count]; Buffer.BlockCopy(drained.Array, 0, owned, 0, drained.Count); @@ -439,7 +439,7 @@ internal static JsonDocument ParseValue(ref Utf8JsonReader reader, bool allowDup bool ret = TryParseValue(ref reader, out JsonDocument? document, shouldThrow: true, useArrayPools: true, allowDuplicateProperties); Debug.Assert(ret, "TryParseValue returned false with shouldThrow: true."); - Debug.Assert(document != null, "null document returned with shouldThrow: true."); + Debug.Assert(document is not null, "null document returned with shouldThrow: true."); return document; } @@ -758,14 +758,12 @@ private static JsonDocument ParseUnrented( { // These tokens should already have been processed. Debug.Assert( - tokenType != JsonTokenType.Null && - tokenType != JsonTokenType.False && - tokenType != JsonTokenType.True); + tokenType is not (JsonTokenType.Null or JsonTokenType.False or JsonTokenType.True)); ReadOnlySpan utf8JsonSpan = utf8Json.Span; MetadataDb database; - if (tokenType == JsonTokenType.String || tokenType == JsonTokenType.Number) + if (tokenType is JsonTokenType.String or JsonTokenType.Number) { // For primitive types, we can avoid renting MetadataDb and creating StackRowStack. database = MetadataDb.CreateLocked(utf8Json.Length); @@ -859,7 +857,7 @@ private static ArraySegment ReadToEnd(Stream stream) } catch { - if (rented != null) + if (rented is not null) { // Holds document content, clear it before returning it. rented.AsSpan(0, written).Clear(); @@ -941,7 +939,7 @@ private static async } catch { - if (rented != null) + if (rented is not null) { // Holds document content, clear it before returning it. rented.AsSpan(0, written).Clear(); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.StackRowStack.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.StackRowStack.cs index 83b7b634913d27..9efc8a5d728f93 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.StackRowStack.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.StackRowStack.cs @@ -30,7 +30,7 @@ public void Dispose() _rentedBuffer = null!; _topOfStack = 0; - if (toReturn != null) + if (toReturn is not null) { // The data in this rented buffer only conveys the positions and // lengths of tokens in a document, but no content; so it does not @@ -52,7 +52,7 @@ internal void Push(StackRow row) internal StackRow Pop() { - Debug.Assert(_rentedBuffer != null); + Debug.Assert(_rentedBuffer is not null); Debug.Assert(_topOfStack <= _rentedBuffer!.Length - StackRow.Size); StackRow row = MemoryMarshal.Read(_rentedBuffer.AsSpan(_topOfStack)); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.TryGetProperty.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.TryGetProperty.cs index 6445b14be512cb..2d47cf5855cd2c 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.TryGetProperty.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.TryGetProperty.cs @@ -201,7 +201,7 @@ private unsafe bool TryGetNamedPropertyValue( } finally { - if (rented != null) + if (rented is not null) { rented.AsSpan(0, written).Clear(); ArrayPool.Shared.Return(rented); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.cs index 185df75c8bd5aa..99f0bca5fdce21 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.cs @@ -45,10 +45,10 @@ private JsonDocument( // Both rented values better be null if we're not disposable. Debug.Assert(isDisposable || - (extraRentedArrayPoolBytes == null && extraPooledByteBufferWriter == null)); + (extraRentedArrayPoolBytes is null && extraPooledByteBufferWriter is null)); // Both rented values can't be specified. - Debug.Assert(extraRentedArrayPoolBytes == null || extraPooledByteBufferWriter == null); + Debug.Assert(extraRentedArrayPoolBytes is null || extraPooledByteBufferWriter is null); _utf8Json = utf8Json; _parsedData = parsedData; @@ -69,11 +69,11 @@ public void Dispose() _parsedData.Dispose(); _utf8Json = ReadOnlyMemory.Empty; - if (_extraRentedArrayPoolBytes != null) + if (_extraRentedArrayPoolBytes is not null) { byte[]? extraRentedBytes = Interlocked.Exchange(ref _extraRentedArrayPoolBytes, null); - if (extraRentedBytes != null) + if (extraRentedBytes is not null) { // When "extra rented bytes exist" it contains the document, // and thus needs to be cleared before being returned. @@ -81,7 +81,7 @@ public void Dispose() ArrayPool.Shared.Return(extraRentedBytes); } } - else if (_extraPooledByteBufferWriter != null) + else if (_extraPooledByteBufferWriter is not null) { PooledByteBufferWriter? extraBufferWriter = Interlocked.Exchange(ref _extraPooledByteBufferWriter, null); extraBufferWriter?.Dispose(); @@ -326,7 +326,7 @@ internal unsafe bool TextEquals(int index, ReadOnlySpan otherText, bool is result = TextEquals(index, otherUtf8Text.Slice(0, written), isPropertyName, shouldUnescape: true); } - if (otherUtf8TextArray != null) + if (otherUtf8TextArray is not null) { otherUtf8Text.Slice(0, written).Clear(); ArrayPool.Shared.Return(otherUtf8TextArray); @@ -832,7 +832,7 @@ private ReadOnlySpan UnescapeString(in DbRow row, out ArraySegment r private static void ClearAndReturn(ArraySegment rented) { - if (rented.Array != null) + if (rented.Array is not null) { rented.AsSpan().Clear(); ArrayPool.Shared.Return(rented.Array); @@ -998,7 +998,7 @@ private static void Parse( } else { - Debug.Assert(tokenType >= JsonTokenType.String && tokenType <= JsonTokenType.Null); + Debug.Assert(tokenType is >= JsonTokenType.String and <= JsonTokenType.Null); numberOfRowsForValues++; numberOfRowsForMembers++; diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonElement.Parse.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonElement.Parse.cs index 522832ea932e0c..9549eee20e27e4 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonElement.Parse.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonElement.Parse.cs @@ -49,7 +49,7 @@ public static JsonElement ParseValue(ref Utf8JsonReader reader) bool ret = JsonDocument.TryParseValue(ref reader, out JsonDocument? document, shouldThrow: true, useArrayPools: false); Debug.Assert(ret, "TryParseValue returned false with shouldThrow: true."); - Debug.Assert(document != null, "null document returned with shouldThrow: true."); + Debug.Assert(document is not null, "null document returned with shouldThrow: true."); return document.RootElement; } @@ -63,7 +63,7 @@ internal static JsonElement ParseValue(ref Utf8JsonReader reader, bool allowDupl allowDuplicateProperties: allowDuplicateProperties); Debug.Assert(ret, "TryParseValue returned false with shouldThrow: true."); - Debug.Assert(document != null, "null document returned with shouldThrow: true."); + Debug.Assert(document is not null, "null document returned with shouldThrow: true."); return document.RootElement; } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonElement.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonElement.cs index 21047a98d7f6a9..c8f12f307cddf0 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonElement.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonElement.cs @@ -1442,7 +1442,7 @@ public bool ValueEquals(string? text) if (TokenType == JsonTokenType.Null) { - return text == null; + return text is null; } return TextEqualsHelper(text.AsSpan(), isPropertyName: false); @@ -1661,7 +1661,7 @@ public override string ToString() case JsonTokenType.StartObject: { // null parent should have hit the None case - Debug.Assert(_parent != null); + Debug.Assert(_parent is not null); return _parent.GetRawValueAsString(_idx); } case JsonTokenType.String: @@ -1704,7 +1704,7 @@ public JsonElement Clone() private void CheckValidInstance() { - if (_parent == null) + if (_parent is null) { throw new InvalidOperationException(); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/JsonEncodedText.cs b/src/libraries/System.Text.Json/src/System/Text/Json/JsonEncodedText.cs index cc2e05ac1291b1..234cd11b327331 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/JsonEncodedText.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/JsonEncodedText.cs @@ -31,7 +31,7 @@ namespace System.Text.Json private JsonEncodedText(byte[] utf8Value) { - Debug.Assert(utf8Value != null); + Debug.Assert(utf8Value is not null); _value = JsonReaderHelper.GetTextFromUtf8(utf8Value); _utf8Value = utf8Value; @@ -143,9 +143,9 @@ private static JsonEncodedText EncodeHelper(ReadOnlySpan utf8Value, JavaSc /// public bool Equals(JsonEncodedText other) { - if (_value == null) + if (_value is null) { - return other._value == null; + return other._value is null; } else { @@ -187,6 +187,6 @@ public override string ToString() /// Returns 0 on a default instance of . /// public override int GetHashCode() - => _value == null ? 0 : _value.GetHashCode(); + => _value is null ? 0 : _value.GetHashCode(); } } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/JsonHelpers.Escaping.cs b/src/libraries/System.Text.Json/src/System/Text/Json/JsonHelpers.Escaping.cs index c719c1f0b53d75..4ea3e2be046da2 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/JsonHelpers.Escaping.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/JsonHelpers.Escaping.cs @@ -45,7 +45,7 @@ public static unsafe byte[] EscapeValue( byte[] escapedString = escapedValue.Slice(0, written).ToArray(); - if (valueArray != null) + if (valueArray is not null) { ArrayPool.Shared.Return(valueArray); } @@ -73,7 +73,7 @@ private static unsafe byte[] GetEscapedPropertyNameSection( byte[] propertySection = GetPropertyNameSection(escapedValue.Slice(0, written)); - if (valueArray != null) + if (valueArray is not null) { ArrayPool.Shared.Return(valueArray); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/JsonHelpers.cs b/src/libraries/System.Text.Json/src/System/Text/Json/JsonHelpers.cs index 15743c819e716a..2a3db10916bb94 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/JsonHelpers.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/JsonHelpers.cs @@ -212,7 +212,7 @@ public static unsafe bool TryLookupUtf8Key( bool success = spanLookup.TryGetValue(decodedKey, out result); - if (rentedBuffer != null) + if (rentedBuffer is not null) { decodedKey.Clear(); ArrayPool.Shared.Return(rentedBuffer); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonArray.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonArray.cs index 3c3bdbf682a434..83115660323805 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonArray.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonArray.cs @@ -242,7 +242,7 @@ internal override unsafe void GetPath(ref ValueStringBuilder path, JsonNode? chi { Parent?.GetPath(ref path, this); - if (child != null) + if (child is not null) { int index = List.IndexOf(child); Debug.Assert(index >= 0); @@ -380,7 +380,7 @@ public string Display { get { - if (Value == null) + if (Value is null) { return $"null"; } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonNode.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonNode.cs index 76d1fd906f6662..d9747f1e019e01 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonNode.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonNode.cs @@ -34,7 +34,7 @@ public JsonNodeOptions? Options { get { - if (!_options.HasValue && Parent != null) + if (!_options.HasValue && Parent is not null) { // Remember the parent options; if node is re-parented later we still want to keep the // original options since they may have affected the way the node was created as is the case @@ -137,7 +137,7 @@ internal set /// The JSON Path value. public unsafe string GetPath() { - if (Parent == null) + if (Parent is null) { return "$"; } @@ -161,12 +161,12 @@ public JsonNode Root get { JsonNode? parent = Parent; - if (parent == null) + if (parent is null) { return this; } - while (parent.Parent != null) + while (parent.Parent is not null) { parent = parent.Parent; } @@ -345,13 +345,13 @@ public void ReplaceWith(T value) internal void AssignParent(JsonNode parent) { - if (Parent != null) + if (Parent is not null) { ThrowHelper.ThrowInvalidOperationException_NodeAlreadyHasParent(); } JsonNode? p = parent; - while (p != null) + while (p is not null) { if (p == this) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.cs index 5ded130cff70ca..33f804be7fea68 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.cs @@ -264,7 +264,7 @@ internal override void GetPath(ref ValueStringBuilder path, JsonNode? child) { Parent?.GetPath(ref path, this); - if (child != null) + if (child is not null) { string propertyName = FindValue(child)!.Value.Key; if (propertyName.AsSpan().ContainsSpecialCharacters()) @@ -315,7 +315,7 @@ internal void SetItem(string propertyName, JsonNode? value) private void DetachParent(JsonNode? item) { - Debug.Assert(_dictionary != null, "Cannot have detachable nodes without a materialized dictionary."); + Debug.Assert(_dictionary is not null, "Cannot have detachable nodes without a materialized dictionary."); item?.Parent = null; } @@ -380,7 +380,7 @@ public string Display { get { - if (Value == null) + if (Value is null) { return $"{PropertyName} = null"; } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValue.CreateOverloads.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValue.CreateOverloads.cs index 439274348f4d3f..55b99343cd6df4 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValue.CreateOverloads.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValue.CreateOverloads.cs @@ -225,7 +225,7 @@ public partial class JsonValue /// Options to control the behavior. /// The new instance of the class that contains the specified value. [return: NotNullIfNotNull(nameof(value))] - public static JsonValue? Create(string? value, JsonNodeOptions? options = null) => value != null ? new JsonValuePrimitive(value, JsonMetadataServices.StringConverter!, options) : null; + public static JsonValue? Create(string? value, JsonNodeOptions? options = null) => value is not null ? new JsonValuePrimitive(value, JsonMetadataServices.StringConverter!, options) : null; /// /// Initializes a new instance of the class that contains the specified value. diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValue.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValue.cs index f7dc1d9083375f..02884ae932dd99 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValue.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValue.cs @@ -153,7 +153,7 @@ static JsonElement ToJsonElement(JsonNode node, out JsonDocument? backingDocumen internal sealed override void GetPath(ref ValueStringBuilder path, JsonNode? child) { - Debug.Assert(child == null); + Debug.Assert(child is null); Parent?.GetPath(ref path, this); } @@ -161,7 +161,7 @@ internal sealed override void GetPath(ref ValueStringBuilder path, JsonNode? chi internal static JsonValue CreateFromTypeInfo(T value, JsonTypeInfo jsonTypeInfo, JsonNodeOptions? options = null) { Debug.Assert(jsonTypeInfo.IsConfigured); - Debug.Assert(value != null); + Debug.Assert(value is not null); if (JsonValue.TypeIsSupportedPrimitive && jsonTypeInfo is { EffectiveConverter.IsInternalConverter: true } && diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueOfElement.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueOfElement.cs index 79f304d7dc43ea..0cc961ba7c84cf 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueOfElement.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueOfElement.cs @@ -142,7 +142,7 @@ public override bool TryGetValue([NotNullWhen(true)] out TypeToCo if (typeof(TypeToConvert) == typeof(string)) { string? result = Value.GetString(); - Debug.Assert(result != null); + Debug.Assert(result is not null); value = (TypeToConvert)(object)result; return true; } @@ -171,7 +171,7 @@ public override bool TryGetValue([NotNullWhen(true)] out TypeToCo if (typeof(TypeToConvert) == typeof(char) || typeof(TypeToConvert) == typeof(char?)) { string? result = Value.GetString(); - Debug.Assert(result != null); + Debug.Assert(result is not null); if (result.Length == 1) { value = (TypeToConvert)(object)result[0]; diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueOfJsonPrimitive.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueOfJsonPrimitive.cs index 823c9b8078d479..0cc2ac0a69d9f7 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueOfJsonPrimitive.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueOfJsonPrimitive.cs @@ -76,7 +76,7 @@ public override bool TryGetValue([NotNullWhen(true)] out T? value) { string? result = JsonReaderHelper.TranscodeHelper(_value.Span); - Debug.Assert(result != null); + Debug.Assert(result is not null); value = (T)(object)result; return true; } @@ -108,7 +108,7 @@ public override bool TryGetValue([NotNullWhen(true)] out T? value) { string? result = JsonReaderHelper.TranscodeHelper(_value.Span); - Debug.Assert(result != null); + Debug.Assert(result is not null); if (result.Length == 1) { value = (T)(object)result[0]; diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueOfT.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueOfT.cs index 5ae4d062da1318..03960ed3c4c625 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueOfT.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueOfT.cs @@ -14,7 +14,7 @@ internal abstract class JsonValue : JsonValue protected JsonValue(TValue value, JsonNodeOptions? options) : base(options) { - Debug.Assert(value != null); + Debug.Assert(value is not null); Debug.Assert(value is not JsonElement or JsonElement { ValueKind: not JsonValueKind.Null }); Debug.Assert(value is not JsonNode); Value = value; diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueOfTCustomized.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueOfTCustomized.cs index 4d1e18dc1b8852..bdbe1304606030 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueOfTCustomized.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueOfTCustomized.cs @@ -32,7 +32,7 @@ public override void WriteTo(Utf8JsonWriter writer, JsonSerializerOptions? optio JsonTypeInfo jsonTypeInfo = _jsonTypeInfo; - if (options != null && options != jsonTypeInfo.Options) + if (options is not null && options != jsonTypeInfo.Options) { options.MakeReadOnly(); jsonTypeInfo = (JsonTypeInfo)options.GetTypeInfoInternal(typeof(TValue)); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Reader/JsonReaderHelper.Unescaping.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Reader/JsonReaderHelper.Unescaping.cs index f5d37b2e3d36a2..52c5683608926f 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Reader/JsonReaderHelper.Unescaping.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Reader/JsonReaderHelper.Unescaping.cs @@ -27,7 +27,7 @@ public static unsafe bool TryGetUnescapedBase64Bytes(ReadOnlySpan utf8Sour bool result = TryDecodeBase64InPlace(utf8Unescaped, out bytes!); - if (unescapedArray != null) + if (unescapedArray is not null) { utf8Unescaped.Clear(); ArrayPool.Shared.Return(unescapedArray); @@ -57,7 +57,7 @@ public static unsafe string GetUnescapedString(ReadOnlySpan utf8Source) string utf8String = TranscodeHelper(utf8Unescaped); - if (pooledName != null) + if (pooledName is not null) { utf8Unescaped.Clear(); ArrayPool.Shared.Return(pooledName); @@ -82,7 +82,7 @@ public static unsafe byte[] GetUnescaped(ReadOnlySpan utf8Source) byte[] propertyName = utf8Unescaped.Slice(0, written).ToArray(); Debug.Assert(propertyName.Length is not 0); - if (pooledName != null) + if (pooledName is not null) { new Span(pooledName, 0, written).Clear(); ArrayPool.Shared.Return(pooledName); @@ -109,7 +109,7 @@ public static unsafe bool UnescapeAndCompare(ReadOnlySpan utf8Source, Read bool result = other.SequenceEqual(utf8Unescaped); - if (unescapedArray != null) + if (unescapedArray is not null) { utf8Unescaped.Clear(); ArrayPool.Shared.Return(unescapedArray); @@ -147,9 +147,9 @@ public static unsafe bool UnescapeAndCompare(ReadOnlySequence utf8Source, bool result = other.SequenceEqual(utf8Unescaped); - if (unescapedArray != null) + if (unescapedArray is not null) { - Debug.Assert(escapedArray != null); + Debug.Assert(escapedArray is not null); utf8Unescaped.Clear(); ArrayPool.Shared.Return(unescapedArray); utf8Escaped.Clear(); @@ -188,13 +188,13 @@ public static unsafe bool UnescapeAndCompareBothInputs(ReadOnlySpan utf8So bool result = utf8Unescaped1.SequenceEqual(utf8Unescaped2); - if (unescapedArray1 != null) + if (unescapedArray1 is not null) { utf8Unescaped1.Clear(); ArrayPool.Shared.Return(unescapedArray1); } - if (unescapedArray2 != null) + if (unescapedArray2 is not null) { utf8Unescaped2.Clear(); ArrayPool.Shared.Return(unescapedArray2); @@ -229,7 +229,7 @@ public static unsafe bool TryDecodeBase64(ReadOnlySpan utf8Unescaped, [Not { bytes = null; - if (pooledArray != null) + if (pooledArray is not null) { byteSpan.Clear(); ArrayPool.Shared.Return(pooledArray); @@ -241,7 +241,7 @@ public static unsafe bool TryDecodeBase64(ReadOnlySpan utf8Unescaped, [Not bytes = byteSpan.Slice(0, bytesWritten).ToArray(); - if (pooledArray != null) + if (pooledArray is not null) { byteSpan.Clear(); ArrayPool.Shared.Return(pooledArray); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Reader/Utf8JsonReader.MultiSegment.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Reader/Utf8JsonReader.MultiSegment.cs index 578b7d5d8e3b0b..977afdad20e829 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Reader/Utf8JsonReader.MultiSegment.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Reader/Utf8JsonReader.MultiSegment.cs @@ -300,7 +300,7 @@ private bool GetNextSpan() ReadOnlyMemory memory; while (true) { - Debug.Assert(!_isMultiSegment || _currentPosition.GetObject() != null); + Debug.Assert(!_isMultiSegment || _currentPosition.GetObject() is not null); SequencePosition copy = _currentPosition; _currentPosition = _nextPosition; bool noMoreData = !_sequence.TryGet(ref _nextPosition, out memory, advance: true); @@ -317,7 +317,7 @@ private bool GetNextSpan() // _currentPosition needs to point to last non-empty segment // Since memory.Length == 0, we need to revert back to previous. _currentPosition = copy; - Debug.Assert(!_isMultiSegment || _currentPosition.GetObject() != null); + Debug.Assert(!_isMultiSegment || _currentPosition.GetObject() is not null); } if (_isFinalBlock) @@ -1141,7 +1141,7 @@ private bool TryGetNumberMultiSegment(ReadOnlySpan data, out int consumed) Debug.Assert(signResult == ConsumeNumberResult.OperationIncomplete); byte nextByte = data[i]; - Debug.Assert(nextByte >= '0' && nextByte <= '9'); + Debug.Assert(nextByte is >= (byte)'0' and <= (byte)'9'); if (nextByte == '0') { @@ -1174,14 +1174,14 @@ private bool TryGetNumberMultiSegment(ReadOnlySpan data, out int consumed) Debug.Assert(result == ConsumeNumberResult.OperationIncomplete); nextByte = data[i]; - if (nextByte != '.' && nextByte != 'E' && nextByte != 'e') + if (nextByte is not ((byte)'.' or (byte)'E' or (byte)'e')) { RollBackState(rollBackState, isError: true); ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedEndOfDigitNotFound, nextByte); } } - Debug.Assert(nextByte == '.' || nextByte == 'E' || nextByte == 'e'); + Debug.Assert(nextByte is (byte)'.' or (byte)'E' or (byte)'e'); if (nextByte == '.') { @@ -1200,14 +1200,14 @@ private bool TryGetNumberMultiSegment(ReadOnlySpan data, out int consumed) Debug.Assert(result == ConsumeNumberResult.OperationIncomplete); nextByte = data[i]; - if (nextByte != 'E' && nextByte != 'e') + if (nextByte is not ((byte)'E' or (byte)'e')) { RollBackState(rollBackState, isError: true); ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedNextDigitEValueNotFound, nextByte); } } - Debug.Assert(nextByte == 'E' || nextByte == 'e'); + Debug.Assert(nextByte is (byte)'E' or (byte)'e'); i++; _bytePositionInLine++; @@ -1341,7 +1341,7 @@ private ConsumeNumberResult ConsumeZeroMultiSegment(ref ReadOnlySpan data, } } nextByte = data[i]; - if (nextByte != '.' && nextByte != 'E' && nextByte != 'e') + if (nextByte is not ((byte)'.' or (byte)'E' or (byte)'e')) { RollBackState(rollBackState, isError: true); ThrowHelper.ThrowJsonReaderException(ref this, @@ -1490,7 +1490,7 @@ private ConsumeNumberResult ConsumeSignMultiSegment(ref ReadOnlySpan data, } byte nextByte = data[i]; - if (nextByte == '+' || nextByte == '-') + if (nextByte is (byte)'+' or (byte)'-') { i++; _bytePositionInLine++; @@ -2264,7 +2264,7 @@ private bool SkipCommentMultiSegment(out int tailBytesToIgnore) } byte marker = localBuffer[0]; - if (marker != JsonConstants.Slash && marker != JsonConstants.Asterisk) + if (marker is not (JsonConstants.Slash or JsonConstants.Asterisk)) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidCharacterAtStartOfComment, marker); } @@ -2340,7 +2340,7 @@ private bool SkipSingleLineCommentMultiSegment(ReadOnlySpan localBuffer, o } int idx = FindLineSeparatorMultiSegment(localBuffer, ref dangerousLineSeparatorBytesConsumed); - Debug.Assert(dangerousLineSeparatorBytesConsumed >= 0 && dangerousLineSeparatorBytesConsumed <= 2); + Debug.Assert(dangerousLineSeparatorBytesConsumed is >= 0 and <= 2); if (idx != -1) { @@ -2498,7 +2498,7 @@ private void ThrowOnDangerousLineSeparatorMultiSegment(ReadOnlySpan localB if (dangerousLineSeparatorBytesConsumed == 2) { byte lastByte = localBuffer[0]; - if (lastByte == 0xA8 || lastByte == 0xA9) + if (lastByte is 0xA8 or 0xA9) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.UnexpectedEndOfLineSeparator); } @@ -2603,10 +2603,8 @@ private bool SkipMultiLineCommentMultiSegment(ReadOnlySpan localBuffer) } } - private PartialStateForRollback CaptureState() - { - return new PartialStateForRollback(_totalConsumed, _bytePositionInLine, _consumed, _currentPosition); - } + private PartialStateForRollback CaptureState() => + new PartialStateForRollback(_totalConsumed, _bytePositionInLine, _consumed, _currentPosition); private readonly struct PartialStateForRollback { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Reader/Utf8JsonReader.TryGet.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Reader/Utf8JsonReader.TryGet.cs index 6abc48478771d6..0650aea594ba6f 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Reader/Utf8JsonReader.TryGet.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Reader/Utf8JsonReader.TryGet.cs @@ -183,7 +183,7 @@ internal readonly unsafe int CopyValue(Span destination) int charsWritten = JsonReaderHelper.TranscodeHelper(unescapedSource, destination); - if (rentedBuffer != null) + if (rentedBuffer is not null) { new Span(rentedBuffer, 0, unescapedSource.Length).Clear(); ArrayPool.Shared.Return(rentedBuffer); @@ -219,7 +219,7 @@ private readonly unsafe bool TryCopyEscapedString(Span destination, out in bool success = JsonReaderHelper.TryUnescape(source, destination, out bytesWritten); - if (rentedBuffer != null) + if (rentedBuffer is not null) { new Span(rentedBuffer, 0, source.Length).Clear(); ArrayPool.Shared.Return(rentedBuffer); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Reader/Utf8JsonReader.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Reader/Utf8JsonReader.cs index 4d376ee80a0ab8..d1ba71625b124b 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Reader/Utf8JsonReader.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Reader/Utf8JsonReader.cs @@ -170,7 +170,7 @@ public readonly SequencePosition Position { if (_isInputSequence) { - Debug.Assert(_currentPosition.GetObject() != null); + Debug.Assert(_currentPosition.GetObject() is not null); return _sequence.GetPosition(_consumed, _currentPosition); } return default; @@ -562,7 +562,7 @@ public readonly unsafe bool ValueTextEquals(ReadOnlySpan text) result = TextEqualsHelper(otherUtf8Text.Slice(0, written)); } - if (otherUtf8TextArray != null) + if (otherUtf8TextArray is not null) { otherUtf8Text.Slice(0, written).Clear(); ArrayPool.Shared.Return(otherUtf8TextArray); @@ -689,7 +689,7 @@ private readonly bool UnescapeSequenceAndCompare(ReadOnlySpan other) // Otherwise, return false. private static bool IsTokenTypeString(JsonTokenType tokenType) { - return tokenType == JsonTokenType.PropertyName || tokenType == JsonTokenType.String; + return tokenType is JsonTokenType.PropertyName or JsonTokenType.String; } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -1473,7 +1473,7 @@ private bool TryGetNumber(ReadOnlySpan data, out int consumed) Debug.Assert(signResult == ConsumeNumberResult.OperationIncomplete); byte nextByte = data[i]; - Debug.Assert(nextByte >= '0' && nextByte <= '9'); + Debug.Assert(nextByte is >= (byte)'0' and <= (byte)'9'); if (nextByte == '0') { @@ -1505,14 +1505,14 @@ private bool TryGetNumber(ReadOnlySpan data, out int consumed) Debug.Assert(result == ConsumeNumberResult.OperationIncomplete); nextByte = data[i]; - if (nextByte != '.' && nextByte != 'E' && nextByte != 'e') + if (nextByte is not ((byte)'.' or (byte)'E' or (byte)'e')) { _bytePositionInLine += i; ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedEndOfDigitNotFound, nextByte); } } - Debug.Assert(nextByte == '.' || nextByte == 'E' || nextByte == 'e'); + Debug.Assert(nextByte is (byte)'.' or (byte)'E' or (byte)'e'); if (nextByte == '.') { @@ -1529,14 +1529,14 @@ private bool TryGetNumber(ReadOnlySpan data, out int consumed) Debug.Assert(result == ConsumeNumberResult.OperationIncomplete); nextByte = data[i]; - if (nextByte != 'E' && nextByte != 'e') + if (nextByte is not ((byte)'E' or (byte)'e')) { _bytePositionInLine += i; ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedNextDigitEValueNotFound, nextByte); } } - Debug.Assert(nextByte == 'E' || nextByte == 'e'); + Debug.Assert(nextByte is (byte)'E' or (byte)'e'); i++; signResult = ConsumeSign(ref data, ref i); @@ -1624,7 +1624,7 @@ private ConsumeNumberResult ConsumeZero(ref ReadOnlySpan data, scoped ref } } nextByte = data[i]; - if (nextByte != '.' && nextByte != 'E' && nextByte != 'e') + if (nextByte is not ((byte)'.' or (byte)'E' or (byte)'e')) { _bytePositionInLine += i; ThrowHelper.ThrowJsonReaderException(ref this, @@ -1703,7 +1703,7 @@ private ConsumeNumberResult ConsumeSign(ref ReadOnlySpan data, scoped ref } byte nextByte = data[i]; - if (nextByte == '+' || nextByte == '-') + if (nextByte is (byte)'+' or (byte)'-') { i++; if (i >= data.Length) @@ -2472,7 +2472,7 @@ private void ThrowOnDangerousLineSeparator(ReadOnlySpan localBuffer) } byte next = localBuffer[1]; - if (localBuffer[0] == 0x80 && (next == 0xA8 || next == 0xA9)) + if (localBuffer[0] == 0x80 && (next is 0xA8 or 0xA9)) { ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.UnexpectedEndOfLineSeparator); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Schema/JsonSchema.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Schema/JsonSchema.cs index 8ffc12bd077926..99fcd17c9595e0 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Schema/JsonSchema.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Schema/JsonSchema.cs @@ -44,56 +44,39 @@ public JsonSchema() { } /// private readonly bool? _trueOrFalse; - public string? Ref { get => _ref; set { VerifyMutable(); _ref = value; } } - private string? _ref; + public string? Ref { get; set { VerifyMutable(); field = value; } } - public string? Comment { get => _comment; set { VerifyMutable(); _comment = value; } } - private string? _comment; + public string? Comment { get; set { VerifyMutable(); field = value; } } - public JsonSchemaType Type { get => _type; set { VerifyMutable(); _type = value; } } - private JsonSchemaType _type = JsonSchemaType.Any; + public JsonSchemaType Type { get; set { VerifyMutable(); field = value; } } = JsonSchemaType.Any; - public string? Format { get => _format; set { VerifyMutable(); _format = value; } } - private string? _format; + public string? Format { get; set { VerifyMutable(); field = value; } } - public string? Pattern { get => _pattern; set { VerifyMutable(); _pattern = value; } } - private string? _pattern; + public string? Pattern { get; set { VerifyMutable(); field = value; } } - public JsonNode? Constant { get => _constant; set { VerifyMutable(); _constant = value; } } - private JsonNode? _constant; + public JsonNode? Constant { get; set { VerifyMutable(); field = value; } } - public List>? Properties { get => _properties; set { VerifyMutable(); _properties = value; } } - private List>? _properties; + public List>? Properties { get; set { VerifyMutable(); field = value; } } - public List? Required { get => _required; set { VerifyMutable(); _required = value; } } - private List? _required; + public List? Required { get; set { VerifyMutable(); field = value; } } - public JsonSchema? Items { get => _items; set { VerifyMutable(); _items = value; } } - private JsonSchema? _items; + public JsonSchema? Items { get; set { VerifyMutable(); field = value; } } - public JsonSchema? AdditionalProperties { get => _additionalProperties; set { VerifyMutable(); _additionalProperties = value; } } - private JsonSchema? _additionalProperties; + public JsonSchema? AdditionalProperties { get; set { VerifyMutable(); field = value; } } - public JsonArray? Enum { get => _enum; set { VerifyMutable(); _enum = value; } } - private JsonArray? _enum; + public JsonArray? Enum { get; set { VerifyMutable(); field = value; } } - public JsonSchema? Not { get => _not; set { VerifyMutable(); _not = value; } } - private JsonSchema? _not; + public JsonSchema? Not { get; set { VerifyMutable(); field = value; } } - public List? AnyOf { get => _anyOf; set { VerifyMutable(); _anyOf = value; } } - private List? _anyOf; + public List? AnyOf { get; set { VerifyMutable(); field = value; } } - public bool HasDefaultValue { get => _hasDefaultValue; set { VerifyMutable(); _hasDefaultValue = value; } } - private bool _hasDefaultValue; + public bool HasDefaultValue { get; set { VerifyMutable(); field = value; } } - public JsonNode? DefaultValue { get => _defaultValue; set { VerifyMutable(); _defaultValue = value; } } - private JsonNode? _defaultValue; + public JsonNode? DefaultValue { get; set { VerifyMutable(); field = value; } } - public int? MinLength { get => _minLength; set { VerifyMutable(); _minLength = value; } } - private int? _minLength; + public int? MinLength { get; set { VerifyMutable(); field = value; } } - public int? MaxLength { get => _maxLength; set { VerifyMutable(); _maxLength = value; } } - private int? _maxLength; + public int? MaxLength { get; set { VerifyMutable(); field = value; } } public JsonSchemaExporterContext? ExporterContext { get; set; } @@ -101,29 +84,29 @@ public int KeywordCount { get { - if (_trueOrFalse != null) + if (_trueOrFalse is not null) { // Boolean schemas admit no keywords return 0; } int count = 0; - Count(Ref != null); - Count(Comment != null); + Count(Ref is not null); + Count(Comment is not null); Count(Type != JsonSchemaType.Any); - Count(Format != null); - Count(Pattern != null); - Count(Constant != null); - Count(Properties != null); - Count(Required != null); - Count(Items != null); - Count(AdditionalProperties != null); - Count(Enum != null); - Count(Not != null); - Count(AnyOf != null); + Count(Format is not null); + Count(Pattern is not null); + Count(Constant is not null); + Count(Properties is not null); + Count(Required is not null); + Count(Items is not null); + Count(AdditionalProperties is not null); + Count(Enum is not null); + Count(Not is not null); + Count(AnyOf is not null); Count(HasDefaultValue); - Count(MinLength != null); - Count(MaxLength != null); + Count(MinLength is not null); + Count(MaxLength is not null); return count; @@ -136,7 +119,7 @@ void Count(bool isKeywordSpecified) public void MakeNullable() { - if (_trueOrFalse != null) + if (_trueOrFalse is not null) { // boolean schemas do not admit type keywords. return; @@ -157,12 +140,12 @@ public JsonNode ToJsonNode(JsonSchemaExporterOptions options) var objSchema = new JsonObject(); - if (Ref != null) + if (Ref is not null) { objSchema.Add(RefPropertyName, Ref); } - if (Comment != null) + if (Comment is not null) { objSchema.Add(CommentPropertyName, Comment); } @@ -172,22 +155,22 @@ public JsonNode ToJsonNode(JsonSchemaExporterOptions options) objSchema.Add(TypePropertyName, type); } - if (Format != null) + if (Format is not null) { objSchema.Add(FormatPropertyName, Format); } - if (Pattern != null) + if (Pattern is not null) { objSchema.Add(PatternPropertyName, Pattern); } - if (Constant != null) + if (Constant is not null) { objSchema.Add(ConstPropertyName, Constant); } - if (Properties != null) + if (Properties is not null) { var properties = new JsonObject(); foreach (KeyValuePair property in Properties) @@ -198,7 +181,7 @@ public JsonNode ToJsonNode(JsonSchemaExporterOptions options) objSchema.Add(PropertiesPropertyName, properties); } - if (Required != null) + if (Required is not null) { var requiredArray = new JsonArray(); foreach (string requiredProperty in Required) @@ -209,27 +192,27 @@ public JsonNode ToJsonNode(JsonSchemaExporterOptions options) objSchema.Add(RequiredPropertyName, requiredArray); } - if (Items != null) + if (Items is not null) { objSchema.Add(ItemsPropertyName, Items.ToJsonNode(options)); } - if (AdditionalProperties != null) + if (AdditionalProperties is not null) { objSchema.Add(AdditionalPropertiesPropertyName, AdditionalProperties.ToJsonNode(options)); } - if (Enum != null) + if (Enum is not null) { objSchema.Add(EnumPropertyName, Enum); } - if (Not != null) + if (Not is not null) { objSchema.Add(NotPropertyName, Not.ToJsonNode(options)); } - if (AnyOf != null) + if (AnyOf is not null) { JsonArray anyOfArray = []; foreach (JsonSchema schema in AnyOf) @@ -261,7 +244,7 @@ JsonNode CompleteSchema(JsonNode schema) { if (ExporterContext is { } context) { - Debug.Assert(options.TransformSchemaNode != null, "context should only be populated if a callback is present."); + Debug.Assert(options.TransformSchemaNode is not null, "context should only be populated if a callback is present."); // Apply any user-defined transformations to the schema. return options.TransformSchemaNode(context, schema); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Schema/JsonSchemaExporter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Schema/JsonSchemaExporter.cs index 1ac5814543c963..ae3c1f54259638 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Schema/JsonSchemaExporter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Schema/JsonSchemaExporter.cs @@ -202,7 +202,7 @@ private static JsonSchema MapJsonSchemaCore( } } } - else if (schema.Enum != null) + else if (schema.Enum is not null) { Debug.Assert(elementTypeInfo.Type.IsEnum, "The enum keyword should only be populated by schemas for enum types."); schema.Enum.Add(null); // Append null to the enum array. @@ -280,7 +280,7 @@ private static JsonSchema MapJsonSchemaCore( }); case JsonTypeInfoKind.Enumerable: - Debug.Assert(typeInfo.ElementTypeInfo != null); + Debug.Assert(typeInfo.ElementTypeInfo is not null); if (typeDiscriminator is null) { @@ -330,7 +330,7 @@ private static JsonSchema MapJsonSchemaCore( } case JsonTypeInfoKind.Dictionary: - Debug.Assert(typeInfo.ElementTypeInfo != null); + Debug.Assert(typeInfo.ElementTypeInfo is not null); List>? dictProps = null; List? dictRequired = null; @@ -451,7 +451,7 @@ bool IsNullableSchema(JsonSchemaExporterOptions options) } } - if (state.ExporterOptions.TransformSchemaNode != null) + if (state.ExporterOptions.TransformSchemaNode is not null) { // Prime the schema for invocation by the JsonNode transformer. schema.ExporterContext = exporterContext; diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/ConfigurationList.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/ConfigurationList.cs index dacb8773d8e418..669cd293974414 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/ConfigurationList.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/ConfigurationList.cs @@ -62,25 +62,16 @@ public void Clear() OnCollectionModified(); } - public bool Contains(TItem item) - { - return _list.Contains(item); - } + public bool Contains(TItem item) => _list.Contains(item); public void CopyTo(TItem[] array, int arrayIndex) { _list.CopyTo(array, arrayIndex); } - public List.Enumerator GetEnumerator() - { - return _list.GetEnumerator(); - } + public List.Enumerator GetEnumerator() => _list.GetEnumerator(); - public int IndexOf(TItem item) - { - return _list.IndexOf(item); - } + public int IndexOf(TItem item) => _list.IndexOf(item); public void Insert(int index, TItem item) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/ArrayConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/ArrayConverter.cs index f50ddf04b40b79..8d9d7df52909d9 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/ArrayConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/ArrayConverter.cs @@ -36,7 +36,7 @@ protected override bool OnWriteResume(Utf8JsonWriter writer, TElement[] array, J int index = state.Current.EnumeratorIndex; JsonConverter elementConverter = GetElementConverter(ref state); - if (elementConverter.CanUseDirectReadOrWrite && state.Current.NumberHandling == null) + if (elementConverter.CanUseDirectReadOrWrite && state.Current.NumberHandling is null) { // Fast path that avoids validation and extra indirection. for (; index < array.Length; index++) diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/DictionaryDefaultConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/DictionaryDefaultConverter.cs index 659461a5e9fe69..7c81280332080c 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/DictionaryDefaultConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/DictionaryDefaultConverter.cs @@ -25,7 +25,7 @@ protected internal override bool OnWriteResume( ref WriteStack state) { IEnumerator> enumerator; - if (state.Current.CollectionEnumerator == null) + if (state.Current.CollectionEnumerator is null) { enumerator = value.GetEnumerator(); state.Current.CollectionEnumerator = enumerator; diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/DictionaryOfTKeyTValueConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/DictionaryOfTKeyTValueConverter.cs index 3d26a18d54ab8b..8c41916aea4e51 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/DictionaryOfTKeyTValueConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/DictionaryOfTKeyTValueConverter.cs @@ -41,7 +41,7 @@ protected internal override bool OnWriteResume( ref WriteStack state) { Dictionary.Enumerator enumerator; - if (state.Current.CollectionEnumerator == null) + if (state.Current.CollectionEnumerator is null) { enumerator = value.GetEnumerator(); if (!enumerator.MoveNext()) @@ -59,7 +59,7 @@ protected internal override bool OnWriteResume( _keyConverter ??= GetConverter(typeInfo.KeyTypeInfo!); _valueConverter ??= GetConverter(typeInfo.ElementTypeInfo!); - if (!state.SupportContinuation && _valueConverter.CanUseDirectReadOrWrite && state.Current.NumberHandling == null) + if (!state.SupportContinuation && _valueConverter.CanUseDirectReadOrWrite && state.Current.NumberHandling is null) { // Fast path that avoids validation and extra indirection. do diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/IDictionaryConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/IDictionaryConverter.cs index 043ff221fe8ad1..b42a96c9fb9e58 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/IDictionaryConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/IDictionaryConverter.cs @@ -49,7 +49,7 @@ protected override void CreateCollection(ref Utf8JsonReader reader, scoped ref R protected internal override bool OnWriteResume(Utf8JsonWriter writer, TDictionary value, JsonSerializerOptions options, ref WriteStack state) { IDictionaryEnumerator enumerator; - if (state.Current.CollectionEnumerator == null) + if (state.Current.CollectionEnumerator is null) { enumerator = value.GetEnumerator(); state.Current.CollectionEnumerator = enumerator; diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/IEnumerableConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/IEnumerableConverter.cs index c156e58f812cd2..d956d2c2ea464e 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/IEnumerableConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/IEnumerableConverter.cs @@ -43,7 +43,7 @@ protected override bool OnWriteResume( ref WriteStack state) { IEnumerator enumerator; - if (state.Current.CollectionEnumerator == null) + if (state.Current.CollectionEnumerator is null) { enumerator = value.GetEnumerator(); state.Current.CollectionEnumerator = enumerator; diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/IEnumerableConverterFactoryHelpers.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/IEnumerableConverterFactoryHelpers.cs index 3d1c4ce8fce545..ea7581ca022495 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/IEnumerableConverterFactoryHelpers.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/IEnumerableConverterFactoryHelpers.cs @@ -73,7 +73,7 @@ public static MethodInfo GetImmutableDictionaryCreateRangeMethod(this Type type, string? constructingTypeName = type.GetImmutableEnumerableConstructingTypeName(); - return constructingTypeName == null + return constructingTypeName is null ? null : type.Assembly.GetType(constructingTypeName); } @@ -86,7 +86,7 @@ public static MethodInfo GetImmutableDictionaryCreateRangeMethod(this Type type, string? constructingTypeName = type.GetImmutableDictionaryConstructingTypeName(); - return constructingTypeName == null + return constructingTypeName is null ? null : type.Assembly.GetType(constructingTypeName); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/IEnumerableDefaultConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/IEnumerableDefaultConverter.cs index e53e48151a25be..a4f5eb15fa50f2 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/IEnumerableDefaultConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/IEnumerableDefaultConverter.cs @@ -19,7 +19,7 @@ protected override bool OnWriteResume(Utf8JsonWriter writer, TCollection value, Debug.Assert(value is not null); IEnumerator enumerator; - if (state.Current.CollectionEnumerator == null) + if (state.Current.CollectionEnumerator is null) { enumerator = value.GetEnumerator(); state.Current.CollectionEnumerator = enumerator; diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/IListConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/IListConverter.cs index 7de440ed11fc18..64bf2d617cc22c 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/IListConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/IListConverter.cs @@ -44,7 +44,7 @@ protected override bool OnWriteResume(Utf8JsonWriter writer, TCollection value, int index = state.Current.EnumeratorIndex; JsonConverter elementConverter = GetElementConverter(ref state); - if (elementConverter.CanUseDirectReadOrWrite && state.Current.NumberHandling == null) + if (elementConverter.CanUseDirectReadOrWrite && state.Current.NumberHandling is null) { // Fast path that avoids validation and extra indirection. for (; index < list.Count; index++) diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/ImmutableDictionaryOfTKeyTValueConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/ImmutableDictionaryOfTKeyTValueConverter.cs index 18eb4adae1cfa0..887b4c4195ef57 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/ImmutableDictionaryOfTKeyTValueConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/ImmutableDictionaryOfTKeyTValueConverter.cs @@ -42,7 +42,7 @@ protected sealed override void ConvertCollection(ref ReadStack state, JsonSerial { Func>, TDictionary>? creator = (Func>, TDictionary>?)state.Current.JsonTypeInfo.CreateObjectWithArgs; - Debug.Assert(creator != null); + Debug.Assert(creator is not null); state.Current.ReturnValue = creator((Dictionary)state.Current.ReturnValue!); } } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/ImmutableEnumerableOfTConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/ImmutableEnumerableOfTConverter.cs index 82577539af58d3..7929b815668f4e 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/ImmutableEnumerableOfTConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/ImmutableEnumerableOfTConverter.cs @@ -30,7 +30,7 @@ protected sealed override void ConvertCollection(ref ReadStack state, JsonSerial JsonTypeInfo typeInfo = state.Current.JsonTypeInfo; Func, TCollection>? creator = (Func, TCollection>?)typeInfo.CreateObjectWithArgs; - Debug.Assert(creator != null); + Debug.Assert(creator is not null); state.Current.ReturnValue = creator((List)state.Current.ReturnValue!); } } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/JsonCollectionConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/JsonCollectionConverter.cs index a02af1f8eeb4d8..7c766d644aec1c 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/JsonCollectionConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/JsonCollectionConverter.cs @@ -54,7 +54,7 @@ protected static JsonConverter GetElementConverter(JsonTypeInfo elemen protected static JsonConverter GetElementConverter(ref WriteStack state) { - Debug.Assert(state.Current.JsonPropertyInfo != null); + Debug.Assert(state.Current.JsonPropertyInfo is not null); return (JsonConverter)state.Current.JsonPropertyInfo.EffectiveConverter; } @@ -83,7 +83,7 @@ internal override bool OnTryRead( state.Current.JsonPropertyInfo = elementTypeInfo.PropertyInfoForTypeInfo; JsonConverter elementConverter = GetElementConverter(elementTypeInfo); - if (elementConverter.CanUseDirectReadOrWrite && state.Current.NumberHandling == null) + if (elementConverter.CanUseDirectReadOrWrite && state.Current.NumberHandling is null) { // Fast path that avoids validation and extra indirection. while (true) @@ -181,7 +181,7 @@ internal override bool OnTryRead( if ((state.Current.MetadataPropertyNames & MetadataPropertyName.Id) != 0) { - Debug.Assert(state.ReferenceId != null); + Debug.Assert(state.ReferenceId is not null); Debug.Assert(options.ReferenceHandlingStrategy == JsonKnownReferenceHandler.Preserve); Debug.Assert(state.Current.ReturnValue is TCollection); state.ReferenceResolver.AddReference(state.ReferenceId, state.Current.ReturnValue); @@ -296,7 +296,7 @@ internal override bool OnTryWrite( { bool success; - if (value == null) + if (value is null) { writer.WriteNullValue(); success = true; diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/JsonDictionaryConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/JsonDictionaryConverter.cs index ba022baaaf7d03..8f7bd7cd0dc8a3 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/JsonDictionaryConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/JsonDictionaryConverter.cs @@ -96,7 +96,7 @@ internal sealed override bool OnTryRead( _keyConverter ??= GetConverter(keyTypeInfo); _valueConverter ??= GetConverter(elementTypeInfo); - if (_valueConverter.CanUseDirectReadOrWrite && state.Current.NumberHandling == null) + if (_valueConverter.CanUseDirectReadOrWrite && state.Current.NumberHandling is null) { // Process all elements. while (true) @@ -204,7 +204,7 @@ internal sealed override bool OnTryRead( if ((state.Current.MetadataPropertyNames & MetadataPropertyName.Id) != 0) { - Debug.Assert(state.ReferenceId != null); + Debug.Assert(state.ReferenceId is not null); Debug.Assert(options.ReferenceHandlingStrategy == JsonKnownReferenceHandler.Preserve); Debug.Assert(state.Current.ReturnValue is TDictionary); state.ReferenceResolver.AddReference(state.ReferenceId, state.Current.ReturnValue); @@ -337,7 +337,7 @@ internal sealed override bool OnTryWrite( JsonSerializerOptions options, ref WriteStack state) { - if (dictionary == null) + if (dictionary is null) { writer.WriteNullValue(); return true; diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/ListOfTConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/ListOfTConverter.cs index 60a934c1104db5..31eacc9ff573e0 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/ListOfTConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/ListOfTConverter.cs @@ -25,7 +25,7 @@ protected override void CreateCollection(ref Utf8JsonReader reader, scoped ref R return; } - if (state.Current.JsonTypeInfo.CreateObject == null) + if (state.Current.JsonTypeInfo.CreateObject is null) { ThrowHelper.ThrowNotSupportedException_SerializationNotSupported(state.Current.JsonTypeInfo.Type); } @@ -41,7 +41,7 @@ protected override bool OnWriteResume(Utf8JsonWriter writer, TCollection value, int index = state.Current.EnumeratorIndex; JsonConverter elementConverter = GetElementConverter(ref state); - if (elementConverter.CanUseDirectReadOrWrite && state.Current.NumberHandling == null) + if (elementConverter.CanUseDirectReadOrWrite && state.Current.NumberHandling is null) { // Fast path that avoids validation and extra indirection. for (; index < list.Count; index++) diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/QueueOfTConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/QueueOfTConverter.cs index 2e5de462226bd2..dcda48cd12dded 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/QueueOfTConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/QueueOfTConverter.cs @@ -23,7 +23,7 @@ protected override void CreateCollection(ref Utf8JsonReader reader, scoped ref R return; } - if (state.Current.JsonTypeInfo.CreateObject == null) + if (state.Current.JsonTypeInfo.CreateObject is null) { ThrowHelper.ThrowNotSupportedException_SerializationNotSupported(state.Current.JsonTypeInfo.Type); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/ReadOnlyMemoryConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/ReadOnlyMemoryConverter.cs index be069d580d8275..f5ce452a83564a 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/ReadOnlyMemoryConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/ReadOnlyMemoryConverter.cs @@ -55,7 +55,7 @@ internal static bool OnWriteResume(Utf8JsonWriter writer, ReadOnlySpan value, JsonConverter elementConverter = GetElementConverter(ref state); - if (elementConverter.CanUseDirectReadOrWrite && state.Current.NumberHandling == null) + if (elementConverter.CanUseDirectReadOrWrite && state.Current.NumberHandling is null) { // Fast path that avoids validation and extra indirection. for (; index < value.Length; index++) diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/StackOfTConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/StackOfTConverter.cs index 18a08f299d212f..0a7c2ef5b072ce 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/StackOfTConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/StackOfTConverter.cs @@ -24,7 +24,7 @@ protected override void CreateCollection(ref Utf8JsonReader reader, scoped ref R return; } - if (state.Current.JsonTypeInfo.CreateObject == null) + if (state.Current.JsonTypeInfo.CreateObject is null) { ThrowHelper.ThrowNotSupportedException_SerializationNotSupported(state.Current.JsonTypeInfo.Type); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/StackOrQueueConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/StackOrQueueConverter.cs index 7a09048f8e450f..33fc965fe4630b 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/StackOrQueueConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/StackOrQueueConverter.cs @@ -16,7 +16,7 @@ internal class StackOrQueueConverter protected sealed override void Add(in object? value, ref ReadStack state) { var addMethodDelegate = ((Action?)state.Current.JsonTypeInfo.AddMethodDelegate); - Debug.Assert(addMethodDelegate != null); + Debug.Assert(addMethodDelegate is not null); addMethodDelegate((TCollection)state.Current.ReturnValue!, value); } @@ -30,20 +30,20 @@ protected sealed override void CreateCollection(ref Utf8JsonReader reader, scope JsonTypeInfo typeInfo = state.Current.JsonTypeInfo; Func? constructorDelegate = typeInfo.CreateObject; - if (constructorDelegate == null) + if (constructorDelegate is null) { ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(Type, ref reader, ref state); } state.Current.ReturnValue = constructorDelegate(); - Debug.Assert(typeInfo.AddMethodDelegate != null); + Debug.Assert(typeInfo.AddMethodDelegate is not null); } protected sealed override bool OnWriteResume(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, ref WriteStack state) { IEnumerator enumerator; - if (state.Current.CollectionEnumerator == null) + if (state.Current.CollectionEnumerator is null) { enumerator = value.GetEnumerator(); state.Current.CollectionEnumerator = enumerator; diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/JsonMetadataServicesConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/JsonMetadataServicesConverter.cs index df1ec84aae68c9..fadf0260d2aceb 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/JsonMetadataServicesConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/JsonMetadataServicesConverter.cs @@ -51,7 +51,7 @@ internal override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, internal override bool OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, ref WriteStack state) { JsonTypeInfo jsonTypeInfo = state.Current.JsonTypeInfo; - Debug.Assert(jsonTypeInfo is JsonTypeInfo typeInfo && typeInfo.SerializeHandler != null); + Debug.Assert(jsonTypeInfo is JsonTypeInfo typeInfo && typeInfo.SerializeHandler is not null); if (!state.SupportContinuation && jsonTypeInfo.CanUseSerializeHandler && diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Node/JsonObjectConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Node/JsonObjectConverter.cs index 9e0cba940c0703..c6004b7aee0d6c 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Node/JsonObjectConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Node/JsonObjectConverter.cs @@ -28,7 +28,7 @@ internal override void ReadElementAndSetProperty( Debug.Assert(obj is JsonObject); JsonObject jObject = (JsonObject)obj; - Debug.Assert(value == null || value is JsonNode); + Debug.Assert(value is null || value is JsonNode); JsonNode? jNodeValue = value; if (options.AllowDuplicateProperties) diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectDefaultConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectDefaultConverter.cs index ae6afbcdad245a..939918ac59ff7a 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectDefaultConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectDefaultConverter.cs @@ -44,7 +44,7 @@ internal override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, } else { - if (jsonTypeInfo.CreateObject == null) + if (jsonTypeInfo.CreateObject is null) { ThrowHelper.ThrowNotSupportedException_DeserializeNoConstructor(jsonTypeInfo, ref reader, ref state); } @@ -53,7 +53,7 @@ internal override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, } PopulatePropertiesFastPath(obj, jsonTypeInfo, options, ref reader, ref state); - Debug.Assert(obj != null); + Debug.Assert(obj is not null); value = (T)obj; return true; } @@ -120,7 +120,7 @@ internal override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, } else { - if (jsonTypeInfo.CreateObject == null) + if (jsonTypeInfo.CreateObject is null) { ThrowHelper.ThrowNotSupportedException_DeserializeNoConstructor(jsonTypeInfo, ref reader, ref state); } @@ -130,7 +130,7 @@ internal override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, if ((state.Current.MetadataPropertyNames & MetadataPropertyName.Id) != 0) { - Debug.Assert(state.ReferenceId != null); + Debug.Assert(state.ReferenceId is not null); Debug.Assert(options.ReferenceHandlingStrategy == JsonKnownReferenceHandler.Preserve); state.ReferenceResolver.AddReference(state.ReferenceId, obj); state.ReferenceId = null; @@ -145,7 +145,7 @@ internal override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, else { obj = state.Current.ReturnValue!; - Debug.Assert(obj != null); + Debug.Assert(obj is not null); } // Process all properties. @@ -199,7 +199,7 @@ internal override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, } else { - Debug.Assert(state.Current.JsonPropertyInfo != null); + Debug.Assert(state.Current.JsonPropertyInfo is not null); jsonPropertyInfo = state.Current.JsonPropertyInfo!; } @@ -260,11 +260,11 @@ internal override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, state.Current.ValidateAllRequiredPropertiesAreRead(jsonTypeInfo); // Unbox - Debug.Assert(obj != null); + Debug.Assert(obj is not null); value = (T)obj; // Check if we are trying to update the UTF-8 property cache. - if (state.Current.PropertyRefCacheBuilder != null) + if (state.Current.PropertyRefCacheBuilder is not null) { jsonTypeInfo.UpdateUtf8PropertyCache(ref state.Current); } @@ -313,7 +313,7 @@ internal static void PopulatePropertiesFastPath(object obj, JsonTypeInfo jsonTyp state.Current.ValidateAllRequiredPropertiesAreRead(jsonTypeInfo); // Check if we are trying to update the UTF-8 property cache. - if (state.Current.PropertyRefCacheBuilder != null) + if (state.Current.PropertyRefCacheBuilder is not null) { jsonTypeInfo.UpdateUtf8PropertyCache(ref state.Current); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectWithParameterizedConstructorConverter.Large.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectWithParameterizedConstructorConverter.Large.cs index b65c994abd1eea..5d24ed607b0788 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectWithParameterizedConstructorConverter.Large.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectWithParameterizedConstructorConverter.Large.cs @@ -20,9 +20,9 @@ protected sealed override bool ReadAndCacheConstructorArgument(scoped ref ReadSt bool success = jsonParameterInfo.EffectiveConverter.TryReadAsObject(ref reader, jsonParameterInfo.ParameterType, jsonParameterInfo.Options, ref state, out object? arg); - if (success && !(arg == null && jsonParameterInfo.IgnoreNullTokensOnRead)) + if (success && !(arg is null && jsonParameterInfo.IgnoreNullTokensOnRead)) { - if (arg == null && !jsonParameterInfo.IsNullable && jsonParameterInfo.Options.RespectNullableAnnotations) + if (arg is null && !jsonParameterInfo.IsNullable && jsonParameterInfo.Options.RespectNullableAnnotations) { ThrowHelper.ThrowJsonException_ConstructorParameterDisallowNull(jsonParameterInfo.Name, state.Current.JsonTypeInfo.Type); } @@ -35,8 +35,8 @@ protected sealed override bool ReadAndCacheConstructorArgument(scoped ref ReadSt protected sealed override object CreateObject(ref ReadStackFrame frame) { - Debug.Assert(frame.CtorArgumentState != null); - Debug.Assert(frame.JsonTypeInfo.CreateObjectWithArgs != null); + Debug.Assert(frame.CtorArgumentState is not null); + Debug.Assert(frame.JsonTypeInfo.CreateObjectWithArgs is not null); object[] arguments = (object[])frame.CtorArgumentState.Arguments; frame.CtorArgumentState.Arguments = null!; diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectWithParameterizedConstructorConverter.Small.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectWithParameterizedConstructorConverter.Small.cs index 292f19b3d0ff29..42df7972f439e6 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectWithParameterizedConstructorConverter.Small.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectWithParameterizedConstructorConverter.Small.cs @@ -27,7 +27,7 @@ protected override bool ReadAndCacheConstructorArgument( ref Utf8JsonReader reader, JsonParameterInfo jsonParameterInfo) { - Debug.Assert(state.Current.CtorArgumentState!.Arguments != null); + Debug.Assert(state.Current.CtorArgumentState!.Arguments is not null); var arguments = (Arguments)state.Current.CtorArgumentState.Arguments; bool success; @@ -90,7 +90,7 @@ protected override void InitializeConstructorArgumentCaches(ref ReadStack state, { JsonTypeInfo typeInfo = state.Current.JsonTypeInfo; - Debug.Assert(typeInfo.CreateObjectWithArgs != null); + Debug.Assert(typeInfo.CreateObjectWithArgs is not null); var arguments = new Arguments(); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectWithParameterizedConstructorConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectWithParameterizedConstructorConverter.cs index bb97c7854bacb1..fd53f8fcacc421 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectWithParameterizedConstructorConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectWithParameterizedConstructorConverter.cs @@ -72,7 +72,7 @@ internal sealed override bool OnTryRead(ref Utf8JsonReader reader, Type typeToCo Utf8JsonReader tempReader; FoundProperty[]? properties = argumentState.FoundProperties; - Debug.Assert(properties != null); + Debug.Assert(properties is not null); for (int i = 0; i < argumentState.FoundPropertyCount; i++) { @@ -97,7 +97,7 @@ internal sealed override bool OnTryRead(ref Utf8JsonReader reader, Type typeToCo state.Current.JsonPropertyInfo = jsonPropertyInfo; state.Current.NumberHandling = jsonPropertyInfo.EffectiveNumberHandling; - bool useExtensionProperty = dataExtKey != null; + bool useExtensionProperty = dataExtKey is not null; if (useExtensionProperty) { @@ -206,7 +206,7 @@ internal sealed override bool OnTryRead(ref Utf8JsonReader reader, Type typeToCo if ((state.Current.MetadataPropertyNames & MetadataPropertyName.Id) != 0) { - Debug.Assert(state.ReferenceId != null); + Debug.Assert(state.ReferenceId is not null); Debug.Assert(options.ReferenceHandlingStrategy == JsonKnownReferenceHandler.Preserve); state.ReferenceResolver.AddReference(state.ReferenceId, obj); state.ReferenceId = null; @@ -222,9 +222,9 @@ internal sealed override bool OnTryRead(ref Utf8JsonReader reader, Type typeToCo object? propValue = argumentState.FoundPropertiesAsync![i].Item2; string? dataExtKey = argumentState.FoundPropertiesAsync![i].Item3; - if (dataExtKey == null) + if (dataExtKey is null) { - Debug.Assert(jsonPropertyInfo.Set != null); + Debug.Assert(jsonPropertyInfo.Set is not null); if (propValue is not null || !jsonPropertyInfo.IgnoreNullTokensOnRead || default(T) is not null) { @@ -274,11 +274,11 @@ internal sealed override bool OnTryRead(ref Utf8JsonReader reader, Type typeToCo jsonTypeInfo.OnDeserialized?.Invoke(obj); // Unbox - Debug.Assert(obj != null); + Debug.Assert(obj is not null); value = (T)obj; // Check if we are trying to update the UTF-8 property cache. - if (state.Current.PropertyRefCacheBuilder != null) + if (state.Current.PropertyRefCacheBuilder is not null) { jsonTypeInfo.UpdateUtf8PropertyCache(ref state.Current); } @@ -349,7 +349,7 @@ private void ReadConstructorArguments(scoped ref ReadStack state, ref Utf8JsonRe continue; } - Debug.Assert(jsonParameterInfo.MatchingProperty != null); + Debug.Assert(jsonParameterInfo.MatchingProperty is not null); ReadAndCacheConstructorArgument(ref state, ref reader, jsonParameterInfo); state.Current.EndConstructorParameter(); @@ -360,7 +360,7 @@ private void ReadConstructorArguments(scoped ref ReadStack state, ref Utf8JsonRe { ArgumentState argumentState = state.Current.CtorArgumentState!; - if (argumentState.FoundProperties == null) + if (argumentState.FoundProperties is null) { argumentState.FoundProperties = ArrayPool.Shared.Rent(Math.Max(1, state.Current.JsonTypeInfo.PropertyCache.Length)); @@ -452,9 +452,9 @@ private bool ReadConstructorArgumentsWithContinuation(scoped ref ReadStack state jsonPropertyInfo = state.Current.JsonPropertyInfo; } - if (jsonParameterInfo != null) + if (jsonParameterInfo is not null) { - Debug.Assert(jsonPropertyInfo == null); + Debug.Assert(jsonPropertyInfo is null); if (!HandleConstructorArgumentWithContinuation(ref state, ref reader, jsonParameterInfo)) { @@ -557,7 +557,7 @@ private static bool HandlePropertyWithContinuation( ArgumentState argumentState = state.Current.CtorArgumentState!; - if (argumentState.FoundPropertiesAsync == null) + if (argumentState.FoundPropertiesAsync is null) { argumentState.FoundPropertiesAsync = ArrayPool.Shared.Rent(Math.Max(1, state.Current.JsonTypeInfo.PropertyCache.Length)); } @@ -602,7 +602,7 @@ private void BeginRead(scoped ref ReadStack state, JsonSerializerOptions options // Set current JsonPropertyInfo to null to avoid conflicts on push. state.Current.JsonPropertyInfo = null; - Debug.Assert(state.Current.CtorArgumentState != null); + Debug.Assert(state.Current.CtorArgumentState is not null); InitializeConstructorArgumentCaches(ref state, options); } @@ -618,7 +618,7 @@ protected static bool TryLookupConstructorParameter( [NotNullWhen(true)] out JsonParameterInfo? jsonParameterInfo) { Debug.Assert(state.Current.JsonTypeInfo.Kind is JsonTypeInfoKind.Object); - Debug.Assert(state.Current.CtorArgumentState != null); + Debug.Assert(state.Current.CtorArgumentState is not null); jsonPropertyInfo = JsonSerializer.LookupProperty( obj: null, @@ -635,7 +635,7 @@ protected static bool TryLookupConstructorParameter( } jsonParameterInfo = jsonPropertyInfo.AssociatedParameter; - if (jsonParameterInfo != null) + if (jsonParameterInfo is not null) { state.Current.JsonPropertyInfo = null; state.Current.CtorArgumentState!.JsonParameterInfo = jsonParameterInfo; diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/ByteArrayConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/ByteArrayConverter.cs index 93c2791d1525b0..7da350f9528a39 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/ByteArrayConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/ByteArrayConverter.cs @@ -19,7 +19,7 @@ internal sealed class ByteArrayConverter : JsonConverter public override void Write(Utf8JsonWriter writer, byte[]? value, JsonSerializerOptions options) { - if (value == null) + if (value is null) { writer.WriteNullValue(); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/EnumConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/EnumConverter.cs index 01188a02c368dc..30002f4e98a099 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/EnumConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/EnumConverter.cs @@ -75,7 +75,7 @@ public EnumConverter(EnumConverterOptions converterOptions, JsonNamingPolicy? na _nameCacheForReading.TryAdd(fieldInfo.JsonName, fieldInfo.Key); } - if (namingPolicy != null) + if (namingPolicy is not null) { // Additionally populate the field index with the default names of fields that used a naming policy. // This is done to preserve backward compat: default names should still be recognized by the parser. @@ -204,7 +204,7 @@ internal override void WriteAsPropertyNameCore(Utf8JsonWriter writer, T value, J if (IsDefinedValueOrCombinationOfValues(key)) { - Debug.Assert(s_isFlagsEnum || dictionaryKeyPolicy != null, "Should only be entered by flags enums or dictionary key policy."); + Debug.Assert(s_isFlagsEnum || dictionaryKeyPolicy is not null, "Should only be entered by flags enums or dictionary key policy."); string stringValue = FormatEnumAsString(key, value, dictionaryKeyPolicy); if (dictionaryKeyPolicy is null && _nameCacheForWriting.Count < NameCacheSizeSoftLimit) { @@ -285,7 +285,7 @@ private unsafe bool TryParseEnumFromString(ref Utf8JsonReader reader, out T resu } End: - if (rentedBuffer != null) + if (rentedBuffer is not null) { charBuffer.Clear(); ArrayPool.Shared.Return(rentedBuffer); @@ -434,7 +434,7 @@ private unsafe string FormatEnumAsString(ulong key, T value, JsonNamingPolicy? d } else { - Debug.Assert(dictionaryKeyPolicy != null); + Debug.Assert(dictionaryKeyPolicy is not null); foreach (EnumFieldInfo enumField in _enumFieldInfo) { @@ -556,14 +556,14 @@ private static EnumFieldInfo[] ResolveEnumFields(JsonNamingPolicy? namingPolicy) ulong key = ConvertToUInt64(value); EnumFieldNameKind kind; - if (enumMemberAttributes != null && enumMemberAttributes.TryGetValue(originalName, out string? attributeName)) + if (enumMemberAttributes is not null && enumMemberAttributes.TryGetValue(originalName, out string? attributeName)) { originalName = attributeName; kind = EnumFieldNameKind.Attribute; } else { - kind = namingPolicy != null ? EnumFieldNameKind.NamingPolicy : EnumFieldNameKind.Default; + kind = namingPolicy is not null ? EnumFieldNameKind.NamingPolicy : EnumFieldNameKind.Default; } string jsonName = ResolveAndValidateJsonName(originalName, namingPolicy, kind); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/HalfConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/HalfConverter.cs index b94fb2ebb7c924..d9f9cc519572bd 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/HalfConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/HalfConverter.cs @@ -62,7 +62,7 @@ private static unsafe Half ReadCore(ref Utf8JsonReader reader) byteBuffer = byteBuffer.Slice(0, written); bool success = TryParse(byteBuffer, out result); - if (rentedByteBuffer != null) + if (rentedByteBuffer is not null) { ArrayPool.Shared.Return(rentedByteBuffer); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/Int128Converter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/Int128Converter.cs index 0bea6fbab9d702..a6e0a5fd37d0cf 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/Int128Converter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/Int128Converter.cs @@ -59,7 +59,7 @@ private static unsafe Int128 ReadCore(ref Utf8JsonReader reader) ThrowHelper.ThrowFormatException(NumericType.Int128); } - if (rentedBuffer != null) + if (rentedBuffer is not null) { ArrayPool.Shared.Return(rentedBuffer); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/StringConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/StringConverter.cs index f04b059b4a8b77..f49dd240e0663c 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/StringConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/StringConverter.cs @@ -17,7 +17,7 @@ internal sealed class StringConverter : JsonPrimitiveConverter public override void Write(Utf8JsonWriter writer, string? value, JsonSerializerOptions options) { // For performance, lift up the writer implementation. - if (value == null) + if (value is null) { writer.WriteNullValue(); } @@ -37,11 +37,11 @@ internal override void WriteAsPropertyNameCore(Utf8JsonWriter writer, string val { ArgumentNullException.ThrowIfNull(value); - if (options.DictionaryKeyPolicy != null && !isWritingExtensionDataProperty) + if (options.DictionaryKeyPolicy is not null && !isWritingExtensionDataProperty) { value = options.DictionaryKeyPolicy.ConvertName(value); - if (value == null) + if (value is null) { ThrowHelper.ThrowInvalidOperationException_NamingPolicyReturnNull(options.DictionaryKeyPolicy); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/UInt128Converter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/UInt128Converter.cs index f6120f990bd84a..ddb056b94378ee 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/UInt128Converter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/UInt128Converter.cs @@ -59,7 +59,7 @@ private static unsafe UInt128 ReadCore(ref Utf8JsonReader reader) ThrowHelper.ThrowFormatException(NumericType.UInt128); } - if (rentedBuffer != null) + if (rentedBuffer is not null) { ArrayPool.Shared.Return(rentedBuffer); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/IgnoreReferenceResolver.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/IgnoreReferenceResolver.cs index c9a66ed6fd529e..e007f5e4da61ae 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/IgnoreReferenceResolver.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/IgnoreReferenceResolver.cs @@ -13,7 +13,7 @@ internal sealed class IgnoreReferenceResolver : ReferenceResolver internal override void PopReferenceForCycleDetection() { - Debug.Assert(_stackForCycleDetection != null); + Debug.Assert(_stackForCycleDetection is not null); _stackForCycleDetection.Pop(); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonConverter.MetadataHandling.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonConverter.MetadataHandling.cs index 0c8a7b66061067..eff7ab02fbd82b 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonConverter.MetadataHandling.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonConverter.MetadataHandling.cs @@ -37,7 +37,7 @@ public partial class JsonConverter else { // Standard discriminator-based resolution. - Debug.Assert(state.PolymorphicTypeDiscriminator != null); + Debug.Assert(state.PolymorphicTypeDiscriminator is not null); Debug.Assert(resolver.UsesTypeDiscriminators); resolver.TryGetDerivedJsonTypeInfo(state.PolymorphicTypeDiscriminator, out resolvedType); } @@ -83,8 +83,8 @@ public partial class JsonConverter internal JsonConverter? ResolvePolymorphicConverter(object value, JsonTypeInfo jsonTypeInfo, JsonSerializerOptions options, ref WriteStack state) { Debug.Assert(!IsValueType); - Debug.Assert(value != null && Type!.IsAssignableFrom(value.GetType())); - Debug.Assert(CanBePolymorphic || jsonTypeInfo.PolymorphicTypeResolver != null); + Debug.Assert(value is not null && Type!.IsAssignableFrom(value.GetType())); + Debug.Assert(CanBePolymorphic || jsonTypeInfo.PolymorphicTypeResolver is not null); Debug.Assert(state.PolymorphicTypeDiscriminator is null); JsonConverter? polymorphicConverter = null; @@ -153,7 +153,7 @@ internal bool TryHandleSerializedObjectReference(Utf8JsonWriter writer, object v { Debug.Assert(!IsValueType); Debug.Assert(!state.IsContinuation); - Debug.Assert(value != null); + Debug.Assert(value is not null); switch (options.ReferenceHandlingStrategy) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonConverter.cs index 8f8efccd306b5f..43e21d0ce82141 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonConverter.cs @@ -39,17 +39,15 @@ internal JsonConverter() internal ConverterStrategy ConverterStrategy { - get => _converterStrategy; + get; init { CanUseDirectReadOrWrite = value == ConverterStrategy.Value && IsInternalConverter; RequiresReadAhead = value == ConverterStrategy.Value; - _converterStrategy = value; + field = value; } } - private ConverterStrategy _converterStrategy; - /// /// Invoked by the base contructor to populate the initial value of the property. /// Used for declaring the default strategy for specific converter hierarchies without explicitly setting in a constructor. diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonConverterOfT.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonConverterOfT.cs index 6f42cbbcf76aed..d616d0abf6e65d 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonConverterOfT.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonConverterOfT.cs @@ -184,7 +184,7 @@ internal bool TryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSeriali int originalPropertyDepth = reader.CurrentDepth; long originalPropertyBytesConsumed = reader.BytesConsumed; - if (state.Current.NumberHandling != null && IsInternalConverterForNumberType) + if (state.Current.NumberHandling is not null && IsInternalConverterForNumberType) { value = ReadNumberWithCustomHandling(ref reader, state.Current.NumberHandling.Value, options); } @@ -245,7 +245,7 @@ internal bool TryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSeriali state.Current.OriginalDepth = reader.CurrentDepth; } - if (parentObj != null && propertyInfo != null && !propertyInfo.IsForTypeInfo) + if (parentObj is not null && propertyInfo is not null && !propertyInfo.IsForTypeInfo) { state.Current.HasParentObject = true; } @@ -345,7 +345,7 @@ internal bool TryWrite(Utf8JsonWriter writer, in T? value, JsonSerializerOptions int originalPropertyDepth = writer.CurrentDepth; - if (state.Current.NumberHandling != null && IsInternalConverterForNumberType) + if (state.Current.NumberHandling is not null && IsInternalConverterForNumberType) { WriteNumberWithCustomHandling(writer, value, state.Current.NumberHandling.Value); } @@ -444,7 +444,7 @@ value is not null && internal bool TryWriteDataExtensionProperty(Utf8JsonWriter writer, T value, JsonSerializerOptions options, ref WriteStack state) { - Debug.Assert(value != null); + Debug.Assert(value is not null); if (!IsInternalConverter) { @@ -454,7 +454,7 @@ internal bool TryWriteDataExtensionProperty(Utf8JsonWriter writer, T value, Json JsonDictionaryConverter? dictionaryConverter = this as JsonDictionaryConverter ?? (this as JsonMetadataServicesConverter)?.Converter as JsonDictionaryConverter; - if (dictionaryConverter == null) + if (dictionaryConverter is null) { // If not JsonDictionaryConverter then we are JsonObject. // Avoid a type reference to JsonObject and its converter to support trimming. diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Helpers.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Helpers.cs index d16b1a3edfca1d..c8b250f2ad1060 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Helpers.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Helpers.cs @@ -54,7 +54,7 @@ private static JsonTypeInfo GetTypeInfo(JsonSerializerOptions? options) private static JsonTypeInfo GetTypeInfo(JsonSerializerContext context, Type inputType) { - Debug.Assert(context != null); + Debug.Assert(context is not null); Debug.Assert(inputType != null); JsonTypeInfo? info = context.GetTypeInfo(inputType); @@ -144,7 +144,7 @@ static void ThrowUnableToCastValue(object? value) private static JsonTypeInfo> GetOrAddListTypeInfoForRootLevelValueMode(JsonTypeInfo elementTypeInfo) { - if (elementTypeInfo._asyncEnumerableRootLevelValueTypeInfo != null) + if (elementTypeInfo._asyncEnumerableRootLevelValueTypeInfo is not null) { return (JsonTypeInfo>)elementTypeInfo._asyncEnumerableRootLevelValueTypeInfo; } @@ -162,7 +162,7 @@ static void ThrowUnableToCastValue(object? value) private static JsonTypeInfo> GetOrAddListTypeInfoForArrayMode(JsonTypeInfo elementTypeInfo) { - if (elementTypeInfo._asyncEnumerableArrayTypeInfo != null) + if (elementTypeInfo._asyncEnumerableArrayTypeInfo is not null) { return (JsonTypeInfo>)elementTypeInfo._asyncEnumerableArrayTypeInfo; } @@ -181,7 +181,7 @@ static void ThrowUnableToCastValue(object? value) private static JsonTypeInfo> GetOrAddIAsyncEnumerableTypeInfoForSerialize(JsonTypeInfo elementTypeInfo) { - if (elementTypeInfo._asyncEnumerableRootLevelSerializer != null) + if (elementTypeInfo._asyncEnumerableRootLevelSerializer is not null) { return (JsonTypeInfo>)elementTypeInfo._asyncEnumerableRootLevelSerializer; } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.HandleMetadata.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.HandleMetadata.cs index a529ca0f5238ca..1eb4237f1f203b 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.HandleMetadata.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.HandleMetadata.cs @@ -178,7 +178,7 @@ internal static bool TryReadMetadata(JsonConverter converter, JsonTypeInfo jsonT // Found a $type property in a type that doesn't support polymorphism ThrowHelper.ThrowJsonException_MetadataUnexpectedProperty(propertyName, ref state); } - if (state.PolymorphicTypeDiscriminator != null) + if (state.PolymorphicTypeDiscriminator is not null) { // Found a duplicate $type property. ThrowHelper.ThrowJsonException_DuplicateMetadataProperty(state.Current.JsonPropertyName); @@ -262,7 +262,7 @@ internal static bool TryReadMetadata(JsonConverter converter, JsonTypeInfo jsonT ThrowHelper.ThrowJsonException_MetadataValueWasNotString(reader.TokenType); } - if (state.ReferenceId != null) + if (state.ReferenceId is not null) { ThrowHelper.ThrowNotSupportedException_ObjectWithParameterizedCtorRefMetadataNotSupported(s_refPropertyName, ref reader, ref state); } @@ -276,7 +276,7 @@ internal static bool TryReadMetadata(JsonConverter converter, JsonTypeInfo jsonT ThrowHelper.ThrowJsonException_MetadataValueWasNotString(reader.TokenType); } - if (state.ReferenceId != null) + if (state.ReferenceId is not null) { ThrowHelper.ThrowNotSupportedException_ObjectWithParameterizedCtorRefMetadataNotSupported(s_refPropertyName, ref reader, ref state); } @@ -285,7 +285,7 @@ internal static bool TryReadMetadata(JsonConverter converter, JsonTypeInfo jsonT break; case MetadataPropertyName.Type: - Debug.Assert(state.PolymorphicTypeDiscriminator == null); + Debug.Assert(state.PolymorphicTypeDiscriminator is null); switch (reader.TokenType) { @@ -414,7 +414,7 @@ internal static bool TryHandleReferenceFromJsonElement( } else if (property.EscapedNameEquals(s_idPropertyName)) { - if (state.ReferenceId != null) + if (state.ReferenceId is not null) { ThrowHelper.ThrowNotSupportedException_ObjectWithParameterizedCtorRefMetadataNotSupported(s_refPropertyName, ref reader, ref state); } @@ -431,7 +431,7 @@ internal static bool TryHandleReferenceFromJsonElement( } else if (property.EscapedNameEquals(s_refPropertyName)) { - if (state.ReferenceId != null) + if (state.ReferenceId is not null) { ThrowHelper.ThrowNotSupportedException_ObjectWithParameterizedCtorRefMetadataNotSupported(s_refPropertyName, ref reader, ref state); } @@ -478,7 +478,7 @@ internal static bool TryHandleReferenceFromJsonNode( } else if (property.Key == "$id") { - if (state.ReferenceId != null) + if (state.ReferenceId is not null) { ThrowHelper.ThrowNotSupportedException_ObjectWithParameterizedCtorRefMetadataNotSupported(s_refPropertyName, ref reader, ref state); } @@ -490,7 +490,7 @@ internal static bool TryHandleReferenceFromJsonNode( } else if (property.Key == "$ref") { - if (state.ReferenceId != null) + if (state.ReferenceId is not null) { ThrowHelper.ThrowNotSupportedException_ObjectWithParameterizedCtorRefMetadataNotSupported(s_refPropertyName, ref reader, ref state); } @@ -562,7 +562,7 @@ internal static void ValidateMetadataForArrayConverter(JsonConverter converter, internal static T ResolveReferenceId(ref ReadStack state) { Debug.Assert(!typeof(T).IsValueType); - Debug.Assert(state.ReferenceId != null); + Debug.Assert(state.ReferenceId is not null); string referenceId = state.ReferenceId; object value = state.ReferenceResolver.ResolveReference(referenceId); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.HandlePropertyName.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.HandlePropertyName.cs index ad85451b85a2e0..e2b65021f144db 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.HandlePropertyName.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.HandlePropertyName.cs @@ -55,7 +55,7 @@ internal static JsonPropertyInfo LookupProperty( if (createExtensionProperty) { - Debug.Assert(obj != null, "obj is null"); + Debug.Assert(obj is not null, "obj is null"); CreateExtensionDataProperty(obj, dataExtProperty, options); } @@ -107,7 +107,7 @@ internal static void CreateExtensionDataProperty( JsonPropertyInfo jsonPropertyInfo, JsonSerializerOptions options) { - Debug.Assert(jsonPropertyInfo != null); + Debug.Assert(jsonPropertyInfo is not null); object? extensionData = jsonPropertyInfo.GetValueAsObject(obj); @@ -116,7 +116,7 @@ internal static void CreateExtensionDataProperty( bool isReadOnlyDictionary = jsonPropertyInfo.PropertyType == typeof(IReadOnlyDictionary) || jsonPropertyInfo.PropertyType == typeof(IReadOnlyDictionary); - if (extensionData == null || (isReadOnlyDictionary && extensionData != null)) + if (extensionData is null || (isReadOnlyDictionary && extensionData is not null)) { // Create the appropriate dictionary type. We already verified the types. #if DEBUG @@ -137,7 +137,7 @@ internal static void CreateExtensionDataProperty( Func? createObjectForExtensionDataProp = jsonPropertyInfo.JsonTypeInfo.CreateObject ?? jsonPropertyInfo.JsonTypeInfo.CreateObjectForExtensionDataProperty; - if (createObjectForExtensionDataProp == null) + if (createObjectForExtensionDataProp is null) { // Avoid a reference to the JsonNode type for trimming if (jsonPropertyInfo.PropertyType.FullName == JsonTypeInfo.JsonObjectTypeName) @@ -148,7 +148,7 @@ internal static void CreateExtensionDataProperty( // create a Dictionary instance seeded with any existing contents. else if (jsonPropertyInfo.PropertyType == typeof(IReadOnlyDictionary)) { - if (extensionData != null) + if (extensionData is not null) { var existing = (IReadOnlyDictionary)extensionData; var newDict = new Dictionary(); @@ -162,13 +162,13 @@ internal static void CreateExtensionDataProperty( { extensionData = new Dictionary(); } - Debug.Assert(jsonPropertyInfo.Set != null); + Debug.Assert(jsonPropertyInfo.Set is not null); jsonPropertyInfo.Set(obj, extensionData); return; } else if (jsonPropertyInfo.PropertyType == typeof(IReadOnlyDictionary)) { - if (extensionData != null) + if (extensionData is not null) { var existing = (IReadOnlyDictionary)extensionData; var newDict = new Dictionary(); @@ -182,7 +182,7 @@ internal static void CreateExtensionDataProperty( { extensionData = new Dictionary(); } - Debug.Assert(jsonPropertyInfo.Set != null); + Debug.Assert(jsonPropertyInfo.Set is not null); jsonPropertyInfo.Set(obj, extensionData); return; } @@ -193,7 +193,7 @@ internal static void CreateExtensionDataProperty( } extensionData = createObjectForExtensionDataProp(); - Debug.Assert(jsonPropertyInfo.Set != null); + Debug.Assert(jsonPropertyInfo.Set is not null); jsonPropertyInfo.Set(obj, extensionData); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.String.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.String.cs index 99811bcfdab7e5..52c3e51f9f7967 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.String.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.String.cs @@ -401,7 +401,7 @@ public static partial class JsonSerializer } finally { - if (tempArray != null) + if (tempArray is not null) { utf8.Clear(); ArrayPool.Shared.Return(tempArray); @@ -432,7 +432,7 @@ public static partial class JsonSerializer } finally { - if (tempArray != null) + if (tempArray is not null) { utf8.Clear(); ArrayPool.Shared.Return(tempArray); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Element.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Element.cs index f89ef8dbafe66d..1481522f55c2de 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Element.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Element.cs @@ -141,7 +141,7 @@ private static JsonElement WriteElement(in TValue value, JsonTypeInfo internal static bool TryGetReferenceForValue(object currentValue, ref WriteStack state, Utf8JsonWriter writer) { - Debug.Assert(state.NewReferenceId == null); + Debug.Assert(state.NewReferenceId is null); string referenceId = state.ReferenceResolver.GetReference(currentValue, out bool alreadyExists); - Debug.Assert(referenceId != null); + Debug.Assert(referenceId is not null); if (alreadyExists) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerContext.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerContext.cs index b13763ae624c18..6c4d8ee7ef68a0 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerContext.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerContext.cs @@ -51,7 +51,7 @@ internal void AssociateWithOptions(JsonSerializerOptions options) /// bool IBuiltInJsonTypeInfoResolver.IsCompatibleWithOptions(JsonSerializerOptions options) { - Debug.Assert(options != null); + Debug.Assert(options is not null); JsonSerializerOptions? generatedSerializerOptions = GeneratedSerializerOptions; @@ -93,7 +93,7 @@ options.Encoder is null && /// protected JsonSerializerContext(JsonSerializerOptions? options) { - if (options != null) + if (options is not null) { options.VerifyMutable(); AssociateWithOptions(options); @@ -109,7 +109,7 @@ protected JsonSerializerContext(JsonSerializerOptions? options) JsonTypeInfo? IJsonTypeInfoResolver.GetTypeInfo(Type type, JsonSerializerOptions options) { - if (options != null && options != _options) + if (options is not null && options != _options) { ThrowHelper.ThrowInvalidOperationException_ResolverTypeInfoOptionsNotCompatible(); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Caching.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Caching.cs index ea8e1b5330aadf..26fb2fdf6ac602 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Caching.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Caching.cs @@ -161,7 +161,7 @@ public bool TryGetTypeInfo([NotNullWhen(true)] out JsonTypeInfo? typeInfo) internal bool TryGetTypeInfoCached(Type type, [NotNullWhen(true)] out JsonTypeInfo? typeInfo) { - if (_cachingContext == null) + if (_cachingContext is null) { typeInfo = null; return false; @@ -188,7 +188,7 @@ internal JsonTypeInfo GetTypeInfoForRootType(Type type, bool fallBackToNearestAn internal bool TryGetPolymorphicTypeInfoForRootType(object rootValue, [NotNullWhen(true)] out JsonTypeInfo? polymorphicTypeInfo) { - Debug.Assert(rootValue != null); + Debug.Assert(rootValue is not null); Type runtimeType = rootValue.GetType(); if (runtimeType != JsonTypeInfo.ObjectType) @@ -429,7 +429,7 @@ internal static class TrackedCachingContexts public static CachingContext GetOrCreate(JsonSerializerOptions options) { Debug.Assert(options.IsReadOnly, "Cannot create caching contexts for mutable JsonSerializerOptions instances"); - Debug.Assert(options._typeInfoResolver != null); + Debug.Assert(options._typeInfoResolver is not null); int hashCode = s_optionsComparer.GetHashCode(options); @@ -513,7 +513,7 @@ private sealed class EqualityComparer : IEqualityComparer { public bool Equals(JsonSerializerOptions? left, JsonSerializerOptions? right) { - Debug.Assert(left != null && right != null); + Debug.Assert(left is not null && right is not null); return left._dictionaryKeyPolicy == right._dictionaryKeyPolicy && diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.cs index f0eccec6b27c9a..345f596236470c 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.cs @@ -909,7 +909,7 @@ internal bool CanUseFastPathSerializationLogic get { Debug.Assert(IsReadOnly); - Debug.Assert(TypeInfoResolver != null); + Debug.Assert(TypeInfoResolver is not null); return _canUseFastPathSerializationLogic ??= TypeInfoResolver.IsCompatibleWithOptions(this); } } @@ -1028,7 +1028,7 @@ private void ConfigureForJsonSerializer() ThrowHelper.ThrowInvalidOperationException_JsonSerializerIsReflectionDisabled(); } - Debug.Assert(_typeInfoResolver != null); + Debug.Assert(_typeInfoResolver is not null); // NB preserve write order. _isReadOnly = true; _isConfiguredForJsonSerializer = true; @@ -1055,7 +1055,7 @@ private void ConfigureForJsonSerializer() JsonTypeInfo? info = resolver.GetTypeInfo(type, this); - if (info != null) + if (info is not null) { if (info.Type != type) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/DefaultJsonTypeInfoResolver.Converters.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/DefaultJsonTypeInfoResolver.Converters.cs index bc8f920f4efe24..fdc989a82a0166 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/DefaultJsonTypeInfoResolver.Converters.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/DefaultJsonTypeInfoResolver.Converters.cs @@ -118,7 +118,7 @@ private static JsonConverter GetBuiltInConverter(Type typeToConvert) } // Since the object and IEnumerable converters cover all types, we should have a converter. - Debug.Assert(converter != null); + Debug.Assert(converter is not null); return converter; } } @@ -153,10 +153,10 @@ internal static JsonConverter GetConverterForType(Type typeToConvert, JsonSerial JsonConverter? converter = options.GetConverterFromList(typeToConvert); // Priority 2: Attempt to get converter from [JsonConverter] on the type being converted. - if (resolveJsonConverterAttribute && converter == null) + if (resolveJsonConverterAttribute && converter is null) { JsonConverterAttribute? converterAttribute = typeToConvert.GetUniqueCustomAttribute(inherit: false); - if (converterAttribute != null) + if (converterAttribute is not null) { converter = GetConverterFromAttribute(converterAttribute, typeToConvert: typeToConvert, memberInfo: null, options); } @@ -188,7 +188,7 @@ private static JsonConverter GetConverterFromAttribute(JsonConverterAttribute co { // Allow the attribute to create the converter. converter = converterAttribute.CreateConverter(typeToConvert); - if (converter == null) + if (converter is null) { ThrowHelper.ThrowInvalidOperationException_SerializationConverterOnAttributeNotCompatible(declaringType, memberInfo, typeToConvert); } @@ -220,7 +220,7 @@ private static JsonConverter GetConverterFromAttribute(JsonConverterAttribute co converter = (JsonConverter)Activator.CreateInstance(converterType)!; } - Debug.Assert(converter != null); + Debug.Assert(converter is not null); if (!converter.CanConvert(typeToConvert)) { Type? underlyingType = Nullable.GetUnderlyingType(typeToConvert); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/DefaultJsonTypeInfoResolver.Helpers.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/DefaultJsonTypeInfoResolver.Helpers.cs index 5f34f749cee427..6264eca84c06c7 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/DefaultJsonTypeInfoResolver.Helpers.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/DefaultJsonTypeInfoResolver.Helpers.cs @@ -523,7 +523,7 @@ private static void AddMembersDeclaredBySuperType( continue; } - bool hasJsonIncludeAttribute = propertyInfo.GetCustomAttribute(inherit: false) != null; + bool hasJsonIncludeAttribute = propertyInfo.GetCustomAttribute(inherit: false) is not null; // Only include properties that either have a public getter or a public setter or have the JsonIncludeAttribute set. if (propertyInfo.GetMethod?.IsPublic == true || @@ -545,7 +545,7 @@ private static void AddMembersDeclaredBySuperType( foreach (FieldInfo fieldInfo in currentType.GetFields(AllInstanceMembers)) { - bool hasJsonIncludeAttribute = fieldInfo.GetCustomAttribute(inherit: false) != null; + bool hasJsonIncludeAttribute = fieldInfo.GetCustomAttribute(inherit: false) is not null; if (hasJsonIncludeAttribute || (fieldInfo.IsPublic && typeInfo.Options.IncludeFields)) { AddMember( @@ -576,13 +576,13 @@ private static void AddMember( ref JsonTypeInfo.PropertyHierarchyResolutionState state) { JsonPropertyInfo? jsonPropertyInfo = CreatePropertyInfo(typeInfo, typeToConvert, memberInfo, typeNamingPolicy, nullabilityCtx, typeIgnoreCondition, typeInfo.Options, shouldCheckForRequiredKeyword, hasJsonIncludeAttribute); - if (jsonPropertyInfo == null) + if (jsonPropertyInfo is null) { // ignored invalid property return; } - Debug.Assert(jsonPropertyInfo.Name != null); + Debug.Assert(jsonPropertyInfo.Name is not null); typeInfo.PropertyList.AddPropertyWithConflictResolution(jsonPropertyInfo, ref state); } @@ -735,7 +735,7 @@ private static void PopulatePropertyInfo( bool hasJsonIncludeAttribute, JsonNamingPolicy? typeNamingPolicy) { - Debug.Assert(jsonPropertyInfo.AttributeProvider == null); + Debug.Assert(jsonPropertyInfo.AttributeProvider is null); switch (jsonPropertyInfo.AttributeProvider = memberInfo) { @@ -765,7 +765,7 @@ private static void PopulatePropertyInfo( } jsonPropertyInfo.IgnoreCondition = ignoreCondition; - jsonPropertyInfo.IsExtensionData = memberInfo.GetCustomAttribute(inherit: false) != null; + jsonPropertyInfo.IsExtensionData = memberInfo.GetCustomAttribute(inherit: false) is not null; } private static void DeterminePropertyPolicies(JsonPropertyInfo propertyInfo, MemberInfo memberInfo) @@ -784,7 +784,7 @@ private static void DeterminePropertyName(JsonPropertyInfo propertyInfo, MemberI { JsonPropertyNameAttribute? nameAttribute = memberInfo.GetCustomAttribute(inherit: false); string? name; - if (nameAttribute != null) + if (nameAttribute is not null) { name = nameAttribute.Name; } @@ -799,7 +799,7 @@ private static void DeterminePropertyName(JsonPropertyInfo propertyInfo, MemberI : memberInfo.Name; } - if (name == null) + if (name is null) { ThrowHelper.ThrowInvalidOperationException_SerializerPropertyNameNull(propertyInfo); } @@ -810,7 +810,7 @@ private static void DeterminePropertyName(JsonPropertyInfo propertyInfo, MemberI private static void DeterminePropertyIsRequired(JsonPropertyInfo propertyInfo, MemberInfo memberInfo, bool shouldCheckForRequiredKeyword) { propertyInfo.IsRequired = - memberInfo.GetCustomAttribute(inherit: false) != null + memberInfo.GetCustomAttribute(inherit: false) is not null || (shouldCheckForRequiredKeyword && memberInfo.HasRequiredMemberAttribute()); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/DefaultJsonTypeInfoResolver.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/DefaultJsonTypeInfoResolver.cs index 724399929685c1..deec3a71091a81 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/DefaultJsonTypeInfoResolver.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/DefaultJsonTypeInfoResolver.cs @@ -63,7 +63,7 @@ public virtual JsonTypeInfo GetTypeInfo(Type type, JsonSerializerOptions options // This should be the last update operation in the resolver to avoid resetting the flag. typeInfo.IsCustomized = false; - if (_modifiers != null) + if (_modifiers is not null) { foreach (Action modifier in _modifiers) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.Converters.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.Converters.cs index 7a8429b4c9db5d..e2bd09a6d1cf53 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.Converters.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.Converters.cs @@ -326,7 +326,7 @@ public static JsonConverter GetEnumConverter(JsonSerializerOptions options internal static JsonConverter GetTypedConverter(JsonConverter converter) { JsonConverter? typedConverter = converter as JsonConverter; - if (typedConverter == null) + if (typedConverter is null) { throw new InvalidOperationException(SR.Format(SR.SerializationConverterNotCompatible, typedConverter, typeof(T))); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.Helpers.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.Helpers.cs index 6fe3d6fd8a6750..d103aaa9f7a550 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.Helpers.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.Helpers.cs @@ -31,7 +31,7 @@ private static JsonTypeInfo CreateCore(JsonSerializerOptions options, Json { JsonConverter converter = GetConverter(objectInfo); var typeInfo = new JsonTypeInfo(converter, options); - if (objectInfo.ObjectWithParameterizedConstructorCreator != null) + if (objectInfo.ObjectWithParameterizedConstructorCreator is not null) { // NB parameter metadata must be populated *before* property metadata // so that properties can be linked to their associated parameters. @@ -44,7 +44,7 @@ private static JsonTypeInfo CreateCore(JsonSerializerOptions options, Json typeInfo.CreateObjectForExtensionDataProperty = ((JsonTypeInfo)typeInfo).CreateObject; } - if (objectInfo.PropertyMetadataInitializer != null) + if (objectInfo.PropertyMetadataInitializer is not null) { typeInfo.SourceGenDelayedPropertyInitializer = objectInfo.PropertyMetadataInitializer; } @@ -79,7 +79,7 @@ private static JsonTypeInfo CreateCore( { ArgumentNullException.ThrowIfNull(collectionInfo); - converter = collectionInfo.SerializeHandler != null + converter = collectionInfo.SerializeHandler is not null ? new JsonMetadataServicesConverter(converter) : converter; @@ -106,12 +106,12 @@ private static JsonTypeInfo CreateCore( private static JsonConverter GetConverter(JsonObjectInfoValues objectInfo) { #pragma warning disable CS8714 // Nullability of type argument 'T' doesn't match 'notnull' constraint. - JsonConverter converter = objectInfo.ObjectWithParameterizedConstructorCreator != null + JsonConverter converter = objectInfo.ObjectWithParameterizedConstructorCreator is not null ? new LargeObjectWithParameterizedConstructorConverter() : new ObjectDefaultConverter(); #pragma warning restore CS8714 - return objectInfo.SerializeHandler != null + return objectInfo.SerializeHandler is not null ? new JsonMetadataServicesConverter(converter) : converter; } @@ -185,7 +185,7 @@ internal static void PopulateProperties(JsonTypeInfo typeInfo, JsonTypeInfo.Json { // [JsonInclude] property is inaccessible and the source generator // did not provide getter/setter delegates (e.g. older generator). - Debug.Assert(jsonPropertyInfo.MemberName != null, "MemberName is not set by source gen"); + Debug.Assert(jsonPropertyInfo.MemberName is not null, "MemberName is not set by source gen"); ThrowHelper.ThrowInvalidOperationException_JsonIncludeOnInaccessibleProperty(jsonPropertyInfo.MemberName, jsonPropertyInfo.DeclaringType); } @@ -249,11 +249,11 @@ private static void DeterminePropertyName( string? name; // Property name settings. - if (declaredJsonPropertyName != null) + if (declaredJsonPropertyName is not null) { name = declaredJsonPropertyName; } - else if (propertyInfo.Options.PropertyNamingPolicy == null) + else if (propertyInfo.Options.PropertyNamingPolicy is null) { name = declaredPropertyName; } @@ -263,7 +263,7 @@ private static void DeterminePropertyName( } // Compat: We need to do validation before we assign Name so that we get InvalidOperationException rather than ArgumentNullException - if (name == null) + if (name is null) { ThrowHelper.ThrowInvalidOperationException_SerializerPropertyNameNull(propertyInfo); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.cs index 29a31aeff4b5a6..8aa193d726e55d 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.cs @@ -33,7 +33,7 @@ public static JsonPropertyInfo CreatePropertyInfo(JsonSerializerOptions optio } string? propertyName = propertyInfo.PropertyName; - if (propertyName == null) + if (propertyName is null) { throw new ArgumentException(nameof(propertyInfo.PropertyName)); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonParameterInfo.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonParameterInfo.cs index 15702db934c73c..ebbd2f5100a883 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonParameterInfo.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonParameterInfo.cs @@ -95,7 +95,7 @@ public ICustomAttributeProvider? AttributeProvider get { // Use delayed initialization to ensure that reflection dependencies are pay-for-play. - Debug.Assert(MatchingProperty.DeclaringTypeInfo != null, "Declaring type metadata must have already been configured."); + Debug.Assert(MatchingProperty.DeclaringTypeInfo is not null, "Declaring type metadata must have already been configured."); ICustomAttributeProvider? parameterInfo = _attributeProvider; if (parameterInfo is null && MatchingProperty.DeclaringTypeInfo.ConstructorAttributeProvider is MethodBase ctorInfo) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonPolymorphismOptions.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonPolymorphismOptions.cs index 7da24b25bef402..becf6ba90899b6 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonPolymorphismOptions.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonPolymorphismOptions.cs @@ -13,9 +13,6 @@ namespace System.Text.Json.Serialization.Metadata public class JsonPolymorphismOptions { private DerivedTypeList? _derivedTypes; - private bool _ignoreUnrecognizedTypeDiscriminators; - private JsonUnknownDerivedTypeHandling _unknownDerivedTypeHandling; - private string? _typeDiscriminatorPropertyName; private bool _isConfigured; /// @@ -40,12 +37,12 @@ public JsonPolymorphismOptions() /// public bool IgnoreUnrecognizedTypeDiscriminators { - get => _ignoreUnrecognizedTypeDiscriminators; + get; set { VerifyMutable(); _isConfigured = true; - _ignoreUnrecognizedTypeDiscriminators = value; + field = value; } } @@ -57,12 +54,12 @@ public bool IgnoreUnrecognizedTypeDiscriminators /// public JsonUnknownDerivedTypeHandling UnknownDerivedTypeHandling { - get => _unknownDerivedTypeHandling; + get; set { VerifyMutable(); _isConfigured = true; - _unknownDerivedTypeHandling = value; + field = value; } } @@ -76,12 +73,12 @@ public JsonUnknownDerivedTypeHandling UnknownDerivedTypeHandling [AllowNull] public string TypeDiscriminatorPropertyName { - get => _typeDiscriminatorPropertyName ?? JsonSerializer.TypePropertyName; + get => field ?? JsonSerializer.TypePropertyName; set { VerifyMutable(); _isConfigured = true; - _typeDiscriminatorPropertyName = value; + field = value; } } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonPropertyInfo.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonPropertyInfo.cs index 622c94fdb92bc2..c508b4aa1a3a37 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonPropertyInfo.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonPropertyInfo.cs @@ -26,7 +26,7 @@ internal JsonConverter EffectiveConverter { get { - Debug.Assert(_effectiveConverter != null); + Debug.Assert(_effectiveConverter is not null); return _effectiveConverter; } } @@ -47,16 +47,14 @@ internal JsonConverter EffectiveConverter /// public JsonConverter? CustomConverter { - get => _customConverter; + get; set { VerifyMutable(); - _customConverter = value; + field = value; } } - private JsonConverter? _customConverter; - /// /// Gets or sets a getter delegate for the property. /// @@ -201,12 +199,12 @@ public ICustomAttributeProvider? AttributeProvider /// public JsonObjectCreationHandling? ObjectCreationHandling { - get => _objectCreationHandling; + get; set { VerifyMutable(); - if (value != null) + if (value is not null) { if (!JsonSerializer.IsValidCreationHandlingValue(value.Value)) { @@ -214,11 +212,10 @@ public JsonObjectCreationHandling? ObjectCreationHandling } } - _objectCreationHandling = value; + field = value; } } - private JsonObjectCreationHandling? _objectCreationHandling; internal JsonObjectCreationHandling EffectiveObjectCreationHandling { get; private set; } internal string? MemberName { get; set; } // Do not rename (legacy schema generation) @@ -316,7 +313,7 @@ public bool IsSetNullable /// public bool IsExtensionData { - get => _isExtensionDataProperty; + get; set { VerifyMutable(); @@ -326,12 +323,10 @@ public bool IsExtensionData ThrowHelper.ThrowInvalidOperationException_SerializationDataExtensionPropertyInvalid(this); } - _isExtensionDataProperty = value; + field = value; } } - private bool _isExtensionDataProperty; - /// /// Specifies whether the current property is required for deserialization to be successful. /// @@ -415,7 +410,7 @@ private protected void VerifyMutable() internal void Configure() { - Debug.Assert(DeclaringTypeInfo != null); + Debug.Assert(DeclaringTypeInfo is not null); Debug.Assert(!IsConfigured); if (IsIgnored) @@ -474,7 +469,7 @@ internal void Configure() private void ValidateAndCachePropertyName() { - Debug.Assert(Name != null); + Debug.Assert(Name is not null); if (Options.ReferenceHandlingStrategy is JsonKnownReferenceHandler.Preserve && this is { DeclaringType.IsValueType: false, IsIgnored: false, IsExtensionData: false } && @@ -493,7 +488,7 @@ private void ValidateAndCachePropertyName() private void DetermineIgnoreCondition() { - if (_ignoreCondition != null) + if (_ignoreCondition is not null) { // Do not apply global policy if already configured on the property level. return; @@ -525,12 +520,12 @@ private void DetermineIgnoreCondition() private void DetermineSerializationCapabilities() { - Debug.Assert(EffectiveConverter != null, "Must have calculated the effective converter."); + Debug.Assert(EffectiveConverter is not null, "Must have calculated the effective converter."); CanSerialize = HasGetter; CanDeserialize = HasSetter; Debug.Assert(MemberType is 0 or MemberTypes.Field or MemberTypes.Property); - if (MemberType == 0 || _ignoreCondition != null) + if (MemberType == 0 || _ignoreCondition is not null) { // No policy to be applied if either: // 1. JsonPropertyInfo is a custom instance (not generated via reflection or sourcegen). @@ -542,7 +537,7 @@ private void DetermineSerializationCapabilities() if ((EffectiveConverter.ConverterStrategy & (ConverterStrategy.Enumerable | ConverterStrategy.Dictionary)) != 0) { // Properties of collections types that only have setters are not supported. - if (Get == null && Set != null && !_isUserSpecifiedSetter) + if (Get is null && Set is not null && !_isUserSpecifiedSetter) { CanDeserialize = false; } @@ -551,7 +546,7 @@ private void DetermineSerializationCapabilities() { // For read-only properties of non-collection types, apply IgnoreReadOnlyProperties/Fields policy, // unless a `ShouldSerialize` predicate has been explicitly applied by the user (null or non-null). - if (Get != null && Set == null && IgnoreReadOnlyMember && !_isUserSpecifiedShouldSerialize) + if (Get is not null && Set is null && IgnoreReadOnlyMember && !_isUserSpecifiedShouldSerialize) { CanSerialize = false; } @@ -562,12 +557,12 @@ private void DetermineSerializationCapabilities() private void DetermineNumberHandlingForTypeInfo() { - Debug.Assert(DeclaringTypeInfo != null, "We should have ensured parent is assigned in JsonTypeInfo"); + Debug.Assert(DeclaringTypeInfo is not null, "We should have ensured parent is assigned in JsonTypeInfo"); Debug.Assert(!DeclaringTypeInfo.IsConfigured); JsonNumberHandling? declaringTypeNumberHandling = DeclaringTypeInfo.NumberHandling; - if (declaringTypeNumberHandling != null && declaringTypeNumberHandling != JsonNumberHandling.Strict && !EffectiveConverter.IsInternalConverter) + if (declaringTypeNumberHandling is not null && declaringTypeNumberHandling != JsonNumberHandling.Strict && !EffectiveConverter.IsInternalConverter) { ThrowHelper.ThrowInvalidOperationException_NumberHandlingOnPropertyInvalid(this); } @@ -590,9 +585,9 @@ private void DetermineNumberHandlingForTypeInfo() private void DetermineNumberHandlingForProperty() { - Debug.Assert(DeclaringTypeInfo != null, "We should have ensured parent is assigned in JsonTypeInfo"); + Debug.Assert(DeclaringTypeInfo is not null, "We should have ensured parent is assigned in JsonTypeInfo"); Debug.Assert(!IsConfigured, "Should not be called post-configuration."); - Debug.Assert(_jsonTypeInfo != null, "Must have already been determined on configuration."); + Debug.Assert(_jsonTypeInfo is not null, "Must have already been determined on configuration."); bool numberHandlingIsApplicable = NumberHandingIsApplicable(); @@ -617,12 +612,12 @@ private void DetermineNumberHandlingForProperty() private void DetermineEffectiveObjectCreationHandlingForProperty() { - Debug.Assert(EffectiveConverter != null, "Must have calculated the effective converter."); - Debug.Assert(DeclaringTypeInfo != null, "We should have ensured parent is assigned in JsonTypeInfo"); + Debug.Assert(EffectiveConverter is not null, "Must have calculated the effective converter."); + Debug.Assert(DeclaringTypeInfo is not null, "We should have ensured parent is assigned in JsonTypeInfo"); Debug.Assert(!IsConfigured, "Should not be called post-configuration."); JsonObjectCreationHandling effectiveObjectCreationHandling = JsonObjectCreationHandling.Replace; - if (ObjectCreationHandling == null) + if (ObjectCreationHandling is null) { // Consult type-level configuration, then global configuration. // Ignore global configuration if we're using a parameterized constructor. @@ -635,10 +630,10 @@ private void DetermineEffectiveObjectCreationHandlingForProperty() bool canPopulate = preferredCreationHandling == JsonObjectCreationHandling.Populate && EffectiveConverter.CanPopulate && - Get != null && - (!PropertyType.IsValueType || Set != null) && + Get is not null && + (!PropertyType.IsValueType || Set is not null) && !DeclaringTypeInfo.SupportsPolymorphicDeserialization && - !(Set == null && IgnoreReadOnlyMember); + !(Set is null && IgnoreReadOnlyMember); effectiveObjectCreationHandling = canPopulate ? JsonObjectCreationHandling.Populate : JsonObjectCreationHandling.Replace; } @@ -649,24 +644,24 @@ private void DetermineEffectiveObjectCreationHandlingForProperty() ThrowHelper.ThrowInvalidOperationException_ObjectCreationHandlingPopulateNotSupportedByConverter(this); } - if (Get == null) + if (Get is null) { ThrowHelper.ThrowInvalidOperationException_ObjectCreationHandlingPropertyMustHaveAGetter(this); } - if (PropertyType.IsValueType && Set == null) + if (PropertyType.IsValueType && Set is null) { ThrowHelper.ThrowInvalidOperationException_ObjectCreationHandlingPropertyValueTypeMustHaveASetter(this); } - Debug.Assert(_jsonTypeInfo != null); + Debug.Assert(_jsonTypeInfo is not null); Debug.Assert(_jsonTypeInfo.IsConfigurationStarted); if (JsonTypeInfo.SupportsPolymorphicDeserialization) { ThrowHelper.ThrowInvalidOperationException_ObjectCreationHandlingPropertyCannotAllowPolymorphicDeserialization(this); } - if (Set == null && IgnoreReadOnlyMember) + if (Set is null && IgnoreReadOnlyMember) { ThrowHelper.ThrowInvalidOperationException_ObjectCreationHandlingPropertyCannotAllowReadOnlyMember(this); } @@ -790,7 +785,7 @@ public string Name { get { - Debug.Assert(_name != null); + Debug.Assert(_name is not null); return _name; } set @@ -832,16 +827,14 @@ public string Name /// public int Order { - get => _order; + get; set { VerifyMutable(); - _order = value; + field = value; } } - private int _order; - internal bool ReadJsonAndAddExtensionProperty( object obj, scoped ref ReadStack state, @@ -958,12 +951,12 @@ internal bool TryGetPrePopulatedValue(scoped ref ReadStack state) return false; Debug.Assert(EffectiveConverter.CanPopulate, "Property is marked with Populate but converter cannot populate. This should have been validated in Configure"); - Debug.Assert(state.Parent.ReturnValue != null, "Parent object is null"); + Debug.Assert(state.Parent.ReturnValue is not null, "Parent object is null"); Debug.Assert(!state.Current.IsPopulating, "We've called TryGetPrePopulatedValue more than once"); object? value = Get!(state.Parent.ReturnValue); state.Current.ReturnValue = value; - state.Current.IsPopulating = value != null; - return value != null; + state.Current.IsPopulating = value is not null; + return value is not null; } internal JsonTypeInfo JsonTypeInfo @@ -1035,16 +1028,14 @@ internal JsonTypeInfo JsonTypeInfo /// public JsonNumberHandling? NumberHandling { - get => _numberHandling; + get; set { VerifyMutable(); - _numberHandling = value; + field = value; } } - private JsonNumberHandling? _numberHandling; - /// /// Number handling after considering options and declaring type number handling /// diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonPropertyInfoOfT.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonPropertyInfoOfT.cs index de34a5bb0b7fd5..a9bc21f9c1338f 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonPropertyInfoOfT.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonPropertyInfoOfT.cs @@ -132,7 +132,7 @@ internal override void AddJsonParameterInfo(JsonParameterInfoValues parameterInf { get { - Debug.Assert(_typedEffectiveConverter != null); + Debug.Assert(_typedEffectiveConverter is not null); return _typedEffectiveConverter; } } @@ -187,7 +187,7 @@ value is not null && { // If a reference cycle is detected, treat value as null. value = default!; - Debug.Assert(value == null); + Debug.Assert(value is null); } if (IgnoreDefaultValuesOnWrite) @@ -260,7 +260,7 @@ internal override bool GetMemberAndWriteJsonExtensionData(object obj, ref WriteS return true; } - if (value == null) + if (value is null) { success = true; } @@ -305,7 +305,7 @@ internal override bool ReadJsonAndSetMember(object obj, scoped ref ReadStack sta success = true; state.Current.MarkPropertyAsRead(this); } - else if (EffectiveConverter.CanUseDirectReadOrWrite && state.Current.NumberHandling == null) + else if (EffectiveConverter.CanUseDirectReadOrWrite && state.Current.NumberHandling is null) { // CanUseDirectReadOrWrite == false when using streams Debug.Assert(!state.IsContinuation); @@ -379,7 +379,7 @@ internal override bool ReadJsonAsObject(scoped ref ReadStack state, ref Utf8Json else { // Optimize for internal converters by avoiding the extra call to TryRead. - if (EffectiveConverter.CanUseDirectReadOrWrite && state.Current.NumberHandling == null) + if (EffectiveConverter.CanUseDirectReadOrWrite && state.Current.NumberHandling is null) { // CanUseDirectReadOrWrite == false when using streams Debug.Assert(!state.IsContinuation); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfo.Cache.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfo.Cache.cs index 15666c7a1d7464..317810f16fab3e 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfo.Cache.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfo.Cache.cs @@ -33,7 +33,7 @@ internal bool UsesParameterizedConstructor get { Debug.Assert(IsConfigured); - return _parameterCache != null; + return _parameterCache is not null; } } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfo.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfo.cs index 9483332a76f398..2dee14b0605c7c 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfo.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfo.cs @@ -36,11 +36,6 @@ public abstract partial class JsonTypeInfo internal BitArray? OptionalPropertiesMask { get; private set; } internal bool ShouldTrackRequiredProperties => OptionalPropertiesMask is not null; - private Action? _onSerializing; - private Action? _onSerialized; - private Action? _onDeserializing; - private Action? _onDeserialized; - internal JsonTypeInfo(Type type, JsonConverter converter, JsonSerializerOptions options) { Type = type; @@ -120,7 +115,7 @@ public Func? CreateObject /// public Action? OnSerializing { - get => _onSerializing; + get; set { VerifyMutable(); @@ -130,7 +125,7 @@ public Action? OnSerializing ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(Kind); } - _onSerializing = value; + field = value; } } @@ -150,7 +145,7 @@ public Action? OnSerializing /// public Action? OnSerialized { - get => _onSerialized; + get; set { VerifyMutable(); @@ -160,7 +155,7 @@ public Action? OnSerialized ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(Kind); } - _onSerialized = value; + field = value; } } @@ -180,7 +175,7 @@ public Action? OnSerialized /// public Action? OnDeserializing { - get => _onDeserializing; + get; set { VerifyMutable(); @@ -196,7 +191,7 @@ public Action? OnDeserializing ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOnDeserializingCallbacksNotSupported(Type); } - _onDeserializing = value; + field = value; } } @@ -216,7 +211,7 @@ public Action? OnDeserializing /// public Action? OnDeserialized { - get => _onDeserialized; + get; set { VerifyMutable(); @@ -226,7 +221,7 @@ public Action? OnDeserialized ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(Kind); } - _onDeserialized = value; + field = value; } } @@ -310,14 +305,14 @@ public JsonPolymorphismOptions? PolymorphismOptions { VerifyMutable(); - if (value != null) + if (value is not null) { if (Kind == JsonTypeInfoKind.None) { ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(Kind); } - if (value.DeclaringTypeInfo != null && value.DeclaringTypeInfo != this) + if (value.DeclaringTypeInfo is not null && value.DeclaringTypeInfo != this) { ThrowHelper.ThrowArgumentException_JsonPolymorphismOptionsAssociatedWithDifferentJsonTypeInfo(nameof(value)); } @@ -790,7 +785,7 @@ public JsonNumberHandling? NumberHandling /// public JsonUnmappedMemberHandling? UnmappedMemberHandling { - get => _unmappedMemberHandling; + get; set { VerifyMutable(); @@ -805,16 +800,12 @@ public JsonUnmappedMemberHandling? UnmappedMemberHandling throw new ArgumentOutOfRangeException(nameof(value)); } - _unmappedMemberHandling = value; + field = value; } } - private JsonUnmappedMemberHandling? _unmappedMemberHandling; - internal JsonUnmappedMemberHandling EffectiveUnmappedMemberHandling { get; private set; } - private JsonObjectCreationHandling? _preferredPropertyObjectCreationHandling; - /// /// Gets or sets the preferred value for properties contained in the type. /// @@ -834,7 +825,7 @@ public JsonUnmappedMemberHandling? UnmappedMemberHandling /// public JsonObjectCreationHandling? PreferredPropertyObjectCreationHandling { - get => _preferredPropertyObjectCreationHandling; + get; set { VerifyMutable(); @@ -849,7 +840,7 @@ public JsonObjectCreationHandling? PreferredPropertyObjectCreationHandling throw new ArgumentOutOfRangeException(nameof(value)); } - _preferredPropertyObjectCreationHandling = value; + field = value; } } @@ -866,7 +857,7 @@ public JsonObjectCreationHandling? PreferredPropertyObjectCreationHandling [EditorBrowsable(EditorBrowsableState.Never)] public IJsonTypeInfoResolver? OriginatingResolver { - get => _originatingResolver; + get; set { VerifyMutable(); @@ -879,12 +870,10 @@ public IJsonTypeInfoResolver? OriginatingResolver IsCustomized = false; } - _originatingResolver = value; + field = value; } } - private IJsonTypeInfoResolver? _originatingResolver; - /// /// Gets or sets an attribute provider corresponding to the deserialization constructor. /// @@ -1001,7 +990,7 @@ private void Configure() PropertyInfoForTypeInfo.Configure(); - if (PolymorphismOptions != null) + if (PolymorphismOptions is not null) { // This needs to be done before ConfigureProperties() is called // JsonPropertyInfo.Configure() must have this value available in order to detect Polymoprhic + cyclic class case @@ -1304,7 +1293,7 @@ private void DetermineIsCompatibleWithCurrentOptions() return; } - if (_properties != null) + if (_properties is not null) { foreach (JsonPropertyInfo property in _properties) { @@ -1569,7 +1558,7 @@ internal void ConfigureProperties() ThrowHelper.ThrowInvalidOperationException_ExtensionDataConflictsWithUnmappedMemberHandling(Type, property); } - if (ExtensionDataProperty != null) + if (ExtensionDataProperty is not null) { ThrowHelper.ThrowInvalidOperationException_SerializationDuplicateTypeAttribute(Type, typeof(JsonExtensionDataAttribute)); } @@ -1688,7 +1677,7 @@ internal void ConfigureConstructorParameters() if (ExtensionDataProperty is { AssociatedParameter: not null }) { - Debug.Assert(ExtensionDataProperty.MemberName != null, "Custom property info cannot be data extension property"); + Debug.Assert(ExtensionDataProperty.MemberName is not null, "Custom property info cannot be data extension property"); ThrowHelper.ThrowInvalidOperationException_ExtensionDataCannotBindToCtorParam(ExtensionDataProperty.MemberName, ExtensionDataProperty); } @@ -1861,7 +1850,7 @@ public void SortProperties() public void AddPropertyWithConflictResolution(JsonPropertyInfo jsonPropertyInfo, ref PropertyHierarchyResolutionState state) { Debug.Assert(!_jsonTypeInfo.IsConfigured); - Debug.Assert(jsonPropertyInfo.MemberName != null, "MemberName can be null in custom JsonPropertyInfo instances and should never be passed in this method"); + Debug.Assert(jsonPropertyInfo.MemberName is not null, "MemberName can be null in custom JsonPropertyInfo instances and should never be passed in this method"); // Algorithm should be kept in sync with the Roslyn equivalent in JsonSourceGenerator.Parser.cs string memberName = jsonPropertyInfo.MemberName; diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfoOfT.WriteHelpers.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfoOfT.WriteHelpers.cs index 6cae18c524a3f9..569b68d1c0ebb5 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfoOfT.WriteHelpers.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfoOfT.WriteHelpers.cs @@ -30,7 +30,7 @@ internal void Serialize( // Even though this is already handled by JsonMetadataServicesConverter, // this avoids creating a WriteStack and calling into the converter infrastructure. - Debug.Assert(SerializeHandler != null); + Debug.Assert(SerializeHandler is not null); Debug.Assert(Converter is JsonMetadataServicesConverter); SerializeHandler(writer, rootValue!); @@ -96,7 +96,7 @@ private async Task SerializeAsync( { // Short-circuit calls into SerializeHandler, if the `CanUseSerializeHandlerInStreaming` heuristic allows it. - Debug.Assert(SerializeHandler != null); + Debug.Assert(SerializeHandler is not null); Debug.Assert(CanUseSerializeHandler); Debug.Assert(Converter is JsonMetadataServicesConverter); @@ -256,7 +256,7 @@ internal void Serialize( { // Short-circuit calls into SerializeHandler, if the `CanUseSerializeHandlerInStreaming` heuristic allows it. - Debug.Assert(SerializeHandler != null); + Debug.Assert(SerializeHandler is not null); Debug.Assert(CanUseSerializeHandler); Debug.Assert(Converter is JsonMetadataServicesConverter); @@ -312,7 +312,7 @@ rootValue is not null && bufferWriter.WriteToStream(utf8Json); bufferWriter.Clear(); - Debug.Assert(state.PendingTask == null); + Debug.Assert(state.PendingTask is null); } while (!isFinalBlock); if (CanUseSerializeHandler) diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfoOfT.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfoOfT.cs index cfa297712edcb7..e338a51435f810 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfoOfT.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfoOfT.cs @@ -63,15 +63,15 @@ private protected override void SetCreateObject(Delegate? createObject) if (Kind == JsonTypeInfoKind.None) { - Debug.Assert(_createObject == null); - Debug.Assert(_typedCreateObject == null); + Debug.Assert(_createObject is null); + Debug.Assert(_typedCreateObject is null); ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(Kind); } if (!Converter.SupportsCreateObjectDelegate) { Debug.Assert(_createObject is null); - Debug.Assert(_typedCreateObject == null); + Debug.Assert(_typedCreateObject is null); ThrowHelper.ThrowInvalidOperationException_CreateObjectConverterNotCompatible(Type); } @@ -242,7 +242,7 @@ internal set { Debug.Assert(!IsReadOnly, "We should not mutate read-only JsonTypeInfo"); _serialize = value; - HasSerializeHandler = value != null; + HasSerializeHandler = value is not null; } } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfoResolverChain.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfoResolverChain.cs index 446ce3e26fc0c7..d52ea4e8e09713 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfoResolverChain.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfoResolverChain.cs @@ -15,7 +15,7 @@ protected override void OnCollectionModifying() foreach (IJsonTypeInfoResolver resolver in _list) { JsonTypeInfo? typeInfo = resolver.GetTypeInfo(type, options); - if (typeInfo != null) + if (typeInfo is not null) { return typeInfo; } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfoResolverWithAddedModifiers.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfoResolverWithAddedModifiers.cs index 2f84b357152f7d..dd75c2011866bd 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfoResolverWithAddedModifiers.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfoResolverWithAddedModifiers.cs @@ -30,7 +30,7 @@ public JsonTypeInfoResolverWithAddedModifiers WithAddedModifier(Action modifier in _modifiers) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/PolymorphicTypeResolver.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/PolymorphicTypeResolver.cs index 13f363674d0f09..9c2e2709fd397a 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/PolymorphicTypeResolver.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/PolymorphicTypeResolver.cs @@ -70,7 +70,7 @@ public PolymorphicTypeResolver(JsonSerializerOptions options, JsonPolymorphismOp if (UsesTypeDiscriminators) { - Debug.Assert(_discriminatorIdtoType != null, "Discriminator index must have been populated."); + Debug.Assert(_discriminatorIdtoType is not null, "Discriminator index must have been populated."); if (!converterCanHaveMetadata) { @@ -186,7 +186,7 @@ public bool TryGetDerivedJsonTypeInfo(object typeDiscriminator, [NotNullWhen(tru { Debug.Assert(typeDiscriminator is int or string); Debug.Assert(UsesTypeDiscriminators); - Debug.Assert(_discriminatorIdtoType != null); + Debug.Assert(_discriminatorIdtoType is not null); if (_discriminatorIdtoType.TryGetValue(typeDiscriminator, out DerivedJsonTypeInfo? result)) { @@ -277,7 +277,7 @@ public static bool IsSupportedDerivedType(Type baseType, Type? derivedType) => { Debug.Assert(typeInfo.IsConfigured); - if (typeInfo.PolymorphismOptions != null) + if (typeInfo.PolymorphismOptions is not null) { // Type defines its own polymorphic configuration. return null; @@ -289,7 +289,7 @@ public static bool IsSupportedDerivedType(Type baseType, Type? derivedType) => for (Type? candidate = typeInfo.Type.BaseType; candidate != null; candidate = candidate.BaseType) { JsonTypeInfo? candidateInfo = ResolveAncestorTypeInfo(candidate, typeInfo.Options); - if (candidateInfo?.PolymorphismOptions != null) + if (candidateInfo?.PolymorphismOptions is not null) { // stop on the first ancestor that has a match matchingResult = candidateInfo; @@ -301,9 +301,9 @@ public static bool IsSupportedDerivedType(Type baseType, Type? derivedType) => foreach (Type interfaceType in typeInfo.Type.GetInterfaces()) { JsonTypeInfo? candidateInfo = ResolveAncestorTypeInfo(interfaceType, typeInfo.Options); - if (candidateInfo?.PolymorphismOptions != null) + if (candidateInfo?.PolymorphismOptions is not null) { - if (matchingResult != null) + if (matchingResult is not null) { // Resolve any conflicting matches. if (matchingResult.Type.IsAssignableFrom(interfaceType)) diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/PreserveReferenceResolver.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/PreserveReferenceResolver.cs index a2bf1a53c5d401..861afeb1129e25 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/PreserveReferenceResolver.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/PreserveReferenceResolver.cs @@ -30,7 +30,7 @@ public PreserveReferenceResolver(bool writing) public override void AddReference(string referenceId, object value) { - Debug.Assert(_referenceIdToObjectMap != null); + Debug.Assert(_referenceIdToObjectMap is not null); if (!_referenceIdToObjectMap.TryAdd(referenceId, value)) { @@ -40,7 +40,7 @@ public override void AddReference(string referenceId, object value) public override string GetReference(object value, out bool alreadyExists) { - Debug.Assert(_objectToReferenceIdMap != null); + Debug.Assert(_objectToReferenceIdMap is not null); if (_objectToReferenceIdMap.TryGetValue(value, out string? referenceId)) { @@ -59,7 +59,7 @@ public override string GetReference(object value, out bool alreadyExists) public override object ResolveReference(string referenceId) { - Debug.Assert(_referenceIdToObjectMap != null); + Debug.Assert(_referenceIdToObjectMap is not null); if (!_referenceIdToObjectMap.TryGetValue(referenceId, out object? value)) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/ReadStack.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/ReadStack.cs index 23dd42c149cdc2..3b0ebc3f4a3d6f 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/ReadStack.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/ReadStack.cs @@ -218,7 +218,7 @@ public void Pop(bool success) public JsonConverter InitializePolymorphicReEntry(JsonTypeInfo derivedJsonTypeInfo) { Debug.Assert(!IsContinuation); - Debug.Assert(Current.PolymorphicJsonTypeInfo == null); + Debug.Assert(Current.PolymorphicJsonTypeInfo is null); Debug.Assert(Current.PolymorphicSerializationState == PolymorphicSerializationState.None); Current.PolymorphicJsonTypeInfo = Current.JsonTypeInfo; @@ -237,7 +237,7 @@ public JsonConverter InitializePolymorphicReEntry(JsonTypeInfo derivedJsonTypeIn /// public JsonConverter ResumePolymorphicReEntry() { - Debug.Assert(Current.PolymorphicJsonTypeInfo != null); + Debug.Assert(Current.PolymorphicJsonTypeInfo is not null); Debug.Assert(Current.PolymorphicSerializationState == PolymorphicSerializationState.PolymorphicReEntrySuspended); // Swap out the two values as we resume the polymorphic converter @@ -251,7 +251,7 @@ public JsonConverter ResumePolymorphicReEntry() /// public void ExitPolymorphicConverter(bool success) { - Debug.Assert(Current.PolymorphicJsonTypeInfo != null); + Debug.Assert(Current.PolymorphicJsonTypeInfo is not null); Debug.Assert(Current.PolymorphicSerializationState == PolymorphicSerializationState.PolymorphicReEntryStarted); // Swap out the two values as we exit the polymorphic converter @@ -291,7 +291,7 @@ static void AppendStackFrame(StringBuilder sb, ref ReadStackFrame frame) string? propertyName = GetPropertyName(ref frame); AppendPropertyName(sb, propertyName); - if (frame.JsonTypeInfo != null && frame.IsProcessingEnumerable()) + if (frame.JsonTypeInfo is not null && frame.IsProcessingEnumerable()) { if (frame.ReturnValue is not IEnumerable enumerable) { @@ -329,7 +329,7 @@ static int GetCount(IEnumerable enumerable) static void AppendPropertyName(StringBuilder sb, string? propertyName) { - if (propertyName != null) + if (propertyName is not null) { if (propertyName.AsSpan().ContainsSpecialCharacters()) { @@ -351,9 +351,9 @@ static void AppendPropertyName(StringBuilder sb, string? propertyName) // Attempt to get the JSON property name from the frame. byte[]? utf8PropertyName = frame.JsonPropertyName; - if (utf8PropertyName == null) + if (utf8PropertyName is null) { - if (frame.JsonPropertyNameAsString != null) + if (frame.JsonPropertyNameAsString is not null) { // Attempt to get the JSON property name set manually for dictionary // keys and KeyValuePair property names. @@ -367,7 +367,7 @@ static void AppendPropertyName(StringBuilder sb, string? propertyName) } } - if (utf8PropertyName != null) + if (utf8PropertyName is not null) { propertyName = Encoding.UTF8.GetString(utf8PropertyName); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/ReadStackFrame.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/ReadStackFrame.cs index 44cba58c54b578..76a32e8fc688d9 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/ReadStackFrame.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/ReadStackFrame.cs @@ -114,18 +114,12 @@ public void EndElement() /// /// Is the current object a Dictionary. /// - public bool IsProcessingDictionary() - { - return JsonTypeInfo.Kind is JsonTypeInfoKind.Dictionary; - } + public bool IsProcessingDictionary() => JsonTypeInfo.Kind is JsonTypeInfoKind.Dictionary; /// /// Is the current object an Enumerable. /// - public bool IsProcessingEnumerable() - { - return JsonTypeInfo.Kind is JsonTypeInfoKind.Enumerable; - } + public bool IsProcessingEnumerable() => JsonTypeInfo.Kind is JsonTypeInfoKind.Enumerable; [MethodImpl(MethodImplOptions.AggressiveInlining)] public void MarkPropertyAsRead(JsonPropertyInfo propertyInfo) diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/WriteStack.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/WriteStack.cs index 568f70b8e2f1fa..2f42db9f95b02f 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/WriteStack.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/WriteStack.cs @@ -121,7 +121,7 @@ public readonly ref WriteStackFrame Parent /// /// Whether the current frame needs to write out any metadata. /// - public readonly bool CurrentContainsMetadata => NewReferenceId != null || PolymorphicTypeDiscriminator != null; + public readonly bool CurrentContainsMetadata => NewReferenceId is not null || PolymorphicTypeDiscriminator is not null; private void EnsurePushCapacity() { @@ -154,7 +154,7 @@ internal void Initialize( JsonSerializerOptions options = jsonTypeInfo.Options; if (options.ReferenceHandlingStrategy != JsonKnownReferenceHandler.Unspecified) { - Debug.Assert(options.ReferenceHandler != null); + Debug.Assert(options.ReferenceHandler is not null); ReferenceResolver = options.ReferenceHandler.CreateResolver(writing: true); if (options.ReferenceHandlingStrategy == JsonKnownReferenceHandler.IgnoreCycles && @@ -418,7 +418,7 @@ static void AppendStackFrame(StringBuilder sb, ref WriteStackFrame frame) static void AppendPropertyName(StringBuilder sb, string? propertyName) { - if (propertyName != null) + if (propertyName is not null) { if (propertyName.AsSpan().ContainsSpecialCharacters()) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/ThrowHelper.Serialization.cs b/src/libraries/System.Text.Json/src/System/Text/Json/ThrowHelper.Serialization.cs index 7066f052edc21f..d514f7ea56c49c 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/ThrowHelper.Serialization.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/ThrowHelper.Serialization.cs @@ -153,11 +153,11 @@ public static void ThrowArgumentException_CannotSerializeInvalidType(string para { if (declaringType == null) { - Debug.Assert(propertyName == null); + Debug.Assert(propertyName is null); throw new ArgumentException(SR.Format(SR.CannotSerializeInvalidType, typeToConvert), paramName); } - Debug.Assert(propertyName != null); + Debug.Assert(propertyName is not null); throw new ArgumentException(SR.Format(SR.CannotSerializeInvalidMember, typeToConvert, propertyName, declaringType), paramName); } @@ -244,7 +244,7 @@ public static void ThrowInvalidOperationException_SerializationConverterOnAttrib [DoesNotReturn] public static void ThrowInvalidOperationException_SerializerOptionsReadOnly(JsonSerializerContext? context) { - string message = context == null + string message = context is null ? SR.SerializerOptionsReadOnly : SR.SerializerContextOptionsReadOnly; @@ -491,7 +491,7 @@ public static void ThrowInvalidOperationException_CreateObjectConverterNotCompat [DoesNotReturn] public static void ReThrowWithPath(scoped ref ReadStack state, JsonReaderException ex) { - Debug.Assert(ex.Path == null); + Debug.Assert(ex.Path is null); string path = state.JsonPath(); string message = ex.Message; @@ -851,7 +851,7 @@ public static void ThrowInvalidOperationException_MetadataReferenceOfTypeCannotB [DoesNotReturn] public static void ThrowInvalidOperationException_JsonPropertyInfoIsBoundToDifferentJsonTypeInfo(JsonPropertyInfo propertyInfo) { - Debug.Assert(propertyInfo.DeclaringTypeInfo != null, "We should not throw this exception when ParentTypeInfo is null"); + Debug.Assert(propertyInfo.DeclaringTypeInfo is not null, "We should not throw this exception when ParentTypeInfo is null"); throw new InvalidOperationException(SR.Format(SR.JsonPropertyInfoBoundToDifferentParent, propertyInfo.Name, propertyInfo.DeclaringTypeInfo.Type.FullName)); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/ThrowHelper.cs b/src/libraries/System.Text.Json/src/System/Text/Json/ThrowHelper.cs index 66601ee7b0b478..e23040acabef37 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/ThrowHelper.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/ThrowHelper.cs @@ -384,7 +384,7 @@ public static JsonException GetJsonReaderException(ref Utf8JsonReader json, Exce return new JsonReaderException(message, lineNumber, bytePositionInLine); } - private static bool IsPrintable(byte value) => value >= 0x20 && value < 0x7F; + private static bool IsPrintable(byte value) => value is >= 0x20 and < 0x7F; [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static string GetPrintableString(byte value) @@ -612,7 +612,7 @@ private static string GetResourceString(ExceptionResource resource, int currentD switch (resource) { case ExceptionResource.MismatchedObjectArray: - Debug.Assert(token == JsonConstants.CloseBracket || token == JsonConstants.CloseBrace); + Debug.Assert(token is JsonConstants.CloseBracket or JsonConstants.CloseBrace); message = (tokenType == JsonTokenType.PropertyName) ? SR.Format(SR.CannotWriteEndAfterProperty, (char)token) : SR.Format(SR.MismatchedObjectArray, (char)token); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/ValueQueue.cs b/src/libraries/System.Text.Json/src/System/Text/Json/ValueQueue.cs index 4b7677f41a9176..48f118415a9670 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/ValueQueue.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/ValueQueue.cs @@ -37,7 +37,7 @@ public void Enqueue(T value) goto default; default: - Debug.Assert(_multiple != null); + Debug.Assert(_multiple is not null); _multiple.Enqueue(value); break; } @@ -58,7 +58,7 @@ public bool TryDequeue([MaybeNullWhen(false)] out T? value) return true; default: - Debug.Assert(_multiple != null); + Debug.Assert(_multiple is not null); return _multiple.TryDequeue(out value); } } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/JsonWriterHelper.Escaping.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/JsonWriterHelper.Escaping.cs index bbfa1ad59fa359..616d45a7871baa 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/JsonWriterHelper.Escaping.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/JsonWriterHelper.Escaping.cs @@ -125,7 +125,7 @@ public static int GetMaxEscapedLength(int textLength, int firstIndexToEscape) private static void EscapeString(ReadOnlySpan value, Span destination, JavaScriptEncoder encoder, ref int consumed, ref int written, bool isFinalBlock) { - Debug.Assert(encoder != null); + Debug.Assert(encoder is not null); OperationStatus result = encoder.EncodeUtf8(value, destination, out int encoderBytesConsumed, out int encoderBytesWritten, isFinalBlock); @@ -154,7 +154,7 @@ public static void EscapeString(ReadOnlySpan value, Span destination written = indexOfFirstByteToEscape; consumed = indexOfFirstByteToEscape; - if (encoder != null) + if (encoder is not null) { destination = destination.Slice(indexOfFirstByteToEscape); value = value.Slice(indexOfFirstByteToEscape); @@ -249,7 +249,7 @@ private static void EscapeNextBytes(byte value, Span destination, ref int private static void EscapeString(ReadOnlySpan value, Span destination, JavaScriptEncoder encoder, ref int consumed, ref int written, bool isFinalBlock) { - Debug.Assert(encoder != null); + Debug.Assert(encoder is not null); OperationStatus result = encoder.Encode(value, destination, out int encoderBytesConsumed, out int encoderCharsWritten, isFinalBlock); @@ -278,7 +278,7 @@ public static void EscapeString(ReadOnlySpan value, Span destination written = indexOfFirstByteToEscape; consumed = indexOfFirstByteToEscape; - if (encoder != null) + if (encoder is not null) { destination = destination.Slice(indexOfFirstByteToEscape); value = value.Slice(indexOfFirstByteToEscape); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/JsonWriterHelper.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/JsonWriterHelper.cs index 89e8c82a8d068c..9504b30e27a4d7 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/JsonWriterHelper.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/JsonWriterHelper.cs @@ -212,7 +212,7 @@ internal static void ValidateNumber(ReadOnlySpan utf8FormattedNumber) val = utf8FormattedNumber[i]; } - if (val == 'e' || val == 'E') + if (val is (byte)'e' or (byte)'E') { i++; @@ -223,7 +223,7 @@ internal static void ValidateNumber(ReadOnlySpan utf8FormattedNumber) val = utf8FormattedNumber[i]; - if (val == '+' || val == '-') + if (val is (byte)'+' or (byte)'-') { i++; } @@ -324,7 +324,7 @@ internal static unsafe T WriteString(ReadOnlySpan utf8Value, WriteCallb } finally { - if (rented != null) + if (rented is not null) { ArrayPool.Shared.Return(rented); } @@ -359,7 +359,7 @@ internal static unsafe T WriteString(ReadOnlySpan utf8Value, WriteCallb } finally { - if (rented != null) + if (rented is not null) { ArrayPool.Shared.Return(rented); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Bytes.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Bytes.cs index 6634d5fef9f7cf..e75de82a857d08 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Bytes.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Bytes.cs @@ -148,7 +148,7 @@ private unsafe void WriteBase64EscapeProperty(ReadOnlySpan propertyName, R WriteBase64ByOptions(escapedPropertyName.Slice(0, written), bytes); - if (propertyArray != null) + if (propertyArray is not null) { ArrayPool.Shared.Return(propertyArray); } @@ -171,7 +171,7 @@ private unsafe void WriteBase64EscapeProperty(ReadOnlySpan utf8PropertyNam WriteBase64ByOptions(escapedPropertyName.Slice(0, written), bytes); - if (propertyArray != null) + if (propertyArray is not null) { ArrayPool.Shared.Return(propertyArray); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.DateTime.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.DateTime.cs index 0e61386aec9315..a5362a8f1a5dc2 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.DateTime.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.DateTime.cs @@ -155,7 +155,7 @@ private unsafe void WriteStringEscapeProperty(ReadOnlySpan propertyName, D WriteStringByOptions(escapedPropertyName.Slice(0, written), value); - if (propertyArray != null) + if (propertyArray is not null) { ArrayPool.Shared.Return(propertyArray); } @@ -178,7 +178,7 @@ private unsafe void WriteStringEscapeProperty(ReadOnlySpan utf8PropertyNam WriteStringByOptions(escapedPropertyName.Slice(0, written), value); - if (propertyArray != null) + if (propertyArray is not null) { ArrayPool.Shared.Return(propertyArray); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.DateTimeOffset.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.DateTimeOffset.cs index 0866fca73a569d..6cc5041475bef3 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.DateTimeOffset.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.DateTimeOffset.cs @@ -154,7 +154,7 @@ private unsafe void WriteStringEscapeProperty(ReadOnlySpan propertyName, D WriteStringByOptions(escapedPropertyName.Slice(0, written), value); - if (propertyArray != null) + if (propertyArray is not null) { ArrayPool.Shared.Return(propertyArray); } @@ -177,7 +177,7 @@ private unsafe void WriteStringEscapeProperty(ReadOnlySpan utf8PropertyNam WriteStringByOptions(escapedPropertyName.Slice(0, written), value); - if (propertyArray != null) + if (propertyArray is not null) { ArrayPool.Shared.Return(propertyArray); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Decimal.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Decimal.cs index 78899594230658..fe19cc2f5fa38a 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Decimal.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Decimal.cs @@ -154,7 +154,7 @@ private unsafe void WriteNumberEscapeProperty(ReadOnlySpan propertyName, d WriteNumberByOptions(escapedPropertyName.Slice(0, written), value); - if (propertyArray != null) + if (propertyArray is not null) { ArrayPool.Shared.Return(propertyArray); } @@ -177,7 +177,7 @@ private unsafe void WriteNumberEscapeProperty(ReadOnlySpan utf8PropertyNam WriteNumberByOptions(escapedPropertyName.Slice(0, written), value); - if (propertyArray != null) + if (propertyArray is not null) { ArrayPool.Shared.Return(propertyArray); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Double.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Double.cs index b1de9a53a86713..2e83ccfd2b0d11 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Double.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Double.cs @@ -158,7 +158,7 @@ private unsafe void WriteNumberEscapeProperty(ReadOnlySpan propertyName, d WriteNumberByOptions(escapedPropertyName.Slice(0, written), value); - if (propertyArray != null) + if (propertyArray is not null) { ArrayPool.Shared.Return(propertyArray); } @@ -181,7 +181,7 @@ private unsafe void WriteNumberEscapeProperty(ReadOnlySpan utf8PropertyNam WriteNumberByOptions(escapedPropertyName.Slice(0, written), value); - if (propertyArray != null) + if (propertyArray is not null) { ArrayPool.Shared.Return(propertyArray); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Float.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Float.cs index 3b118ff46ccc5a..e78472e37cfa1c 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Float.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Float.cs @@ -158,7 +158,7 @@ private unsafe void WriteNumberEscapeProperty(ReadOnlySpan propertyName, f WriteNumberByOptions(escapedPropertyName.Slice(0, written), value); - if (propertyArray != null) + if (propertyArray is not null) { ArrayPool.Shared.Return(propertyArray); } @@ -181,7 +181,7 @@ private unsafe void WriteNumberEscapeProperty(ReadOnlySpan utf8PropertyNam WriteNumberByOptions(escapedPropertyName.Slice(0, written), value); - if (propertyArray != null) + if (propertyArray is not null) { ArrayPool.Shared.Return(propertyArray); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.FormattedNumber.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.FormattedNumber.cs index 596693ca089f8c..d9422c857f337c 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.FormattedNumber.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.FormattedNumber.cs @@ -128,7 +128,7 @@ private unsafe void WriteNumberEscapeProperty(ReadOnlySpan propertyName, R WriteNumberByOptions(escapedPropertyName.Slice(0, written), value); - if (propertyArray != null) + if (propertyArray is not null) { ArrayPool.Shared.Return(propertyArray); } @@ -151,7 +151,7 @@ private unsafe void WriteNumberEscapeProperty(ReadOnlySpan utf8PropertyNam WriteNumberByOptions(escapedPropertyName.Slice(0, written), value); - if (propertyArray != null) + if (propertyArray is not null) { ArrayPool.Shared.Return(propertyArray); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Guid.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Guid.cs index db28f991fcb69d..146579f182d9c8 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Guid.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Guid.cs @@ -154,7 +154,7 @@ private unsafe void WriteStringEscapeProperty(ReadOnlySpan propertyName, G WriteStringByOptions(escapedPropertyName.Slice(0, written), value); - if (propertyArray != null) + if (propertyArray is not null) { ArrayPool.Shared.Return(propertyArray); } @@ -177,7 +177,7 @@ private unsafe void WriteStringEscapeProperty(ReadOnlySpan utf8PropertyNam WriteStringByOptions(escapedPropertyName.Slice(0, written), value); - if (propertyArray != null) + if (propertyArray is not null) { ArrayPool.Shared.Return(propertyArray); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Literal.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Literal.cs index 114496443b3daf..f757f3709e6082 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Literal.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Literal.cs @@ -273,7 +273,7 @@ private unsafe void WriteLiteralEscapeProperty(ReadOnlySpan propertyName, WriteLiteralByOptions(escapedPropertyName.Slice(0, written), value); - if (propertyArray != null) + if (propertyArray is not null) { ArrayPool.Shared.Return(propertyArray); } @@ -296,7 +296,7 @@ private unsafe void WriteLiteralEscapeProperty(ReadOnlySpan utf8PropertyNa WriteLiteralByOptions(escapedPropertyName.Slice(0, written), value); - if (propertyArray != null) + if (propertyArray is not null) { ArrayPool.Shared.Return(propertyArray); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.SignedNumber.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.SignedNumber.cs index c8193930b416d8..757b0f8eab5cc8 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.SignedNumber.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.SignedNumber.cs @@ -227,7 +227,7 @@ private unsafe void WriteNumberEscapeProperty(ReadOnlySpan propertyName, l WriteNumberByOptions(escapedPropertyName.Slice(0, written), value); - if (propertyArray != null) + if (propertyArray is not null) { ArrayPool.Shared.Return(propertyArray); } @@ -250,7 +250,7 @@ private unsafe void WriteNumberEscapeProperty(ReadOnlySpan utf8PropertyNam WriteNumberByOptions(escapedPropertyName.Slice(0, written), value); - if (propertyArray != null) + if (propertyArray is not null) { ArrayPool.Shared.Return(propertyArray); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.String.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.String.cs index ce9ceab57e9d1e..53c46a91498de5 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.String.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.String.cs @@ -134,7 +134,7 @@ private unsafe void WriteStringEscapeProperty(scoped ReadOnlySpan property WriteStringByOptionsPropertyName(propertyName); - if (propertyArray != null) + if (propertyArray is not null) { ArrayPool.Shared.Return(propertyArray); } @@ -293,7 +293,7 @@ private unsafe void WriteStringEscapeProperty(scoped ReadOnlySpan utf8Prop WriteStringByOptionsPropertyName(utf8PropertyName); - if (propertyArray != null) + if (propertyArray is not null) { ArrayPool.Shared.Return(propertyArray); } @@ -483,7 +483,7 @@ public void WriteString(string propertyName, string? value) { ArgumentNullException.ThrowIfNull(propertyName); - if (value == null) + if (value is null) { WriteNull(propertyName.AsSpan()); } @@ -563,7 +563,7 @@ public void WriteString(ReadOnlySpan utf8PropertyName, ReadOnlySpan /// public void WriteString(JsonEncodedText propertyName, string? value) { - if (value == null) + if (value is null) { WriteNull(propertyName); } @@ -809,7 +809,7 @@ private void WriteStringHelperEscapeProperty(ReadOnlySpan propertyName, Re /// public void WriteString(ReadOnlySpan propertyName, string? value) { - if (value == null) + if (value is null) { WriteNull(propertyName); } @@ -881,7 +881,7 @@ private void WriteStringHelperEscapeProperty(ReadOnlySpan utf8PropertyName /// public void WriteString(ReadOnlySpan utf8PropertyName, string? value) { - if (value == null) + if (value is null) { WriteNull(utf8PropertyName); } @@ -908,7 +908,7 @@ private unsafe void WriteStringEscapeValueOnly(ReadOnlySpan escapedPropert WriteStringByOptions(escapedPropertyName, escapedValue.Slice(0, written)); - if (valueArray != null) + if (valueArray is not null) { ArrayPool.Shared.Return(valueArray); } @@ -931,7 +931,7 @@ private unsafe void WriteStringEscapeValueOnly(ReadOnlySpan escapedPropert WriteStringByOptions(escapedPropertyName, escapedValue.Slice(0, written)); - if (valueArray != null) + if (valueArray is not null) { ArrayPool.Shared.Return(valueArray); } @@ -954,7 +954,7 @@ private unsafe void WriteStringEscapePropertyOnly(ReadOnlySpan propertyNam WriteStringByOptions(escapedPropertyName.Slice(0, written), escapedValue); - if (propertyArray != null) + if (propertyArray is not null) { ArrayPool.Shared.Return(propertyArray); } @@ -977,7 +977,7 @@ private unsafe void WriteStringEscapePropertyOnly(ReadOnlySpan utf8Propert WriteStringByOptions(escapedPropertyName.Slice(0, written), escapedValue); - if (propertyArray != null) + if (propertyArray is not null) { ArrayPool.Shared.Return(propertyArray); } @@ -1108,12 +1108,12 @@ private unsafe void WriteStringEscapePropertyOrValue(scoped ReadOnlySpan p WriteStringByOptions(propertyName, value); - if (valueArray != null) + if (valueArray is not null) { ArrayPool.Shared.Return(valueArray); } - if (propertyArray != null) + if (propertyArray is not null) { ArrayPool.Shared.Return(propertyArray); } @@ -1168,12 +1168,12 @@ private unsafe void WriteStringEscapePropertyOrValue(scoped ReadOnlySpan u WriteStringByOptions(utf8PropertyName, utf8Value); - if (valueArray != null) + if (valueArray is not null) { ArrayPool.Shared.Return(valueArray); } - if (propertyArray != null) + if (propertyArray is not null) { ArrayPool.Shared.Return(propertyArray); } @@ -1228,12 +1228,12 @@ private unsafe void WriteStringEscapePropertyOrValue(scoped ReadOnlySpan p WriteStringByOptions(propertyName, utf8Value); - if (valueArray != null) + if (valueArray is not null) { ArrayPool.Shared.Return(valueArray); } - if (propertyArray != null) + if (propertyArray is not null) { ArrayPool.Shared.Return(propertyArray); } @@ -1288,12 +1288,12 @@ private unsafe void WriteStringEscapePropertyOrValue(scoped ReadOnlySpan u WriteStringByOptions(utf8PropertyName, value); - if (valueArray != null) + if (valueArray is not null) { ArrayPool.Shared.Return(valueArray); } - if (propertyArray != null) + if (propertyArray is not null) { ArrayPool.Shared.Return(propertyArray); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.UnsignedNumber.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.UnsignedNumber.cs index a6f60827847f05..4020b29cfe4f52 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.UnsignedNumber.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.UnsignedNumber.cs @@ -236,7 +236,7 @@ private unsafe void WriteNumberEscapeProperty(ReadOnlySpan propertyName, u WriteNumberByOptions(escapedPropertyName.Slice(0, written), value); - if (propertyArray != null) + if (propertyArray is not null) { ArrayPool.Shared.Return(propertyArray); } @@ -259,7 +259,7 @@ private unsafe void WriteNumberEscapeProperty(ReadOnlySpan utf8PropertyNam WriteNumberByOptions(escapedPropertyName.Slice(0, written), value); - if (propertyArray != null) + if (propertyArray is not null) { ArrayPool.Shared.Return(propertyArray); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Raw.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Raw.cs index 965141d3d628fc..6658a7476425db 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Raw.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Raw.cs @@ -217,7 +217,7 @@ private unsafe void TranscodeAndWriteRawValue(ReadOnlySpan json, bool skip } finally { - if (tempArray != null) + if (tempArray is not null) { utf8Json.Clear(); ArrayPool.Shared.Return(tempArray); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.String.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.String.cs index d629f98ebc4e76..e713a1267ed130 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.String.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.String.cs @@ -46,7 +46,7 @@ public void WriteStringValue(JsonEncodedText value) /// public void WriteStringValue(string? value) { - if (value == null) + if (value is null) { WriteNullValue(); } @@ -116,7 +116,7 @@ private void WriteStringByOptions(ReadOnlySpan value, int maxRequiredBytes // TODO: https://github.com/dotnet/runtime/issues/29293 private void WriteStringMinimized(ReadOnlySpan escapedValue, int maxRequiredBytes) { - Debug.Assert(maxRequiredBytes >= 0 && maxRequiredBytes < int.MaxValue - 3); + Debug.Assert(maxRequiredBytes is >= 0 and < int.MaxValue - 3); // 2 quotes + optional 1 list separator, plus precomputed max bytes for the payload. int maxRequired = maxRequiredBytes + 3; @@ -199,7 +199,7 @@ private unsafe void WriteStringEscapeValue(ReadOnlySpan value, int firstEs WriteStringByOptions(escapedValue.Slice(0, written), requiredBytes); - if (valueArray != null) + if (valueArray is not null) { ArrayPool.Shared.Return(valueArray); } @@ -346,7 +346,7 @@ private unsafe void WriteStringEscapeValue(ReadOnlySpan utf8Value, int fir WriteStringByOptions(escapedValue.Slice(0, written)); - if (valueArray != null) + if (valueArray is not null) { ArrayPool.Shared.Return(valueArray); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.StringSegment.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.StringSegment.cs index fe06a0f57a921c..1012fb31bb4999 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.StringSegment.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.StringSegment.cs @@ -155,7 +155,7 @@ private unsafe void WriteStringSegmentEscapeValue(ReadOnlySpan value, int PartialUtf16StringData = value.Slice(consumed); } - if (valueArray != null) + if (valueArray is not null) { ArrayPool.Shared.Return(valueArray); } @@ -321,7 +321,7 @@ private unsafe void WriteStringSegmentEscapeValue(ReadOnlySpan utf8Value, PartialUtf8StringData = utf8Value.Slice(consumed); } - if (valueArray != null) + if (valueArray is not null) { ArrayPool.Shared.Return(valueArray); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.cs index 1f8ce040a5c223..a03476fecd9c74 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.cs @@ -299,7 +299,7 @@ public void Reset(Stream utf8Json) { CheckNotDisposed(); - if (utf8Json == null) + if (utf8Json is null) { throw new ArgumentNullException(nameof(utf8Json)); } @@ -310,7 +310,7 @@ public void Reset(Stream utf8Json) } _stream = utf8Json; - if (_arrayBufferWriter == null) + if (_arrayBufferWriter is null) { _arrayBufferWriter = new ArrayBufferWriter(); } @@ -425,10 +425,10 @@ private void ResetHelper() private void CheckNotDisposed() { - if (_stream == null) + if (_stream is null) { // The conditions are ordered with stream first as that would be the most common mode - if (_output == null) + if (_output is null) { ThrowHelper.ThrowObjectDisposedException_Utf8JsonWriter(); } @@ -451,9 +451,9 @@ public void Flush() _memory = default; - if (_stream != null) + if (_stream is not null) { - Debug.Assert(_arrayBufferWriter != null); + Debug.Assert(_arrayBufferWriter is not null); if (BytesPending != 0) { _arrayBufferWriter.Advance(BytesPending); @@ -472,7 +472,7 @@ public void Flush() } else { - Debug.Assert(_output != null); + Debug.Assert(_output is not null); if (BytesPending != 0) { _output.Advance(BytesPending); @@ -496,10 +496,10 @@ public void Flush() /// public void Dispose() { - if (_stream == null) + if (_stream is null) { // The conditions are ordered with stream first as that would be the most common mode - if (_output == null) + if (_output is null) { return; } @@ -527,10 +527,10 @@ public void Dispose() /// public async ValueTask DisposeAsync() { - if (_stream == null) + if (_stream is null) { // The conditions are ordered with stream first as that would be the most common mode - if (_output == null) + if (_output is null) { return; } @@ -560,9 +560,9 @@ public async Task FlushAsync(CancellationToken cancellationToken = default) _memory = default; - if (_stream != null) + if (_stream is not null) { - Debug.Assert(_arrayBufferWriter != null); + Debug.Assert(_arrayBufferWriter is not null); if (BytesPending != 0) { _arrayBufferWriter.Advance(BytesPending); @@ -577,7 +577,7 @@ public async Task FlushAsync(CancellationToken cancellationToken = default) } else { - Debug.Assert(_output != null); + Debug.Assert(_output is not null); if (BytesPending != 0) { _output.Advance(BytesPending); @@ -873,7 +873,7 @@ private unsafe void WriteStartEscapeProperty(ReadOnlySpan utf8PropertyName WriteStartByOptions(escapedPropertyName.Slice(0, written), token); - if (propertyArray != null) + if (propertyArray is not null) { ArrayPool.Shared.Return(propertyArray); } @@ -1022,7 +1022,7 @@ private unsafe void WriteStartEscapeProperty(ReadOnlySpan propertyName, by WriteStartByOptions(escapedPropertyName.Slice(0, written), token); - if (propertyArray != null) + if (propertyArray is not null) { ArrayPool.Shared.Return(propertyArray); } @@ -1217,9 +1217,9 @@ private void Grow(int requiredSize) Debug.Assert(BytesPending != 0); - if (_stream != null) + if (_stream is not null) { - Debug.Assert(_arrayBufferWriter != null); + Debug.Assert(_arrayBufferWriter is not null); int needed = BytesPending + sizeHint; JsonHelpers.ValidateInt32MaxArrayLength((uint)needed); @@ -1230,7 +1230,7 @@ private void Grow(int requiredSize) } else { - Debug.Assert(_output != null); + Debug.Assert(_output is not null); _output.Advance(BytesPending); BytesCommitted += BytesPending; @@ -1252,15 +1252,15 @@ private void FirstCallToGetMemory(int requiredSize) int sizeHint = Math.Max(InitialGrowthSize, requiredSize); - if (_stream != null) + if (_stream is not null) { - Debug.Assert(_arrayBufferWriter != null); + Debug.Assert(_arrayBufferWriter is not null); _memory = _arrayBufferWriter.GetMemory(sizeHint); Debug.Assert(_memory.Length >= sizeHint); } else { - Debug.Assert(_output != null); + Debug.Assert(_output is not null); _memory = _output.GetMemory(sizeHint); if (_memory.Length < sizeHint) diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriterCache.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriterCache.cs index 47a6f46d7be2b6..4340918308564e 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriterCache.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriterCache.cs @@ -63,7 +63,7 @@ public static Utf8JsonWriter RentWriter(JsonSerializerOptions options, IBufferWr public static void ReturnWriterAndBuffer(Utf8JsonWriter writer, PooledByteBufferWriter bufferWriter) { - Debug.Assert(t_threadLocalState != null); + Debug.Assert(t_threadLocalState is not null); ThreadLocalState state = t_threadLocalState; writer.ResetAllStateForCacheReuse(); @@ -75,7 +75,7 @@ public static void ReturnWriterAndBuffer(Utf8JsonWriter writer, PooledByteBuffer public static void ReturnWriter(Utf8JsonWriter writer) { - Debug.Assert(t_threadLocalState != null); + Debug.Assert(t_threadLocalState is not null); ThreadLocalState state = t_threadLocalState; writer.ResetAllStateForCacheReuse();