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 @@ -3214,4 +3214,93 @@ class C
public string Goo { get => field ?? throw new System.InvalidOperationException(); } = "";
}
""" + s_allowNullAttribute);

[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/81320")]
public Task TestStaticFieldWrittenInInstanceConstructor_ReadOnlyProperty()
=> TestInRegularAndScriptAsync(
"""
public sealed class Test
{
[|private static Test? s_instance;|]
public static Test Instance => s_instance!;

public Test()
{
s_instance = this;
}
}
""",
"""
public sealed class Test
{
public static Test Instance { get => field!; private set; }

public Test()
{
Instance = this;
}
}
""");

[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/XXXXX")]
public Task TestStaticFieldWrittenInStaticConstructor_ReadOnlyProperty()
=> TestInRegularAndScriptAsync(
"""
public sealed class Test
{
[|private static Test? s_instance;|]
public static Test Instance => s_instance!;

static Test()
{
s_instance = new Test();
}
}
""",
"""
public sealed class Test
{
public static Test Instance => field!;

static Test()
{
Instance = new Test();
}
}
""");

[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/XXXXX")]
public Task TestStaticFieldWrittenInInstanceConstructor_WithSetter()
=> TestInRegularAndScriptAsync(
"""
public sealed class Test
{
[|private static Test? s_instance;|]
public static Test Instance
{
get => s_instance!;
set => s_instance = value;
}

public Test()
{
s_instance = this;
}
}
""",
"""
public sealed class Test
{
public static Test Instance
{
get => field!;
set;
}

public Test()
{
Instance = this;
}
}
""");
}
Original file line number Diff line number Diff line change
Expand Up @@ -484,9 +484,12 @@ private async Task<SyntaxNode> FormatAsync(
CancellationToken cancellationToken)
{
var isWrittenOutsideConstructor = false;

// Only include constructors that match the static-ness of the field. For a static field, only static
// constructors are relevant. For an instance field, only instance constructors are relevant.
var constructorSpans = field.ContainingType
.GetMembers()
.Where(m => m.IsConstructor())
.Where(m => field.IsStatic ? m.IsStaticConstructor() : m.IsConstructor())
.SelectMany(c => c.DeclaringSyntaxReferences)
.Select(s => s.GetSyntax(cancellationToken))
.Select(n => n.FirstAncestorOrSelf<TConstructorDeclaration>())
Expand Down
Loading