Skip to content

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

Closed

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

Activity

  1. ghost added
    untriaged
    on Dec 14, 2021
  2. added
    source-generator
    and removed
    untriaged
    on Dec 14, 2021
  3. self-assigned this
    on Dec 14, 2021
  4. added this to the 6.0.x milestone on Dec 14, 2021
  5. layomia commented on Dec 14, 2021

    @layomia
    Contributor

    I was able to repro.
    6.0.x candidate as we are preventing successful compilation for a trivial/common scenario.

  6. ghost added
    in-pr
    on Dec 14, 2021
  7. ghost removed
    in-pr
    on Jan 6, 2022
  8. layomia commented on Jan 7, 2022

    @layomia
    Contributor

    Re-opening for 6.0 consideration.

  9. ghost locked as resolved and limited conversation to collaborators on Feb 6, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area-System.Text.Jsonbugsource-generator

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions