Repository navigation
Scope Guards
ScopeGuard and ScopeGuard<TState> are stack-allocated ref struct types that run cleanup logic immediately when leaving a using scope—even on early return or exceptions—with zero heap allocations.
In vanilla .NET, ad-hoc cleanup for resources that don't implement IDisposable (temp files, ArrayPool<T> buffers, feature-flag overrides, or transaction rollbacks) usually means nested try/finally blocks with manual bool committed flags, or allocating a throwaway IDisposable wrapper class:
// Vanilla C#: nested try/finally + manual boolean bookkeeping
byte[] buffer = ArrayPool<byte>.Shared.Rent(4096);
bool committed = false;
string tempFile = Path.GetTempFileName();
try
{
WritePayload(tempFile, buffer);
await UploadAsync(tempFile);
File.Move(tempFile, finalPath, overwrite: true);
committed = true;
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
if (!committed && File.Exists(tempFile))
{
File.Delete(tempFile);
}
}With Ferrous.Guard, cleanup stays right next to acquisition, runs in reverse (LIFO) order on every exit path, and Dismiss() disarms rollback cleanly once the operation succeeds:
using System.Buffers;
using Ferrous.Guard;
byte[] buffer = ArrayPool<byte>.Shared.Rent(4096);
using var returnBuf = ScopeGuard.Defer(buffer, static b => ArrayPool<byte>.Shared.Return(b));
string tempFile = Path.GetTempFileName();
using var deleteTemp = ScopeGuard.Defer(tempFile, static path =>
{
if (File.Exists(path))
{
File.Delete(path);
}
});
WritePayload(tempFile, buffer);
File.Move(tempFile, finalPath, overwrite: true);
deleteTemp.Dismiss(); // Commit succeeded; keep the moved file, still return buffer!Note: Because
ScopeGuardis aref struct, it cannot be held acrossawait(for async methods, place synchronous critical sections in a helper or use atry/finallyaround theawait).
| Concern | Vanilla .NET (try/finally or IDisposable wrapper) |
ScopeGuard / ScopeGuard<TState>
|
|---|---|---|
| Heap allocations | Custom IDisposable class allocates on every call; capturing lambdas allocate closures |
0 bytes on the heap when using ScopeGuard.Defer(state, static s => ...)
|
| Locality | Cleanup is pushed to the bottom of the method | Cleanup is declared on the line immediately after acquisition |
Forgotten using |
Easy to forget to dispose a helper |
[MustUse] triggers FE0001 at compile time if you forget using var
|
| Accidental closure alloc | Silent heap allocation |
FE0403 (Ferrous.Pedantic) warns if a capturing lambda is passed to ScopeGuard.Defer(Action)
|
| Commit / rollback | Manual bool succeeded flags |
Built-in guard.Dismiss()
|
Ferrous — Rust quality-of-life primitives, source generators, and analyzers for .NET (.NET 10 / .NET 11, NativeAOT-ready, MIT License).