Skip to content
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 @@ -5,6 +5,7 @@
#nullable disable

using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
Expand All @@ -28,7 +29,13 @@ protected override Task<Document> IntroduceFieldAsync(
bool isConstant,
CancellationToken cancellationToken)
{
var oldTypeDeclaration = expression.GetAncestorOrThis<TypeDeclarationSyntax>();
// Get the ancestor TypeDeclarationSyntax that is NOT an ExtensionBlockDeclarationSyntax.
// Extension blocks can't contain fields, so we need to find the containing class/struct.
//
// Note, this can be revised in the future as we do expect to allow constants/static in
// extension blocks in a future version of the language.
var oldTypeDeclaration = expression.GetAncestorsOrThis<TypeDeclarationSyntax>()
.FirstOrDefault(t => t is not ExtensionBlockDeclarationSyntax);

var oldType = oldTypeDeclaration != null
? document.SemanticModel.GetDeclaredSymbol(oldTypeDeclaration, cancellationToken)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8559,4 +8559,64 @@ public Customer* D
}
}
""");

[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/81337")]
public Task TestExtensionBlockIntroduceConstant()
=> TestInRegularAndScriptAsync(
"""
public static class CEx
{
extension(C c)
{
public string P => c[[|"P"|]];
}
}

public class C { public string this[string k] => ""; }
""",
"""
public static class CEx
{
private const string {|Rename:V|} = "P";

extension(C c)
{
public string P => c[V];
}
}

public class C { public string this[string k] => ""; }
""",
new(parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp14)));

[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/81337")]
public Task TestExtensionBlockIntroduceConstant_AllOccurrences()
=> TestInRegularAndScriptAsync(
"""
public static class CEx
{
extension(C c)
{
public string P => c[[|"P"|]];
public string P2 => c["P"];
}
}

public class C { public string this[string k] => ""; }
""",
"""
public static class CEx
{
private const string {|Rename:V|} = "P";

extension(C c)
{
public string P => c[V];
public string P2 => c[V];
}
}

public class C { public string this[string k] => ""; }
""",
new(parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp14), index: 1));
}
Loading