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 @@ -3530,4 +3530,33 @@ public unsafe void ToUnmanaged()
ReferenceAssemblies = ReferenceAssemblies.Net.Net90,
}.RunAsync();
}

[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/77251")]
public async Task TestRefFieldWrittenNotRead()
{
await new VerifyCS.Test
{
TestCode = """
public readonly ref struct RefScope<T>
{
public RefScope(ref T originalvalue, T newvalue)
{
_OriginalValue = originalvalue;
_Reference = ref originalvalue;
originalvalue = newvalue;
}

readonly ref T _Reference; // Should get no diagnostic here.
readonly T _OriginalValue;

public void Dispose()
{
_Reference = _OriginalValue;
}
}
""",
LanguageVersion = LanguageVersion.CSharp13,
ReferenceAssemblies = ReferenceAssemblies.Net.Net90,
}.RunAsync();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -583,8 +583,16 @@ private void OnSymbolEnd(SymbolAnalysisContext symbolEndContext, bool hasUnsuppo
continue;

// Do not flag ref-fields that are not read. A ref-field can exist to have side effects by
// writing into some other location when a write happens to it.
if (member is IFieldSymbol { IsReadOnly: false, RefKind: RefKind.Ref })
// writing into some other location when a write happens to it. Note: this includes `readonly
// ref` fields as well. It's still legal to assign a normal value into a `readonly ref` field.
// It's just not allowed to overwrite it *with another ref*. In other words:
//
// _readonlyRefField = value; // is fine.
// _readonlyRefField = ref value; // is not.
//
// So as long as it is a ref-field, we don't care if it is unread, but is written to. We must
// continue allowing it.
if (member is IFieldSymbol { RefKind: RefKind.Ref })
continue;
}

Expand Down
Loading