Skip to content

Cannot use ConfigurationBinder source generator with a type that has a string ctor parameter with default value #93159

Closed

Description

@ericstj

Description

When binding to a type with a constructor that has a default string parameter, the generator emits code that doesn't compile.

C:\scratch\configStringCtorParam\Microsoft.Extensions.Configuration.Binder.SourceGeneration\Microsoft.Extensions.Config
uration.Binder.SourceGeneration.ConfigurationBindingGenerator\BindingExtensions.g.cs(77,27): error CS0103: The name 's'
 does not exist in the current context [C:\scratch\configStringCtorParam\configStringCtorParam.csproj]

The code generated looks like this:

 public static SD InitializeSD(IConfiguration configuration, BinderOptions? binderOptions)
        {
            if (configuration["S"] is string value1)
            {
                string s = value1;
            }

            return new SD(s);
        }

Bug is likely in the EmitBindImplForMember method but I haven't tracked it down. I suspect there's a disagreement between the case where the member is string parseable but also has a default value. This same repro works when removing the default value.

Reproduction Steps

using Microsoft.Extensions.Configuration;
var c = new ConfigurationBuilder().Build();
var x = c.Get<SD>();
Console.WriteLine(x);

public class SD
{
    public SD(string s = "default value") { S = s; }
    public string S { get;}
    public override string ToString() => S;
}

Expected behavior

Compiles successfully.

Actual behavior

Compilation failure.

Regression?

No

Known Workarounds

Remove default value from ctor param.

Configuration

No response

Other information

No response

Activity

  1. ghost added
    untriaged
    on Oct 7, 2023
  2. added this to the 9.0.0 milestone on Oct 7, 2023
  3. ghost removed
    untriaged
    on Oct 7, 2023
  4. added
    source-generator
    on Oct 7, 2023
  5. modified the milestones: 9.0.0, 8.0.0 on Oct 9, 2023
  6. modified the milestones: 8.0.0, 9.0.0 on Oct 10, 2023
  7. ghost added
    in-pr
    on Oct 16, 2023
  8. ghost removed
    in-pr
    on Nov 6, 2023
  9. ghost locked as resolved and limited conversation to collaborators on Dec 6, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-Extensions-Configurationsource-generator

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions