diff --git a/src/NJsonSchema.CodeGeneration.CSharp/Models/PropertyModel.cs b/src/NJsonSchema.CodeGeneration.CSharp/Models/PropertyModel.cs index ad274e12d..38efb2c17 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp/Models/PropertyModel.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp/Models/PropertyModel.cs @@ -65,6 +65,9 @@ public PropertyModel( /// Gets a value indicating whether the property is nullable. public override bool IsNullable => (_settings.GenerateOptionalPropertiesAsNullable && !_property.IsRequired) || base.IsNullable; + /// Gets a value indicating whether the property's corresponding constructor parameter should be optional. + public bool RenderOptionalCtorArgument => IsNullable && !_property.IsRequired; + /// Gets or sets a value indicating whether empty strings are allowed. public bool AllowEmptyStrings => _property.ActualTypeSchema.Type.IsString() && @@ -336,4 +339,4 @@ private static string GetRangeType(string? propertyFormat) => _ => "double", }; } -} \ No newline at end of file +} diff --git a/src/NJsonSchema.CodeGeneration.CSharp/Templates/Class.Constructor.Record.liquid b/src/NJsonSchema.CodeGeneration.CSharp/Templates/Class.Constructor.Record.liquid index f88b7e1b9..627e4bd24 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp/Templates/Class.Constructor.Record.liquid +++ b/src/NJsonSchema.CodeGeneration.CSharp/Templates/Class.Constructor.Record.liquid @@ -5,7 +5,7 @@ {%- assign parentProperties = "" | empty %} {% endif %} -{%- assign sortedProperties = AllProperties | sort: "Name" %} +{%- assign sortedProperties = AllProperties | sort: "RenderOptionalCtorArgument", "Name" %} {%- assign sortedParentProperties = parentProperties | sort: "Name" %} {%- if UseSystemTextJson %} @@ -13,7 +13,7 @@ {%- else %} [Newtonsoft.Json.JsonConstructor] {%- endif %} -{% if IsAbstract %}protected{% else %}public{% endif %} {{ClassName}}({% for property in sortedProperties %}{%- if skipComma %}{%- assign skipComma = false %}{% else %}, {% endif %}{{ property.Type }} @{{ property.PropertyName | lowercamelcase }}{% endfor %}) +{% if IsAbstract %}protected{% else %}public{% endif %} {{ClassName}}({% for property in sortedProperties %}{%- if skipComma %}{%- assign skipComma = false %}{% else %}, {% endif %}{{ property.Type }} @{{ property.PropertyName | lowercamelcase }}{% if property.RenderOptionalCtorArgument %} = null{% endif %}{% endfor %}) {%- assign skipComma = true %} {%- if HasInheritance %} : base({%- for property in sortedParentProperties %}{%- if skipComma %}{%- assign skipComma = false %}{% else %}, {% endif %}{{ property.PropertyName | lowercamelcase }}{%- endfor %})