Skip to content

UseRequiredKeyword fails to generate default values for non-nullable, non-required properties when RespectNullable is true, resulting in generated code that will not compile in projects that use #nullable enable #5384

Description

@KirkMunroSagent

Describe the bug

In Class.liquid (line 110, identical in 11.5.2 and 11.6.1):

public {% if UseRequiredKeyword and property.IsRequired %}required {% endif %}{{
property.Type }} {{ property.PropertyName }}{% if RenderInpc == false and RenderPrism == false %} { get; {% if property.HasSetter and RenderRecord ==
false %}{{ WriteAccessor }}; {% elsif RenderRecord and GenerateNativeRecords %}init; {% endif %}}{% if property.HasDefaultValue and RenderRecord ==
false and UseRequiredKeyword == false %} = {{ property.DefaultValue }};{% elsif GenerateNullableReferenceTypes and RenderRecord == false and
UseRequiredKeyword == false %} = default!;{% endif %}
  • required is emitted only when UseRequiredKeyword AND property.IsRequired.
  • = default!; is emitted only when UseRequiredKeyword == false.

So with UseRequiredKeyword = true, a property that is non-nullable but not required (Required.DisallowNull) gets neither required nor = default!; → error CS8618.

Existing tests only cover required props and optional-nullable props, but not "optional-but-non-nullable" props.

Version of NSwag toolchain, computer and .NET runtime used

NSwag 14.17.1, .NET 10 on Windows 11.

To Reproduce

Just extend your unit tests for UseRequiredKeyword to include a single non-null, non-required property.

Expected behavior

It doesn't matter if such properties really should be nullable. This scenario does happen, so the generator should initialize such properties even if UseRequiredKeyword is true, using a value of default!.

Additional context

The suggested fix for this is simple:

Emit the initializer whenever the property will NOT receive the required keyword, i.e. change the two template guards from:

and UseRequiredKeyword == false

to:

and not (UseRequiredKeyword and property.IsRequired)

Please fix this in the next release.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions