Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Let non-required, nullable properties of Record classes be C#-optiona… #1665

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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