Skip to content

Fix crash when converting primary constructor to normal constructor #78234

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

Merged
merged 1 commit into from
Apr 22, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,9 @@ void AddConstructorDeclaration()

async Task RewritePrimaryConstructorParameterReferencesAsync()
{
using var _ = PooledHashSet<EqualsValueClauseSyntax>.GetInstance(out var removedInitializers);
removedInitializers.AddRange(initializedFieldsAndProperties.Select(t => t.initializer));

foreach (var (parameter, references) in parameterReferences)
{
// Only have to update references if we're synthesizing a field for this parameter.
Expand All @@ -364,6 +367,12 @@ async Task RewritePrimaryConstructorParameterReferencesAsync()

foreach (var identifierName in grouping)
{
// Don't both updating an identifier that was in a node we already decided to explicitly remove. For
// example, if we have `int Prop { get; } = p;` and we already deleted `= p`, then no need to update
// the `p` reference here.
if (identifierName.GetAncestors<EqualsValueClauseSyntax>().Any(removedInitializers.Contains))
continue;

var xmlElement = identifierName.AncestorsAndSelf().OfType<XmlEmptyElementSyntax>().FirstOrDefault();
if (xmlElement is { Name.LocalName.ValueText: "paramref" })
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2757,4 +2757,49 @@ public void Goo() { }
LanguageVersion = LanguageVersionExtensions.CSharpNext,
}.RunAsync();
}

[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76981")]
public async Task TestConvertWithReferencesToParameter1()
{
await new VerifyCS.Test
{
TestCode = """
namespace N
{
internal class [|Goo(int bar)|]
{
public int Bar { get; private set; } = bar;

public void Baz()
{
Bar = bar;
}
}
}
""",
FixedCode = """
namespace N
{
internal class Goo
{
private readonly int bar;

public Goo(int bar)
{
this.bar = bar;
Bar = bar;
}

public int Bar { get; private set; }

public void Baz()
{
Bar = bar;
}
}
}
""",
LanguageVersion = LanguageVersionExtensions.CSharpNext,
}.RunAsync();
}
}
Loading