Skip to content

Commit

Permalink
Use TryGetValue()
Browse files Browse the repository at this point in the history
- Use `TryGetValue()` instead of `ContainsKey()` and indexer.
- Apply some IDE refactoring suggestions.
  • Loading branch information
martincostello committed Apr 16, 2024
1 parent 409f9c7 commit 466a55b
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public DataContract GetDataContractForType(Type type)
{
var enumValues = jsonContract.UnderlyingType.GetEnumValues();

//Test to determine if the serializer will treat as string
// Test to determine if the serializer will treat as string
var serializeAsString = (enumValues.Length > 0)
&& JsonConverterFunc(enumValues.GetValue(0)).StartsWith("\"");

Expand Down Expand Up @@ -84,7 +84,7 @@ public DataContract GetDataContractForType(Type type)
// This is a special case where we know the possible key values
var enumValuesAsJson = keyType.GetEnumValues()
.Cast<object>()
.Select(value => JsonConverterFunc(value));
.Select(JsonConverterFunc);

keys = enumValuesAsJson.Any(json => json.StartsWith("\""))
? enumValuesAsJson.Select(json => json.Replace("\"", string.Empty))
Expand Down Expand Up @@ -197,7 +197,7 @@ private IEnumerable<DataProperty> GetDataPropertiesFor(JsonObjectContract jsonOb
return dataProperties;
}

private static readonly Dictionary<Type, Tuple<DataType, string>> PrimitiveTypesAndFormats = new Dictionary<Type, Tuple<DataType, string>>
private static readonly Dictionary<Type, Tuple<DataType, string>> PrimitiveTypesAndFormats = new()
{
[ typeof(bool) ] = Tuple.Create(DataType.Boolean, (string)null),
[ typeof(byte) ] = Tuple.Create(DataType.Integer, "int32"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,8 @@ public DataContract GetDataContractForType(Type type)
jsonConverter: JsonConverterFunc);
}

if (PrimitiveTypesAndFormats.ContainsKey(type))
if (PrimitiveTypesAndFormats.TryGetValue(type, out var primitiveTypeAndFormat))
{
var primitiveTypeAndFormat = PrimitiveTypesAndFormats[type];

return DataContract.ForPrimitive(
underlyingType: type,
dataType: primitiveTypeAndFormat.Item1,
Expand All @@ -45,7 +43,7 @@ public DataContract GetDataContractForType(Type type)
var serializeAsString = (enumValues.Length > 0)
&& JsonConverterFunc(enumValues.GetValue(0)).StartsWith("\"");

var primitiveTypeAndFormat = serializeAsString
primitiveTypeAndFormat = serializeAsString
? PrimitiveTypesAndFormats[typeof(string)]
: PrimitiveTypesAndFormats[type.GetEnumUnderlyingType()];

Expand Down

0 comments on commit 466a55b

Please sign in to comment.