Skip to content

System.Text.Json generator does not generate valid code for empty string default parameter constructors #62766

@333fred

Description

@333fred

Description

As the title says, when there is a get-only property with an empty string as the default parameter in the constructor, the generator generates invalid C# code.

Reproduction Steps

Attempt to compile the following code:

using System.Text.Json.Serialization;

public class Test
{
    public string Property { get; }

    public Test(string property = "") { Property = property; }
}

[JsonSerializable(typeof(Test))]
public partial class Context : JsonSerializerContext
{
}

Expected behavior

The code compiles.

Actual behavior

1>C:\temp\System.Text.Json.SourceGeneration\System.Text.Json.SourceGeneration.JsonSourceGenerator\Context.Test.g.cs(92,31,92,31): error CS1525: Invalid expression term '}'

It appears the generator is generating the following invalid object initializer:

        private static global::System.Text.Json.Serialization.Metadata.JsonParameterInfoValues[] TestCtorParamInit()
        {
            global::System.Text.Json.Serialization.Metadata.JsonParameterInfoValues[] parameters = new global::System.Text.Json.Serialization.Metadata.JsonParameterInfoValues[1];
            global::System.Text.Json.Serialization.Metadata.JsonParameterInfoValues info;
        
            info = new()
            {
                Name = "property",
                ParameterType = typeof(global::System.String),
                Position = 0,
                HasDefaultValue = true,
                DefaultValue = 
            };
            parameters[0] = info;
        
            return parameters;
        }

Regression?

No

Known Workarounds

Don't use empty strings as the default value.

Configuration

.NET 6.0.100.

Other information

No response

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions