Skip to content

Commit

Permalink
Simplify collection initialization and use pattern matching (#5047)
Browse files Browse the repository at this point in the history
  • Loading branch information
lahma authored Nov 22, 2024
1 parent 79ca06b commit 8ff1c5d
Show file tree
Hide file tree
Showing 33 changed files with 65 additions and 66 deletions.
4 changes: 1 addition & 3 deletions Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@
[IDE0022] Use block body for method
[IDE0025] Use expression body for property
[IDE0027] Use expression body for accessor
[IDE0028] Collection initialization can be simplified
[IDE0029] Null check can be simplified
[IDE0032] Use auto property
[IDE0039] Use local function
Expand All @@ -71,7 +70,6 @@
[IDE0130] Namespace does not match folder structure
[IDE0160] Convert to block scoped namespace
[IDE0200] Lambda expression can be removed
[IDE0260] Use pattern matching
[IDE0270] Null check can be simplified
[IDE0290] Use primary constructor
[IDE0330] Use 'System.Threading.Lock'
Expand Down Expand Up @@ -101,7 +99,7 @@
[SYSLIB0012] 'Assembly.CodeBase' is obsolete
-->
<NoWarn>$(NoWarn);IDE0005;IDE0008;IDE0011;IDE0017;IDE0021;IDE0022;IDE0025;IDE0027;IDE0028;IDE0029;IDE0032;IDE0039;IDE0045;IDE0046;IDE0055;IDE0056;IDE0057;IDE0059;IDE0060;IDE0061;IDE0090;IDE0130;IDE0160;IDE0200;IDE0260;IDE0270;IDE0290;IDE0330</NoWarn>
<NoWarn>$(NoWarn);IDE0005;IDE0008;IDE0011;IDE0017;IDE0021;IDE0022;IDE0025;IDE0027;IDE0029;IDE0032;IDE0039;IDE0045;IDE0046;IDE0055;IDE0056;IDE0057;IDE0059;IDE0060;IDE0061;IDE0090;IDE0130;IDE0160;IDE0200;IDE0270;IDE0290;IDE0330</NoWarn>
<NoWarn>$(NoWarn);CA1200;CA1304;CA1305;CA1310;CA1311;CA1507;CA1510;CA1514;CA1710;CA1716;CA1720;CA1725;CA1805;CA1834;CA1845;CA1847;CA1861;CA1862;CA1865;CA1866;CA1870;CA2249;CA2263;SYSLIB0012</NoWarn>
</PropertyGroup>

Expand Down
2 changes: 1 addition & 1 deletion src/NSwag.AspNet.WebApi/JsonExceptionFilterAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public class JsonExceptionFilterAttribute : ActionFilterAttribute
{
private readonly bool _hideStackTrace;
private readonly IDictionary<string, Assembly> _searchedNamespaces;
private readonly List<Type> _exceptionTypes = new List<Type>();
private readonly List<Type> _exceptionTypes = [];

/// <summary>Initializes a new instance of the <see cref="JsonExceptionFilterAttribute"/> class.</summary>
/// <param name="exceptionTypes">The serialized exception types.</param>
Expand Down
2 changes: 1 addition & 1 deletion src/NSwag.AspNetCore/JsonExceptionFilterAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public class JsonExceptionFilterAttribute : ActionFilterAttribute
{
private readonly bool _hideStackTrace;
private readonly IDictionary<string, Assembly> _searchedNamespaces;
private readonly List<Type> _exceptionTypes = new List<Type>();
private readonly List<Type> _exceptionTypes = [];

/// <summary>Initializes a new instance of the <see cref="JsonExceptionFilterAttribute"/> class.</summary>
/// <param name="exceptionTypes">The serialized exception types.</param>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,7 @@ public class OpenApiDocumentMiddleware

private int _version;
private readonly object _documentsCacheLock = new object();
private readonly Dictionary<string, Tuple<string, ExceptionDispatchInfo, DateTimeOffset>> _documentsCache
= new Dictionary<string, Tuple<string, ExceptionDispatchInfo, DateTimeOffset>>();
private readonly Dictionary<string, Tuple<string, ExceptionDispatchInfo, DateTimeOffset>> _documentsCache = [];

/// <summary>Initializes a new instance of the <see cref="OpenApiDocumentMiddleware"/> class.</summary>
/// <param name="nextDelegate">The next delegate.</param>
Expand Down
2 changes: 1 addition & 1 deletion src/NSwag.AspNetCore/OAuth2ClientSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public class OAuth2ClientSettings
public string ScopeSeparator { get; set; } = " ";

/// <summary>Gets or sets initially selected scopes.</summary>
public ICollection<string> Scopes { get; } = new List<string>();
public ICollection<string> Scopes { get; } = [];

/// <summary>Gets or sets the additional query string parameters.</summary>
public IDictionary<string, string> AdditionalQueryStringParameters { get; } = new Dictionary<string, string>();
Expand Down
2 changes: 1 addition & 1 deletion src/NSwag.AspNetCore/SwaggerUiSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ public bool WithCredentials
}

/// <summary>Gets or sets the Swagger URL routes (must start with '/', hides SwaggerRoute).</summary>
public ICollection<SwaggerUiRoute> SwaggerRoutes { get; } = new List<SwaggerUiRoute>();
public ICollection<SwaggerUiRoute> SwaggerRoutes { get; } = [];

/// <summary>Gets or sets the Swagger URL routes factory (SwaggerRoutes is ignored when set).</summary>
#if AspNetOwin
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -374,7 +374,7 @@ private static OpenApiDocument GetOpenApiDocument()
Type = JsonObjectType.String
}
},
Tags = new List<string> { "Secondary" }
Tags = ["Secondary"]
}
}
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ public void When_form_parameters_are_defined_then_FormUrlEncodedContent_is_gener
OpenApiOperationMethod.Post,
new OpenApiOperation
{
Consumes = new System.Collections.Generic.List<string> { "application/x-www-form-urlencoded" },
Consumes = ["application/x-www-form-urlencoded"],
Parameters =
{
new OpenApiParameter
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ public CSharpFileTemplateModel(
_document.Operations.Any(o => o.Operation.ActualResponses.Any(r => r.Value.IsBinary(o.Operation)));

/// <summary>Gets or sets a value indicating whether to generate exception classes (default: true).</summary>
public bool GenerateExceptionClasses => (_settings as CSharpClientGeneratorSettings)?.GenerateExceptionClasses == true;
public bool GenerateExceptionClasses => _settings is CSharpClientGeneratorSettings { GenerateExceptionClasses: true };

/// <summary>Gets or sets a value indicating whether to wrap success responses to allow full response access.</summary>
public bool WrapResponses => _settings.WrapResponses;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ public string MethodAccessModifier
/// <summary>
/// The default value of the result type, i.e. default(T) or default(T)! depending on whether NRT are enabled.
/// </summary>
public string UnwrappedResultDefaultValue => $"default({UnwrappedResultType}){((_settings as CSharpClientGeneratorSettings)?.CSharpGeneratorSettings.GenerateNullableReferenceTypes == true ? "!" : "")}";
public string UnwrappedResultDefaultValue => $"default({UnwrappedResultType}){(_settings is CSharpClientGeneratorSettings { CSharpGeneratorSettings.GenerateNullableReferenceTypes: true } ? "!" : "")}";

/// <summary>Gets or sets the synchronous type of the result.</summary>
public string SyncResultType
Expand Down
14 changes: 8 additions & 6 deletions src/NSwag.CodeGeneration.Tests/CodeGenerationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -315,17 +315,19 @@ private static OpenApiDocument CreateDocument()
var settings = new NewtonsoftJsonSchemaGeneratorSettings();
var generator = new JsonSchemaGenerator(settings);

document.Paths["/Person"] = new OpenApiPathItem();
document.Paths["/Person"][OpenApiOperationMethod.Get] = new OpenApiOperation
document.Paths["/Person"] = new OpenApiPathItem
{
Responses =
[OpenApiOperationMethod.Get] = new OpenApiOperation
{
Responses =
{
"200", new OpenApiResponse
{
Schema = new JsonSchema
"200", new OpenApiResponse
{
Reference = generator.Generate(typeof(Person), new OpenApiSchemaResolver(document, settings))
Schema = new JsonSchema
{
Reference = generator.Generate(typeof(Person), new OpenApiSchemaResolver(document, settings))
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public async Task When_query_parameter_is_enum_array_then_the_enum_is_referenced
{
var serializerSettings = new JsonSerializerSettings
{
Converters = new List<JsonConverter> {new StringEnumConverter()}
Converters = [new StringEnumConverter()]
};

// Arrange
Expand Down
2 changes: 1 addition & 1 deletion src/NSwag.CodeGeneration/JsonSchemaExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public static class JsonSchema4Extensions
/// <returns>true or false</returns>
public static bool UsesComplexObjectSchema(this JsonSchema schema)
{
return UsesComplexObjectSchema(schema, new List<JsonSchema>());
return UsesComplexObjectSchema(schema, []);
}

private static bool UsesComplexObjectSchema(this JsonSchema schema, List<JsonSchema> checkedSchemas)
Expand Down
6 changes: 3 additions & 3 deletions src/NSwag.Commands/NSwagDocumentBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -297,10 +297,10 @@ private static JsonSerializerSettings GetSerializerSettings()
DefaultValueHandling = DefaultValueHandling.Include,
NullValueHandling = NullValueHandling.Include,
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Converters = new List<JsonConverter>
{
Converters =
[
new StringEnumConverter()
}
]
};
}

Expand Down
2 changes: 1 addition & 1 deletion src/NSwag.Commands/OpenApiDocumentExecutionResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ namespace NSwag.Commands
/// <summary>Stores the result of a <see cref="OpenApiDocument"/> execution.</summary>
public class OpenApiDocumentExecutionResult
{
private readonly Dictionary<Type, string> _generatorOutputs = new Dictionary<Type, string>();
private readonly Dictionary<Type, string> _generatorOutputs = [];

/// <summary>Initializes a new instance of the <see cref="NSwagDocumentBase"/> class.</summary>
/// <param name="output">The command line output.</param>
Expand Down
2 changes: 1 addition & 1 deletion src/NSwag.Core.Tests/SwaggerResponseTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public void When_response_contains_produces_detect_if_binary_response(string con
// Arrange
var response = new OpenApiResponse();
var operation = new OpenApiOperation();
operation.Produces = new System.Collections.Generic.List<string> { contentType };
operation.Produces = [contentType];
operation.Responses.Add("200", response);

// Act
Expand Down
2 changes: 1 addition & 1 deletion src/NSwag.Core/Collections/ObservableDictionary.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public class ObservableDictionary<TKey, TValue> :
/// <summary>Initializes a new instance of the <see cref="ObservableDictionary{TKey, TValue}"/> class. </summary>
public ObservableDictionary()
{
_dictionary = new Dictionary<TKey, TValue>();
_dictionary = [];
}

/// <summary>Initializes a new instance of the <see cref="ObservableDictionary{TKey, TValue}"/> class. </summary>
Expand Down
18 changes: 9 additions & 9 deletions src/NSwag.Core/OpenApiDocument.Serialization.cs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ private static PropertyRenameAndIgnoreSerializerContractResolver CreateJsonSeria
return resolver;
}

private ObservableCollection<OpenApiSchema> _schemes = new ObservableCollection<OpenApiSchema>();
private ObservableCollection<OpenApiSchema> _schemes = [];

/// <summary>Gets or sets the host (name or ip) serving the API (Swagger only).</summary>
[JsonProperty(PropertyName = "host", Order = 5, DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]
Expand Down Expand Up @@ -149,13 +149,13 @@ public ICollection<OpenApiSchema> Schemes
_schemes = new ObservableCollection<OpenApiSchema>(Servers?
.Where(s => s.Url.Contains("://"))
.Select(s => s.Url.StartsWith("http://") ? OpenApiSchema.Http : OpenApiSchema.Https)
.Distinct() ?? new List<OpenApiSchema>());
.Distinct() ?? []);

_schemes.CollectionChanged += OnSchemesChanged;

return _schemes;
}
set { UpdateServers(value, Host, BasePath); }
set => UpdateServers(value, Host, BasePath);
}

private void OnSchemesChanged(object sender, NotifyCollectionChangedEventArgs e)
Expand All @@ -167,30 +167,30 @@ private void UpdateServers(ICollection<OpenApiSchema> schemes, string host, stri
{
if ((schemes == null || schemes.Count == 0) && (!string.IsNullOrEmpty(host) || !string.IsNullOrEmpty(basePath)))
{
Servers = new List<OpenApiServer>
{
Servers =
[
new OpenApiServer
{
Url = host + basePath
}
};
];
}
else
{
Servers = schemes?.Select(s => new OpenApiServer
{
Url = s.ToString().ToLowerInvariant() + "://" + host + basePath
}).ToList() ?? new List<OpenApiServer>();
}).ToList() ?? [];
}
}

/// <summary>Gets or sets a list of MIME types the operation can consume.</summary>
[JsonProperty(PropertyName = "consumes", Order = 8, DefaultValueHandling = DefaultValueHandling.Ignore)]
public ICollection<string> Consumes { get; set; } = new List<string>();
public ICollection<string> Consumes { get; set; } = [];

/// <summary>Gets or sets a list of MIME types the operation can produce.</summary>
[JsonProperty(PropertyName = "produces", Order = 9, DefaultValueHandling = DefaultValueHandling.Ignore)]
public ICollection<string> Produces { get; set; } = new List<string>();
public ICollection<string> Produces { get; set; } = [];

/// <summary>Gets or sets the types (Swagger only).</summary>
[JsonProperty(PropertyName = "definitions", Order = 13, DefaultValueHandling = DefaultValueHandling.Ignore)]
Expand Down
6 changes: 3 additions & 3 deletions src/NSwag.Core/OpenApiDocument.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public OpenApiDocument()

/// <summary>Gets or sets the servers (OpenAPI only).</summary>
[JsonProperty(PropertyName = "servers", Order = 10, DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]
public ICollection<OpenApiServer> Servers { get; private set; } = new Collection<OpenApiServer>();
public ICollection<OpenApiServer> Servers { get; private set; } = [];

/// <summary>Gets or sets the operations.</summary>
[JsonProperty(PropertyName = "paths", Order = 11, DefaultValueHandling = DefaultValueHandling.Ignore)]
Expand All @@ -87,11 +87,11 @@ public OpenApiDocument()

/// <summary>Gets or sets a security description.</summary>
[JsonProperty(PropertyName = "security", Order = 17, DefaultValueHandling = DefaultValueHandling.Ignore)]
public ICollection<OpenApiSecurityRequirement> Security { get; set; } = new Collection<OpenApiSecurityRequirement>();
public ICollection<OpenApiSecurityRequirement> Security { get; set; } = [];

/// <summary>Gets or sets the description.</summary>
[JsonProperty(PropertyName = "tags", Order = 18, DefaultValueHandling = DefaultValueHandling.Ignore)]
public IList<OpenApiTag> Tags { get; set; } = new Collection<OpenApiTag>();
public IList<OpenApiTag> Tags { get; set; } = [];

/// <summary>Gets the base URL of the web service.</summary>
[JsonIgnore]
Expand Down
2 changes: 1 addition & 1 deletion src/NSwag.Core/OpenApiEncoding.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public class OpenApiEncoding

/// <summary>Gets or sets the headers.</summary>
[JsonProperty(PropertyName = "headers", DefaultValueHandling = DefaultValueHandling.Ignore)]
public OpenApiHeaders Headers { get; } = new OpenApiHeaders();
public OpenApiHeaders Headers { get; } = [];

/// <summary>Gets or sets the encoding type.</summary>
[JsonProperty(PropertyName = "style", DefaultValueHandling = DefaultValueHandling.Ignore)]
Expand Down
6 changes: 3 additions & 3 deletions src/NSwag.Core/OpenApiOperation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public class OpenApiOperation : JsonExtensionObject
/// <summary>Initializes a new instance of the <see cref="OpenApiPathItem"/> class.</summary>
public OpenApiOperation()
{
Tags = new List<string>();
Tags = [];

var parameters = new ObservableCollection<OpenApiParameter>();
parameters.CollectionChanged += (sender, args) =>
Expand Down Expand Up @@ -152,7 +152,7 @@ public IReadOnlyList<OpenApiParameter> ActualParameters

/// <summary>Gets or sets the servers (OpenAPI only).</summary>
[JsonProperty(PropertyName = "servers", Order = 15, DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]
public ICollection<OpenApiServer> Servers { get; set; } = new Collection<OpenApiServer>();
public ICollection<OpenApiServer> Servers { get; set; } = [];

/// <summary>Gets the list of MIME types the operation can consume, either from the operation or from the <see cref="OpenApiDocument"/>.</summary>
[JsonIgnore]
Expand Down Expand Up @@ -184,7 +184,7 @@ public void TryAddConsumes(string mimeType)
{
if (Consumes == null)
{
Consumes = new List<string> { mimeType };
Consumes = [mimeType];
}
else if (!Consumes.Contains(mimeType))
{
Expand Down
4 changes: 2 additions & 2 deletions src/NSwag.Core/OpenApiPathItem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,11 @@ public OpenApiPathItem()

/// <summary>Gets or sets the servers (OpenAPI only).</summary>
[JsonProperty(PropertyName = "servers", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]
public ICollection<OpenApiServer> Servers { get; set; } = new Collection<OpenApiServer>();
public ICollection<OpenApiServer> Servers { get; set; } = [];

/// <summary>Gets or sets the parameters.</summary>
[JsonProperty(PropertyName = "parameters", DefaultValueHandling = DefaultValueHandling.Ignore)]
public ICollection<OpenApiParameter> Parameters { get; set; } = new Collection<OpenApiParameter>();
public ICollection<OpenApiParameter> Parameters { get; set; } = [];

/// <summary>Gets or sets the extension data (i.e. additional properties which are not directly defined by the JSON object).</summary>
[JsonExtensionData]
Expand Down
2 changes: 1 addition & 1 deletion src/NSwag.Core/OpenApiResponse.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public class OpenApiResponse : JsonReferenceBase<OpenApiResponse>, IJsonReferenc

/// <summary>Gets or sets the headers.</summary>
[JsonProperty(PropertyName = "headers", Order = 3, DefaultValueHandling = DefaultValueHandling.Ignore)]
public OpenApiHeaders Headers { get; } = new OpenApiHeaders();
public OpenApiHeaders Headers { get; } = [];

/// <summary>Sets a value indicating whether the response can be null (use IsNullable() to get a parameter's nullability).</summary>
/// <remarks>The Swagger spec does not support null in schemas, see https://github.com/OAI/OpenAPI-Specification/issues/229 </remarks>
Expand Down
2 changes: 1 addition & 1 deletion src/NSwag.Core/OpenApiServerVariable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public class OpenApiServerVariable
{
/// <summary>Gets or sets the enum of the server.</summary>
[JsonProperty(PropertyName = "enum", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]
public ICollection<string> Enum { get; } = new Collection<string>();
public ICollection<string> Enum { get; } = [];

/// <summary>Gets or sets the variables of the server.</summary>
[JsonProperty(PropertyName = "default", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ private AspNetCoreOperationProcessorContext GetContext(ApiDescription apiDescrip
generator,
schemaResolver,
settings,
new List<OpenApiOperationDescription>())
[])
{
ApiDescription = apiDescription,
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,7 @@ private List<Tuple<OpenApiOperationDescription, ApiDescription, MethodInfo>> Add
var path = operation.Path.Replace("//", "/");
if (!document.Paths.TryGetValue(path, out var pathItem))
{
document.Paths[path] = pathItem = new OpenApiPathItem();
document.Paths[path] = pathItem = [];
}

if (pathItem.ContainsKey(operation.Method))
Expand Down
Loading

0 comments on commit 8ff1c5d

Please sign in to comment.