Skip to content

Commit

Permalink
Generate field for const arrays in constructor declarations (#7231)
Browse files Browse the repository at this point in the history
  • Loading branch information
CollinAlpert authored Jun 7, 2024
1 parent be1b0f0 commit 4d5fd9d
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ private static async Task<Document> ExtractConstArrayAsync(Document document, Sy
// Get method containing the symbol that is being diagnosed
IOperation? methodContext = arrayArgument.GetAncestor<IMethodBodyOperation>(OperationKind.MethodBody);
methodContext ??= arrayArgument.GetAncestor<IBlockOperation>(OperationKind.Block); // VB methods have a different structure than CS methods
methodContext ??= arrayArgument.GetAncestor<IConstructorBodyOperation>(OperationKind.ConstructorBody);

// Create the new member
SyntaxNode newMember = generator.FieldDeclaration(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1053,5 +1053,38 @@ partial class Program
}
}.RunAsync();
}

[Fact, WorkItem(7216, "https://github.com/dotnet/roslyn-analyzers/issues/7216")]
public Task BaseDeclaration_Diagnostic()
{
const string code = """
public class Class1
{
public Class1(int[] arr) { }
}
public class Class2 : Class1
{
public Class2()
: base([|new int[] { 1, 2, 3 }|]) { }
}
""";
const string fixedCode = """
public class Class1
{
public Class1(int[] arr) { }
}
public class Class2 : Class1
{
private static readonly int[] arr = new int[] { 1, 2, 3 };
public Class2()
: base(arr) { }
}
""";

return VerifyCS.VerifyCodeFixAsync(code, fixedCode);
}
}
}

0 comments on commit 4d5fd9d

Please sign in to comment.