capypad
0 day streak
csharp / expert
Snippet

Ref Fields and Scoped Lifetime Tracking

C# 11 introduced 'ref fields' within 'ref structs', allowing stack-allocated structures to hold references to other variables. To prevent dangling references, the 'scoped' keyword ensures that a reference cannot escape the current method or be assigned to a field with a longer lifetime, enabling safe, pointer-free high-performance memory management.

snippet.csharp
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public ref struct ReferenceTracker {
public ref int Value;
public void Update(scoped ref int newValue) {
// Error if newValue has a shorter lifetime than the struct
this.Value = ref newValue;
}
}
 
public void Process() {
int local = 10;
var tracker = new ReferenceTracker();
tracker.Update(ref local); // Valid: local lives as long as tracker
}
Breakdown
1
public ref struct ReferenceTracker
A stack-only structure that can contain ref fields (C# 11 feature).
2
public ref int Value;
A field that stores a reference to an integer, not just the value.
3
scoped ref int newValue
Ensures the reference 'newValue' does not outlive the scope of the method call.