From 473a7721bd67cca8fef1ecc37da1951a1c180022 Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Mon, 23 Oct 2017 10:33:35 +1300 Subject: [PATCH] -Refactor --- Src/Newtonsoft.Json/Linq/JObject.Async.cs | 2 +- .../Serialization/CamelCaseNamingStrategy.cs | 27 +++++++++++- .../Serialization/DefaultContractResolver.cs | 34 ++++++--------- .../Serialization/DefaultReferenceResolver.cs | 15 +++---- .../Serialization/JsonArrayContract.cs | 8 ++-- .../Serialization/JsonDictionaryContract.cs | 13 +++--- .../Serialization/JsonDynamicContract.cs | 3 -- .../Serialization/JsonFormatterConverter.cs | 3 +- .../Serialization/JsonPropertyCollection.cs | 3 +- .../JsonSerializerInternalWriter.cs | 35 +++++---------- .../Serialization/NamingStrategy.cs | 27 +++++++++++- .../Serialization/SnakeCaseNamingStrategy.cs | 27 +++++++++++- .../Serialization/TraceJsonReader.cs | 36 +++++++++++++--- .../Serialization/TraceJsonWriter.cs | 27 +++++++++++- .../Utilities/BidirectionalDictionary.cs | 7 +-- .../Utilities/CollectionUtils.cs | 3 +- .../Utilities/CollectionWrapper.cs | 3 +- Src/Newtonsoft.Json/Utilities/ConvertUtils.cs | 16 ++++--- .../Utilities/DateTimeUtils.cs | 26 +++-------- .../Utilities/DictionaryWrapper.cs | 2 +- Src/Newtonsoft.Json/Utilities/DynamicProxy.cs | 4 -- .../Utilities/DynamicProxyMetaObject.cs | 2 +- .../DynamicReflectionDelegateFactory.cs | 4 +- Src/Newtonsoft.Json/Utilities/EnumUtils.cs | 9 ++-- Src/Newtonsoft.Json/Utilities/EnumValue.cs | 12 ++---- .../ExpressionReflectionDelegateFactory.cs | 5 +-- .../Utilities/JsonTokenUtils.cs | 3 -- .../Utilities/MiscellaneousUtils.cs | 8 +--- .../Utilities/ReflectionDelegateFactory.cs | 12 ++---- .../Utilities/ReflectionObject.cs | 1 - .../Utilities/ReflectionUtils.cs | 43 ++++++------------- .../Utilities/ThreadSafeStore.cs | 6 +-- 32 files changed, 228 insertions(+), 198 deletions(-) diff --git a/Src/Newtonsoft.Json/Linq/JObject.Async.cs b/Src/Newtonsoft.Json/Linq/JObject.Async.cs index 878b07ee7..8dba9055e 100644 --- a/Src/Newtonsoft.Json/Linq/JObject.Async.cs +++ b/Src/Newtonsoft.Json/Linq/JObject.Async.cs @@ -44,7 +44,7 @@ public partial class JObject /// A that represents the asynchronous write operation. public override Task WriteToAsync(JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters) { - var t = writer.WriteStartObjectAsync(cancellationToken); + Task t = writer.WriteStartObjectAsync(cancellationToken); if (!t.IsCompletedSucessfully()) { return AwaitProperties(t, 0, writer, cancellationToken, converters); diff --git a/Src/Newtonsoft.Json/Serialization/CamelCaseNamingStrategy.cs b/Src/Newtonsoft.Json/Serialization/CamelCaseNamingStrategy.cs index beb5066a4..0280c833f 100644 --- a/Src/Newtonsoft.Json/Serialization/CamelCaseNamingStrategy.cs +++ b/Src/Newtonsoft.Json/Serialization/CamelCaseNamingStrategy.cs @@ -1,4 +1,29 @@ -using Newtonsoft.Json.Utilities; +#region License +// Copyright (c) 2007 James Newton-King +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +#endregion + +using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Serialization { diff --git a/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs b/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs index 22e558ee7..053468a21 100644 --- a/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs +++ b/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs @@ -275,8 +275,7 @@ protected virtual List GetSerializableMembers(Type objectType) // serialize all fields foreach (MemberInfo member in allMembers) { - FieldInfo field = member as FieldInfo; - if (field != null && !field.IsStatic) + if (member is FieldInfo field && !field.IsStatic) { serializableMembers.Add(member); } @@ -426,8 +425,7 @@ private MemberInfo GetExtensionDataMemberForType(Type type) Type t = ReflectionUtils.GetMemberUnderlyingType(m); - Type dictionaryType; - if (ReflectionUtils.ImplementsGenericDefinition(t, typeof(IDictionary<,>), out dictionaryType)) + if (ReflectionUtils.ImplementsGenericDefinition(t, typeof(IDictionary<,>), out Type dictionaryType)) { Type keyType = dictionaryType.GetGenericArguments()[0]; Type valueType = dictionaryType.GetGenericArguments()[1]; @@ -454,8 +452,7 @@ private static void SetExtensionDataDelegates(JsonObjectContract contract, Membe Type t = ReflectionUtils.GetMemberUnderlyingType(member); - Type dictionaryType; - ReflectionUtils.ImplementsGenericDefinition(t, typeof(IDictionary<,>), out dictionaryType); + ReflectionUtils.ImplementsGenericDefinition(t, typeof(IDictionary<,>), out Type dictionaryType); Type keyType = dictionaryType.GetGenericArguments()[0]; Type valueType = dictionaryType.GetGenericArguments()[1]; @@ -590,7 +587,7 @@ private ConstructorInfo GetImmutableConstructor(Type objectType, JsonPropertyCol { foreach (ParameterInfo parameterInfo in parameters) { - var memberProperty = MatchProperty(memberProperties, parameterInfo.Name, parameterInfo.ParameterType); + JsonProperty memberProperty = MatchProperty(memberProperties, parameterInfo.Name, parameterInfo.ParameterType); if (memberProperty == null || memberProperty.Writable) { return null; @@ -691,8 +688,7 @@ protected virtual JsonProperty CreatePropertyFromConstructorParameter(JsonProper property.PropertyType = parameterInfo.ParameterType; property.AttributeProvider = new ReflectionAttributeProvider(parameterInfo); - bool allowNonPublicAccess; - SetPropertySettingsFromAttributes(property, parameterInfo, parameterInfo.Name, parameterInfo.Member.DeclaringType, MemberSerialization.OptOut, out allowNonPublicAccess); + SetPropertySettingsFromAttributes(property, parameterInfo, parameterInfo.Name, parameterInfo.Member.DeclaringType, MemberSerialization.OptOut, out _); property.Readable = false; property.Writable = true; @@ -776,13 +772,13 @@ private void InitializeContract(JsonContract contract) private void ResolveCallbackMethods(JsonContract contract, Type t) { - List onSerializing; - List onSerialized; - List onDeserializing; - List onDeserialized; - List onError; - - GetCallbackMethodsForType(t, out onSerializing, out onSerialized, out onDeserializing, out onDeserialized, out onError); + GetCallbackMethodsForType( + t, + out List onSerializing, + out List onSerialized, + out List onDeserializing, + out List onDeserialized, + out List onError); if (onSerializing != null) { @@ -1222,8 +1218,7 @@ internal static bool IsIConvertible(Type t) internal static bool CanConvertToString(Type type) { #if HAVE_TYPE_DESCRIPTOR - TypeConverter converter; - if (JsonTypeReflector.CanTypeDescriptorConvertString(type, out converter)) + if (JsonTypeReflector.CanTypeDescriptorConvertString(type, out _)) { return true; } @@ -1379,8 +1374,7 @@ protected virtual JsonProperty CreateProperty(MemberInfo member, MemberSerializa property.ValueProvider = CreateMemberValueProvider(member); property.AttributeProvider = new ReflectionAttributeProvider(member); - bool allowNonPublicAccess; - SetPropertySettingsFromAttributes(property, member, member.Name, member.DeclaringType, memberSerialization, out allowNonPublicAccess); + SetPropertySettingsFromAttributes(property, member, member.Name, member.DeclaringType, memberSerialization, out bool allowNonPublicAccess); if (memberSerialization != MemberSerialization.Fields) { diff --git a/Src/Newtonsoft.Json/Serialization/DefaultReferenceResolver.cs b/Src/Newtonsoft.Json/Serialization/DefaultReferenceResolver.cs index 347660021..83e0f4846 100644 --- a/Src/Newtonsoft.Json/Serialization/DefaultReferenceResolver.cs +++ b/Src/Newtonsoft.Json/Serialization/DefaultReferenceResolver.cs @@ -35,11 +35,9 @@ internal class DefaultReferenceResolver : IReferenceResolver private BidirectionalDictionary GetMappings(object context) { - JsonSerializerInternalBase internalSerializer = context as JsonSerializerInternalBase; - if (internalSerializer == null) + if (!(context is JsonSerializerInternalBase internalSerializer)) { - JsonSerializerProxy proxy = context as JsonSerializerProxy; - if (proxy != null) + if (context is JsonSerializerProxy proxy) { internalSerializer = proxy.GetInternalSerializer(); } @@ -54,8 +52,7 @@ internal class DefaultReferenceResolver : IReferenceResolver public object ResolveReference(object context, string reference) { - object value; - GetMappings(context).TryGetByFirst(reference, out value); + GetMappings(context).TryGetByFirst(reference, out object value); return value; } @@ -63,8 +60,7 @@ public string GetReference(object context, object value) { BidirectionalDictionary mappings = GetMappings(context); - string reference; - if (!mappings.TryGetBySecond(value, out reference)) + if (!mappings.TryGetBySecond(value, out string reference)) { _referenceCount++; reference = _referenceCount.ToString(CultureInfo.InvariantCulture); @@ -81,8 +77,7 @@ public void AddReference(object context, string reference, object value) public bool IsReferenced(object context, object value) { - string reference; - return GetMappings(context).TryGetBySecond(value, out reference); + return GetMappings(context).TryGetBySecond(value, out _); } } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Serialization/JsonArrayContract.cs b/Src/Newtonsoft.Json/Serialization/JsonArrayContract.cs index 66b5c0119..78a3e3c15 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonArrayContract.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonArrayContract.cs @@ -251,9 +251,11 @@ public JsonArrayContract(Type underlyingType) } #endif - Type immutableCreatedType; - ObjectConstructor immutableParameterizedCreator; - if (ImmutableCollectionsUtils.TryBuildImmutableForArrayContract(underlyingType, CollectionItemType, out immutableCreatedType, out immutableParameterizedCreator)) + if (ImmutableCollectionsUtils.TryBuildImmutableForArrayContract( + underlyingType, + CollectionItemType, + out Type immutableCreatedType, + out ObjectConstructor immutableParameterizedCreator)) { CreatedType = immutableCreatedType; _parameterizedCreator = immutableParameterizedCreator; diff --git a/Src/Newtonsoft.Json/Serialization/JsonDictionaryContract.cs b/Src/Newtonsoft.Json/Serialization/JsonDictionaryContract.cs index 1731a8d7f..486b0e0ce 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonDictionaryContract.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonDictionaryContract.cs @@ -180,20 +180,21 @@ public JsonDictionaryContract(Type underlyingType) #if (NET20 || NET35) if (DictionaryValueType != null && ReflectionUtils.IsNullableType(DictionaryValueType)) { - Type tempDictioanryType; - // bug in .NET 2.0 & 3.5 that Dictionary> throws an error when adding null via IDictionary[key] = object // wrapper will handle calling Add(T) instead - if (ReflectionUtils.InheritsGenericDefinition(CreatedType, typeof(Dictionary<,>), out tempDictioanryType)) + if (ReflectionUtils.InheritsGenericDefinition(CreatedType, typeof(Dictionary<,>), out _)) { ShouldCreateWrapper = true; } } #endif - Type immutableCreatedType; - ObjectConstructor immutableParameterizedCreator; - if (ImmutableCollectionsUtils.TryBuildImmutableForDictionaryContract(underlyingType, DictionaryKeyType, DictionaryValueType, out immutableCreatedType, out immutableParameterizedCreator)) + if (ImmutableCollectionsUtils.TryBuildImmutableForDictionaryContract( + underlyingType, + DictionaryKeyType, + DictionaryValueType, + out Type immutableCreatedType, + out ObjectConstructor immutableParameterizedCreator)) { CreatedType = immutableCreatedType; _parameterizedCreator = immutableParameterizedCreator; diff --git a/Src/Newtonsoft.Json/Serialization/JsonDynamicContract.cs b/Src/Newtonsoft.Json/Serialization/JsonDynamicContract.cs index 1133f9a30..f8a6ad391 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonDynamicContract.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonDynamicContract.cs @@ -25,12 +25,9 @@ #if HAVE_DYNAMIC using System; -using System.Collections.Generic; using System.Dynamic; -using System.Reflection; using System.Runtime.CompilerServices; using Newtonsoft.Json.Utilities; -using System.Collections; namespace Newtonsoft.Json.Serialization { diff --git a/Src/Newtonsoft.Json/Serialization/JsonFormatterConverter.cs b/Src/Newtonsoft.Json/Serialization/JsonFormatterConverter.cs index f11f7162e..8be45fb9c 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonFormatterConverter.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonFormatterConverter.cs @@ -60,8 +60,7 @@ public object Convert(object value, Type type) { ValidationUtils.ArgumentNotNull(value, nameof(value)); - JToken token = value as JToken; - if (token == null) + if (!(value is JToken token)) { throw new ArgumentException("Value is not a JToken.", nameof(value)); } diff --git a/Src/Newtonsoft.Json/Serialization/JsonPropertyCollection.cs b/Src/Newtonsoft.Json/Serialization/JsonPropertyCollection.cs index 996bf64d1..d9dda703e 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonPropertyCollection.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonPropertyCollection.cs @@ -156,8 +156,7 @@ public JsonProperty GetProperty(string propertyName, StringComparison comparison // KeyedCollection has an ordinal comparer if (comparisonType == StringComparison.Ordinal) { - JsonProperty property; - if (TryGetValue(propertyName, out property)) + if (TryGetValue(propertyName, out JsonProperty property)) { return property; } diff --git a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs index da224c4c9..36572dc2b 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs @@ -380,8 +380,7 @@ private string GetReference(JsonWriter writer, object value) internal static bool TryConvertToString(object value, Type type, out string s) { #if HAVE_TYPE_DESCRIPTOR - TypeConverter converter; - if (JsonTypeReflector.CanTypeDescriptorConvertString(type, out converter)) + if (JsonTypeReflector.CanTypeDescriptorConvertString(type, out TypeConverter converter)) { s = converter.ConvertToInvariantString(value); return true; @@ -411,8 +410,7 @@ private void SerializeString(JsonWriter writer, object value, JsonStringContract { OnSerializing(writer, contract, value); - string s; - TryConvertToString(value, contract.UnderlyingType, out s); + TryConvertToString(value, contract.UnderlyingType, out string s); writer.WriteValue(s); OnSerialized(writer, contract, value); @@ -453,10 +451,7 @@ private void SerializeObject(JsonWriter writer, object value, JsonObjectContract JsonProperty property = contract.Properties[index]; try { - object memberValue; - JsonContract memberContract; - - if (!CalculatePropertyValues(writer, value, contract, member, property, out memberContract, out memberValue)) + if (!CalculatePropertyValues(writer, value, contract, member, property, out JsonContract memberContract, out object memberValue)) { continue; } @@ -585,8 +580,7 @@ private void WriteObjectStart(JsonWriter writer, object value, JsonContract cont private bool HasCreatorParameter(JsonContainerContract contract, JsonProperty property) { - JsonObjectContract objectContract = contract as JsonObjectContract; - if (objectContract == null) + if (!(contract is JsonObjectContract objectContract)) { return false; } @@ -668,8 +662,7 @@ private void SerializeConvertable(JsonWriter writer, JsonConverter converter, ob private void SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) { - IWrappedCollection wrappedCollection = values as IWrappedCollection; - object underlyingList = wrappedCollection != null ? wrappedCollection.UnderlyingCollection : values; + object underlyingList = values is IWrappedCollection wrappedCollection ? wrappedCollection.UnderlyingCollection : values; OnSerializing(writer, contract, underlyingList); @@ -904,10 +897,7 @@ private void SerializeDynamic(JsonWriter writer, IDynamicMetaObjectProvider valu { try { - object memberValue; - JsonContract memberContract; - - if (!CalculatePropertyValues(writer, value, contract, member, property, out memberContract, out memberValue)) + if (!CalculatePropertyValues(writer, value, contract, member, property, out JsonContract memberContract, out object memberValue)) { continue; } @@ -931,8 +921,7 @@ private void SerializeDynamic(JsonWriter writer, IDynamicMetaObjectProvider valu foreach (string memberName in value.GetDynamicMemberNames()) { - object memberValue; - if (contract.TryGetMember(value, memberName, out memberValue)) + if (contract.TryGetMember(value, memberName, out object memberValue)) { try { @@ -1036,8 +1025,7 @@ private bool ShouldWriteType(TypeNameHandling typeNameHandlingFlag, JsonContract private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) { - IWrappedDictionary wrappedDictionary = values as IWrappedDictionary; - object underlyingDictionary = wrappedDictionary != null ? wrappedDictionary.UnderlyingDictionary : values; + object underlyingDictionary = values is IWrappedDictionary wrappedDictionary ? wrappedDictionary.UnderlyingDictionary : values; OnSerializing(writer, contract, underlyingDictionary); _serializeStack.Add(underlyingDictionary); @@ -1064,8 +1052,7 @@ private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDict { DictionaryEntry entry = e.Entry; - bool escape; - string propertyName = GetPropertyName(writer, entry.Key, contract.KeyContract, out escape); + string propertyName = GetPropertyName(writer, entry.Key, contract.KeyContract, out bool escape); propertyName = (contract.DictionaryKeyResolver != null) ? contract.DictionaryKeyResolver(propertyName) @@ -1120,8 +1107,6 @@ private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDict private string GetPropertyName(JsonWriter writer, object name, JsonContract contract, out bool escape) { - string propertyName; - if (contract.ContractType == JsonContractType.Primitive) { JsonPrimitiveContract primitiveContract = (JsonPrimitiveContract)contract; @@ -1170,7 +1155,7 @@ private string GetPropertyName(JsonWriter writer, object name, JsonContract cont } } } - else if (TryConvertToString(name, name.GetType(), out propertyName)) + else if (TryConvertToString(name, name.GetType(), out string propertyName)) { escape = true; return propertyName; diff --git a/Src/Newtonsoft.Json/Serialization/NamingStrategy.cs b/Src/Newtonsoft.Json/Serialization/NamingStrategy.cs index 695fdd062..04880f4fc 100644 --- a/Src/Newtonsoft.Json/Serialization/NamingStrategy.cs +++ b/Src/Newtonsoft.Json/Serialization/NamingStrategy.cs @@ -1,4 +1,29 @@ -namespace Newtonsoft.Json.Serialization +#region License +// Copyright (c) 2007 James Newton-King +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +#endregion + +namespace Newtonsoft.Json.Serialization { /// /// A base class for resolving how property names and dictionary keys are serialized. diff --git a/Src/Newtonsoft.Json/Serialization/SnakeCaseNamingStrategy.cs b/Src/Newtonsoft.Json/Serialization/SnakeCaseNamingStrategy.cs index 7fec865f8..f22107939 100644 --- a/Src/Newtonsoft.Json/Serialization/SnakeCaseNamingStrategy.cs +++ b/Src/Newtonsoft.Json/Serialization/SnakeCaseNamingStrategy.cs @@ -1,4 +1,29 @@ -using Newtonsoft.Json.Utilities; +#region License +// Copyright (c) 2007 James Newton-King +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +#endregion + +using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Serialization { diff --git a/Src/Newtonsoft.Json/Serialization/TraceJsonReader.cs b/Src/Newtonsoft.Json/Serialization/TraceJsonReader.cs index d4885d9b4..f0817dfd9 100644 --- a/Src/Newtonsoft.Json/Serialization/TraceJsonReader.cs +++ b/Src/Newtonsoft.Json/Serialization/TraceJsonReader.cs @@ -1,4 +1,29 @@ -using System; +#region License +// Copyright (c) 2007 James Newton-King +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +#endregion + +using System; using System.Collections.Generic; using System.Globalization; using System.IO; @@ -122,16 +147,14 @@ public override void Close() bool IJsonLineInfo.HasLineInfo() { - IJsonLineInfo lineInfo = _innerReader as IJsonLineInfo; - return lineInfo != null && lineInfo.HasLineInfo(); + return _innerReader is IJsonLineInfo lineInfo && lineInfo.HasLineInfo(); } int IJsonLineInfo.LineNumber { get { - IJsonLineInfo lineInfo = _innerReader as IJsonLineInfo; - return (lineInfo != null) ? lineInfo.LineNumber : 0; + return (_innerReader is IJsonLineInfo lineInfo) ? lineInfo.LineNumber : 0; } } @@ -139,8 +162,7 @@ int IJsonLineInfo.LinePosition { get { - IJsonLineInfo lineInfo = _innerReader as IJsonLineInfo; - return (lineInfo != null) ? lineInfo.LinePosition : 0; + return (_innerReader is IJsonLineInfo lineInfo) ? lineInfo.LinePosition : 0; } } } diff --git a/Src/Newtonsoft.Json/Serialization/TraceJsonWriter.cs b/Src/Newtonsoft.Json/Serialization/TraceJsonWriter.cs index 56133c42e..95d9ebae2 100644 --- a/Src/Newtonsoft.Json/Serialization/TraceJsonWriter.cs +++ b/Src/Newtonsoft.Json/Serialization/TraceJsonWriter.cs @@ -1,11 +1,34 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +#endregion + using System; -using System.Collections.Generic; using System.Globalization; using System.IO; #if HAVE_BIG_INTEGER using System.Numerics; #endif -using System.Text; namespace Newtonsoft.Json.Serialization { diff --git a/Src/Newtonsoft.Json/Utilities/BidirectionalDictionary.cs b/Src/Newtonsoft.Json/Utilities/BidirectionalDictionary.cs index b72d56cc9..3ee3c5969 100644 --- a/Src/Newtonsoft.Json/Utilities/BidirectionalDictionary.cs +++ b/Src/Newtonsoft.Json/Utilities/BidirectionalDictionary.cs @@ -61,10 +61,7 @@ public BidirectionalDictionary(IEqualityComparer firstEqualityComparer, public void Set(TFirst first, TSecond second) { - TFirst existingFirst; - TSecond existingSecond; - - if (_firstToSecond.TryGetValue(first, out existingSecond)) + if (_firstToSecond.TryGetValue(first, out TSecond existingSecond)) { if (!existingSecond.Equals(second)) { @@ -72,7 +69,7 @@ public void Set(TFirst first, TSecond second) } } - if (_secondToFirst.TryGetValue(second, out existingFirst)) + if (_secondToFirst.TryGetValue(second, out TFirst existingFirst)) { if (!existingFirst.Equals(first)) { diff --git a/Src/Newtonsoft.Json/Utilities/CollectionUtils.cs b/Src/Newtonsoft.Json/Utilities/CollectionUtils.cs index c69236adf..c42ec8efa 100644 --- a/Src/Newtonsoft.Json/Utilities/CollectionUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/CollectionUtils.cs @@ -289,8 +289,7 @@ private static IList GetDimensions(IList values, int dimensionsCount) } object v = currentArray[0]; - IList list = v as IList; - if (list != null) + if (v is IList list) { currentArray = list; } diff --git a/Src/Newtonsoft.Json/Utilities/CollectionWrapper.cs b/Src/Newtonsoft.Json/Utilities/CollectionWrapper.cs index 55d17fcec..a1696670f 100644 --- a/Src/Newtonsoft.Json/Utilities/CollectionWrapper.cs +++ b/Src/Newtonsoft.Json/Utilities/CollectionWrapper.cs @@ -52,8 +52,7 @@ public CollectionWrapper(IList list) { ValidationUtils.ArgumentNotNull(list, nameof(list)); - ICollection collection = list as ICollection; - if (collection != null) + if (list is ICollection collection) { _genericCollection = collection; } diff --git a/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs b/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs index 0798b4b1e..18394129e 100644 --- a/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs @@ -30,8 +30,10 @@ #if HAVE_BIG_INTEGER using System.Numerics; #endif +#if !HAVE_GUID_TRY_PARSE using System.Text; using System.Text.RegularExpressions; +#endif using Newtonsoft.Json.Serialization; using System.Reflection; #if !HAVE_LINQ @@ -381,7 +383,7 @@ public static object FromBigInteger(BigInteger i, Type targetType) } #endif - #region TryConvert +#region TryConvert internal enum ConvertResult { Success = 0, @@ -447,7 +449,7 @@ private static ConvertResult TryConvertInternal(object initialValue, CultureInfo } // use Convert.ChangeType if both types are IConvertible - if (ConvertUtils.IsConvertible(initialValue.GetType()) && ConvertUtils.IsConvertible(targetType)) + if (IsConvertible(initialValue.GetType()) && IsConvertible(targetType)) { if (targetType.IsEnum()) { @@ -468,9 +470,9 @@ private static ConvertResult TryConvertInternal(object initialValue, CultureInfo } #if HAVE_DATE_TIME_OFFSET - if (initialValue is DateTime && targetType == typeof(DateTimeOffset)) + if (initialValue is DateTime dt && targetType == typeof(DateTimeOffset)) { - value = new DateTimeOffset((DateTime)initialValue); + value = new DateTimeOffset(dt); return ConvertResult.Success; } #endif @@ -582,9 +584,9 @@ private static ConvertResult TryConvertInternal(object initialValue, CultureInfo value = null; return ConvertResult.NoValidConversion; } - #endregion +#endregion - #region ConvertOrCast +#region ConvertOrCast /// /// Converts the value to the specified type. If the value is unable to be converted, the /// value is checked whether it assignable to the specified type. @@ -615,7 +617,7 @@ public static object ConvertOrCast(object initialValue, CultureInfo culture, Typ return EnsureTypeAssignable(initialValue, ReflectionUtils.GetObjectType(initialValue), targetType); } - #endregion +#endregion private static object EnsureTypeAssignable(object value, Type initialType, Type targetType) { diff --git a/Src/Newtonsoft.Json/Utilities/DateTimeUtils.cs b/Src/Newtonsoft.Json/Utilities/DateTimeUtils.cs index 19e6ce300..24e076dcb 100644 --- a/Src/Newtonsoft.Json/Utilities/DateTimeUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/DateTimeUtils.cs @@ -521,11 +521,7 @@ private static bool TryParseMicrosoftDate(StringReference text, out long ticks, private static bool TryParseDateTimeMicrosoft(StringReference text, DateTimeZoneHandling dateTimeZoneHandling, out DateTime dt) { - long ticks; - TimeSpan offset; - DateTimeKind kind; - - if (!TryParseMicrosoftDate(text, out ticks, out offset, out kind)) + if (!TryParseMicrosoftDate(text, out long ticks, out _, out DateTimeKind kind)) { dt = default(DateTime); return false; @@ -552,8 +548,7 @@ private static bool TryParseDateTimeMicrosoft(StringReference text, DateTimeZone private static bool TryParseDateTimeExact(string text, DateTimeZoneHandling dateTimeZoneHandling, string dateFormatString, CultureInfo culture, out DateTime dt) { - DateTime temp; - if (DateTime.TryParseExact(text, dateFormatString, culture, DateTimeStyles.RoundtripKind, out temp)) + if (DateTime.TryParseExact(text, dateFormatString, culture, DateTimeStyles.RoundtripKind, out DateTime temp)) { temp = EnsureDateTime(temp, dateTimeZoneHandling); dt = temp; @@ -567,11 +562,7 @@ private static bool TryParseDateTimeExact(string text, DateTimeZoneHandling date #if HAVE_DATE_TIME_OFFSET private static bool TryParseDateTimeOffsetMicrosoft(StringReference text, out DateTimeOffset dt) { - long ticks; - TimeSpan offset; - DateTimeKind kind; - - if (!TryParseMicrosoftDate(text, out ticks, out offset, out kind)) + if (!TryParseMicrosoftDate(text, out long ticks, out TimeSpan offset, out _)) { dt = default(DateTime); return false; @@ -585,8 +576,7 @@ private static bool TryParseDateTimeOffsetMicrosoft(StringReference text, out Da private static bool TryParseDateTimeOffsetExact(string text, string dateFormatString, CultureInfo culture, out DateTimeOffset dt) { - DateTimeOffset temp; - if (DateTimeOffset.TryParseExact(text, dateFormatString, culture, DateTimeStyles.RoundtripKind, out temp)) + if (DateTimeOffset.TryParseExact(text, dateFormatString, culture, DateTimeStyles.RoundtripKind, out DateTimeOffset temp)) { dt = temp; return true; @@ -601,8 +591,7 @@ private static bool TryReadOffset(StringReference offsetText, int startIndex, ou { bool negative = (offsetText[startIndex] == '-'); - int hours; - if (ConvertUtils.Int32TryParse(offsetText.Chars, startIndex + 1, 2, out hours) != ParseResult.Success) + if (ConvertUtils.Int32TryParse(offsetText.Chars, startIndex + 1, 2, out int hours) != ParseResult.Success) { offset = default(TimeSpan); return false; @@ -698,10 +687,7 @@ internal static int WriteDefaultIsoDate(char[] chars, int start, DateTime dt) { int length = 19; - int year; - int month; - int day; - GetDateValues(dt, out year, out month, out day); + GetDateValues(dt, out int year, out int month, out int day); CopyIntToCharArray(chars, start, year, 4); chars[start + 4] = '-'; diff --git a/Src/Newtonsoft.Json/Utilities/DictionaryWrapper.cs b/Src/Newtonsoft.Json/Utilities/DictionaryWrapper.cs index 05977bd53..fdfd55d8f 100644 --- a/Src/Newtonsoft.Json/Utilities/DictionaryWrapper.cs +++ b/Src/Newtonsoft.Json/Utilities/DictionaryWrapper.cs @@ -376,7 +376,7 @@ public bool Remove(KeyValuePair item) { object value = _dictionary[item.Key]; - if (object.Equals(value, item.Value)) + if (Equals(value, item.Value)) { _dictionary.Remove(item.Key); return true; diff --git a/Src/Newtonsoft.Json/Utilities/DynamicProxy.cs b/Src/Newtonsoft.Json/Utilities/DynamicProxy.cs index c3affe92e..caeb9194c 100644 --- a/Src/Newtonsoft.Json/Utilities/DynamicProxy.cs +++ b/Src/Newtonsoft.Json/Utilities/DynamicProxy.cs @@ -24,12 +24,8 @@ #endregion #if HAVE_DYNAMIC -using System; using System.Collections.Generic; using System.Dynamic; -using System.Linq; -using System.Linq.Expressions; -using System.Text; namespace Newtonsoft.Json.Utilities { diff --git a/Src/Newtonsoft.Json/Utilities/DynamicProxyMetaObject.cs b/Src/Newtonsoft.Json/Utilities/DynamicProxyMetaObject.cs index 05e7e214d..56b556560 100644 --- a/Src/Newtonsoft.Json/Utilities/DynamicProxyMetaObject.cs +++ b/Src/Newtonsoft.Json/Utilities/DynamicProxyMetaObject.cs @@ -184,7 +184,7 @@ private static Expression[] GetArgArray(DynamicMetaObject[] args) private static Expression[] GetArgArray(DynamicMetaObject[] args, DynamicMetaObject value) { - var exp = value.Expression; + Expression exp = value.Expression; return new[] { Expression.NewArrayInit(typeof(object), GetArgs(args)), diff --git a/Src/Newtonsoft.Json/Utilities/DynamicReflectionDelegateFactory.cs b/Src/Newtonsoft.Json/Utilities/DynamicReflectionDelegateFactory.cs index 83888089e..10b3e10b6 100644 --- a/Src/Newtonsoft.Json/Utilities/DynamicReflectionDelegateFactory.cs +++ b/Src/Newtonsoft.Json/Utilities/DynamicReflectionDelegateFactory.cs @@ -38,9 +38,7 @@ namespace Newtonsoft.Json.Utilities { internal class DynamicReflectionDelegateFactory : ReflectionDelegateFactory { - private static readonly DynamicReflectionDelegateFactory _instance = new DynamicReflectionDelegateFactory(); - - internal static DynamicReflectionDelegateFactory Instance => _instance; + internal static DynamicReflectionDelegateFactory Instance { get; } = new DynamicReflectionDelegateFactory(); private static DynamicMethod CreateDynamicMethod(string name, Type returnType, Type[] parameterTypes, Type owner) { diff --git a/Src/Newtonsoft.Json/Utilities/EnumUtils.cs b/Src/Newtonsoft.Json/Utilities/EnumUtils.cs index edee67311..3afe9ac32 100644 --- a/Src/Newtonsoft.Json/Utilities/EnumUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/EnumUtils.cs @@ -60,8 +60,7 @@ internal static class EnumUtils n2 = f.Name; #endif - string s; - if (map.TryGetBySecond(n2, out s)) + if (map.TryGetBySecond(n2, out _)) { throw new InvalidOperationException("Enum name '{0}' already exists on enum '{1}'.".FormatWith(CultureInfo.InvariantCulture, n2, type.Name)); } @@ -196,8 +195,7 @@ public static object ParseEnumName(string enumText, bool isNullable, bool disall string finalEnumText; BidirectionalDictionary map = EnumMemberNamesPerType.Get(t); - string resolvedEnumName; - if (TryResolvedEnumName(map, enumText, out resolvedEnumName)) + if (TryResolvedEnumName(map, enumText, out string resolvedEnumName)) { finalEnumText = resolvedEnumName; } @@ -242,8 +240,7 @@ public static string ToEnumName(Type enumType, string enumText, bool camelCaseTe { string name = names[i].Trim(); - string resolvedEnumName; - map.TryGetByFirst(name, out resolvedEnumName); + map.TryGetByFirst(name, out string resolvedEnumName); resolvedEnumName = resolvedEnumName ?? name; if (camelCaseText) diff --git a/Src/Newtonsoft.Json/Utilities/EnumValue.cs b/Src/Newtonsoft.Json/Utilities/EnumValue.cs index 909cd1a45..bbf289896 100644 --- a/Src/Newtonsoft.Json/Utilities/EnumValue.cs +++ b/Src/Newtonsoft.Json/Utilities/EnumValue.cs @@ -27,17 +27,13 @@ namespace Newtonsoft.Json.Utilities { internal class EnumValue where T : struct { - private readonly string _name; - private readonly T _value; - - public string Name => _name; - - public T Value => _value; + public string Name { get; } + public T Value { get; } public EnumValue(string name, T value) { - _name = name; - _value = value; + Name = name; + Value = value; } } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Utilities/ExpressionReflectionDelegateFactory.cs b/Src/Newtonsoft.Json/Utilities/ExpressionReflectionDelegateFactory.cs index 39f11abf3..33d800cb7 100644 --- a/Src/Newtonsoft.Json/Utilities/ExpressionReflectionDelegateFactory.cs +++ b/Src/Newtonsoft.Json/Utilities/ExpressionReflectionDelegateFactory.cs @@ -39,10 +39,7 @@ internal class ExpressionReflectionDelegateFactory : ReflectionDelegateFactory { private static readonly ExpressionReflectionDelegateFactory _instance = new ExpressionReflectionDelegateFactory(); - internal static ReflectionDelegateFactory Instance - { - get { return _instance; } - } + internal static ReflectionDelegateFactory Instance => _instance; public override ObjectConstructor CreateParameterizedConstructor(MethodBase method) { diff --git a/Src/Newtonsoft.Json/Utilities/JsonTokenUtils.cs b/Src/Newtonsoft.Json/Utilities/JsonTokenUtils.cs index fa45a5eb2..7e02baa2f 100644 --- a/Src/Newtonsoft.Json/Utilities/JsonTokenUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/JsonTokenUtils.cs @@ -23,9 +23,6 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -using System; -using System.Text; - namespace Newtonsoft.Json.Utilities { internal static class JsonTokenUtils diff --git a/Src/Newtonsoft.Json/Utilities/MiscellaneousUtils.cs b/Src/Newtonsoft.Json/Utilities/MiscellaneousUtils.cs index 88196e5cc..34c6e857a 100644 --- a/Src/Newtonsoft.Json/Utilities/MiscellaneousUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/MiscellaneousUtils.cs @@ -108,18 +108,14 @@ public static int ByteArrayCompare(byte[] a1, byte[] a2) public static string GetPrefix(string qualifiedName) { - string prefix; - string localName; - GetQualifiedNameParts(qualifiedName, out prefix, out localName); + GetQualifiedNameParts(qualifiedName, out string prefix, out _); return prefix; } public static string GetLocalName(string qualifiedName) { - string prefix; - string localName; - GetQualifiedNameParts(qualifiedName, out prefix, out localName); + GetQualifiedNameParts(qualifiedName, out _, out string localName); return localName; } diff --git a/Src/Newtonsoft.Json/Utilities/ReflectionDelegateFactory.cs b/Src/Newtonsoft.Json/Utilities/ReflectionDelegateFactory.cs index 7c70cfdb7..927415d6d 100644 --- a/Src/Newtonsoft.Json/Utilities/ReflectionDelegateFactory.cs +++ b/Src/Newtonsoft.Json/Utilities/ReflectionDelegateFactory.cs @@ -38,14 +38,12 @@ internal abstract class ReflectionDelegateFactory { public Func CreateGet(MemberInfo memberInfo) { - PropertyInfo propertyInfo = memberInfo as PropertyInfo; - if (propertyInfo != null) + if (memberInfo is PropertyInfo propertyInfo) { return CreateGet(propertyInfo); } - FieldInfo fieldInfo = memberInfo as FieldInfo; - if (fieldInfo != null) + if (memberInfo is FieldInfo fieldInfo) { return CreateGet(fieldInfo); } @@ -55,14 +53,12 @@ internal abstract class ReflectionDelegateFactory public Action CreateSet(MemberInfo memberInfo) { - PropertyInfo propertyInfo = memberInfo as PropertyInfo; - if (propertyInfo != null) + if (memberInfo is PropertyInfo propertyInfo) { return CreateSet(propertyInfo); } - FieldInfo fieldInfo = memberInfo as FieldInfo; - if (fieldInfo != null) + if (memberInfo is FieldInfo fieldInfo) { return CreateSet(fieldInfo); } diff --git a/Src/Newtonsoft.Json/Utilities/ReflectionObject.cs b/Src/Newtonsoft.Json/Utilities/ReflectionObject.cs index b39a3da98..838be9c9b 100644 --- a/Src/Newtonsoft.Json/Utilities/ReflectionObject.cs +++ b/Src/Newtonsoft.Json/Utilities/ReflectionObject.cs @@ -26,7 +26,6 @@ using Newtonsoft.Json.Serialization; using System; using System.Collections.Generic; -using System.IO; using System.Reflection; using System.Globalization; #if !HAVE_LINQ diff --git a/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs b/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs index d10e996b7..0e0def46d 100644 --- a/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs @@ -31,8 +31,6 @@ using System.Reflection; using System.Collections; using System.Globalization; -using System.Runtime.Serialization; -using System.Runtime.Serialization.Formatters; using System.Text; #if !HAVE_LINQ using Newtonsoft.Json.Utilities.LinqBridge; @@ -164,9 +162,7 @@ private static string GetFullyQualifiedTypeName(Type t, ISerializationBinder bin { if (binder != null) { - string assemblyName; - string typeName; - binder.BindToName(t, out assemblyName, out typeName); + binder.BindToName(t, out string assemblyName, out string typeName); #if (NET20 || NET35) // for older SerializationBinder implementations that didn't have BindToName if (assemblyName == null & typeName == null) @@ -292,8 +288,7 @@ public static bool IsGenericDefinition(Type type, Type genericInterfaceDefinitio public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition) { - Type implementingType; - return ImplementsGenericDefinition(type, genericInterfaceDefinition, out implementingType); + return ImplementsGenericDefinition(type, genericInterfaceDefinition, out _); } public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition, out Type implementingType) @@ -340,8 +335,7 @@ public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceD public static bool InheritsGenericDefinition(Type type, Type genericClassDefinition) { - Type implementingType; - return InheritsGenericDefinition(type, genericClassDefinition, out implementingType); + return InheritsGenericDefinition(type, genericClassDefinition, out _); } public static bool InheritsGenericDefinition(Type type, Type genericClassDefinition, out Type implementingType) @@ -387,13 +381,12 @@ private static bool InheritsGenericDefinitionInternal(Type currentType, Type gen public static Type GetCollectionItemType(Type type) { ValidationUtils.ArgumentNotNull(type, nameof(type)); - Type genericListType; if (type.IsArray) { return type.GetElementType(); } - if (ImplementsGenericDefinition(type, typeof(IEnumerable<>), out genericListType)) + if (ImplementsGenericDefinition(type, typeof(IEnumerable<>), out Type genericListType)) { if (genericListType.IsGenericTypeDefinition()) { @@ -414,8 +407,7 @@ public static void GetDictionaryKeyValueTypes(Type dictionaryType, out Type keyT { ValidationUtils.ArgumentNotNull(dictionaryType, nameof(dictionaryType)); - Type genericDictionaryType; - if (ImplementsGenericDefinition(dictionaryType, typeof(IDictionary<,>), out genericDictionaryType)) + if (ImplementsGenericDefinition(dictionaryType, typeof(IDictionary<,>), out Type genericDictionaryType)) { if (genericDictionaryType.IsGenericTypeDefinition()) { @@ -473,9 +465,7 @@ public static bool IsIndexedProperty(MemberInfo member) { ValidationUtils.ArgumentNotNull(member, nameof(member)); - PropertyInfo propertyInfo = member as PropertyInfo; - - if (propertyInfo != null) + if (member is PropertyInfo propertyInfo) { return IsIndexedProperty(propertyInfo); } @@ -821,36 +811,31 @@ public static Attribute[] GetAttributes(object attributeProvider, Type attribute public static Attribute[] GetAttributes(object provider, Type attributeType, bool inherit) { - if (provider is Type) + if (provider is Type t) { - Type t = (Type)provider; return (attributeType != null) ? t.GetTypeInfo().GetCustomAttributes(attributeType, inherit).ToArray() : t.GetTypeInfo().GetCustomAttributes(inherit).ToArray(); } - if (provider is Assembly) + if (provider is Assembly a) { - Assembly a = (Assembly)provider; return (attributeType != null) ? a.GetCustomAttributes(attributeType).ToArray() : a.GetCustomAttributes().ToArray(); } - if (provider is MemberInfo) + if (provider is MemberInfo memberInfo) { - MemberInfo m = (MemberInfo)provider; - return (attributeType != null) ? m.GetCustomAttributes(attributeType, inherit).ToArray() : m.GetCustomAttributes(inherit).ToArray(); + return (attributeType != null) ? memberInfo.GetCustomAttributes(attributeType, inherit).ToArray() : memberInfo.GetCustomAttributes(inherit).ToArray(); } - if (provider is Module) + if (provider is Module module) { - Module m = (Module)provider; - return (attributeType != null) ? m.GetCustomAttributes(attributeType).ToArray() : m.GetCustomAttributes().ToArray(); + return (attributeType != null) ? module.GetCustomAttributes(attributeType).ToArray() : module.GetCustomAttributes().ToArray(); } - if (provider is ParameterInfo) + if (provider is ParameterInfo parameterInfo) { - ParameterInfo p = (ParameterInfo)provider; - return (attributeType != null) ? p.GetCustomAttributes(attributeType, inherit).ToArray() : p.GetCustomAttributes(inherit).ToArray(); + return (attributeType != null) ? parameterInfo.GetCustomAttributes(attributeType, inherit).ToArray() : parameterInfo.GetCustomAttributes(inherit).ToArray(); } throw new Exception("Cannot get attributes from '{0}'.".FormatWith(CultureInfo.InvariantCulture, provider)); diff --git a/Src/Newtonsoft.Json/Utilities/ThreadSafeStore.cs b/Src/Newtonsoft.Json/Utilities/ThreadSafeStore.cs index 2b8f5e497..1f0110816 100644 --- a/Src/Newtonsoft.Json/Utilities/ThreadSafeStore.cs +++ b/Src/Newtonsoft.Json/Utilities/ThreadSafeStore.cs @@ -63,8 +63,7 @@ public TValue Get(TKey key) #if HAVE_CONCURRENT_DICTIONARY return _concurrentStore.GetOrAdd(key, _creator); #else - TValue value; - if (!_store.TryGetValue(key, out value)) + if (!_store.TryGetValue(key, out TValue value)) { return AddValue(key); } @@ -88,8 +87,7 @@ private TValue AddValue(TKey key) else { // double check locking - TValue checkValue; - if (_store.TryGetValue(key, out checkValue)) + if (_store.TryGetValue(key, out TValue checkValue)) { return checkValue; }