Skip to content

Commit

Permalink
Let non-required, nullable properties of Record classes be C#-optiona…
Browse files Browse the repository at this point in the history
…l in the constructor
  • Loading branch information
adamjones2 committed Jan 11, 2024
1 parent 3585d60 commit 8ca8446
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 2 deletions.
3 changes: 3 additions & 0 deletions src/NJsonSchema.CodeGeneration.CSharp/Models/PropertyModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,9 @@ public class PropertyModel : PropertyModelBase
/// <summary>Gets a value indicating whether the property is nullable.</summary>
public override bool IsNullable => (_settings.GenerateOptionalPropertiesAsNullable && !_property.IsRequired) || base.IsNullable;

/// <summary>Gets a value indicating whether the property's corresponding constructor parameter should be optional.</summary>
public bool RenderOptionalCtorArgument => IsNullable && _property.IsRequired;

/// <summary>Gets or sets a value indicating whether empty strings are allowed.</summary>
public bool AllowEmptyStrings =>
_property.ActualTypeSchema.Type.IsString() &&
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@
{%- assign parentProperties = "" | empty %}
{% endif %}

{%- assign sortedProperties = AllProperties | sort: "Name" %}
{%- assign sortedProperties = AllProperties | sort: "RenderOptionalCtorArgument", "Name" %}
{%- assign sortedParentProperties = parentProperties | sort: "Name" %}

{%- if UseSystemTextJson %}
[System.Text.Json.Serialization.JsonConstructor]
{%- 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.Name | lowercamelcase }}{% endfor %})
{% if IsAbstract %}protected{% else %}public{% endif %} {{ClassName}}({% for property in sortedProperties %}{%- if skipComma %}{%- assign skipComma = false %}{% else %}, {% endif %}{{ property.Type }} @{{ property.Name | 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.Name | lowercamelcase }}{%- endfor %})
Expand Down

0 comments on commit 8ca8446

Please sign in to comment.