NSwag
NSwag copied to clipboard
`string` should be `string?` for optional properties if `"generateOptionalPropertiesAsNullable": true`
NSwagStudio v13.16.1.0
Runtime: Net60 Outputs: CSharpClient Settings:
"generateOptionalPropertiesAsNullable": true,
"generateNullableReferenceTypes": true,
According to its docs, the Newtonsoft.Json.Required.DisallowNull
enum value means:
The property is not required but it cannot be a null value.
so then properties that are marked that way are "optional".
For (EDIT: some) value type properties, the generated outputs is:
[Newtonsoft.Json.JsonProperty("repaymentType", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
[System.ComponentModel.DataAnnotations.StringLength(3)]
public string RepaymentType { get; set; } = default!;
[Newtonsoft.Json.JsonProperty("numberOfInstallments", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
[System.ComponentModel.DataAnnotations.Range(1, 99999)]
public int NumberOfInstallments { get; set; } = default!;
This is wrong: string
should be string?
and int
should be int?
for these optional properties.
For nullable reference types and enum
s it always looks OK:
[Newtonsoft.Json.JsonProperty("installmentAmount", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
public MoneyAmount? InstallmentAmount { get; set; } = default!;
EDIT: wow, weird. At some places in the code, string?
IS used correctly:
/// <summary>
/// The name of the institution that provides the income.
/// </summary>
[Newtonsoft.Json.JsonProperty("institutionName", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
[System.ComponentModel.DataAnnotations.StringLength(30)]
public string? InstitutionName { get; set; } = default!;
Help for finding were to fix it:
- It seems that if a property has a
<summary>
, then it is generated correctly (as nullable, with?
). - If there is no summary, it is generated wrongly (without
?
, as non-nullable).
I have more than 15 cases of both and without exception!