π§Ή using var x = new MyRefStruct();
Ref structs couldn’t implement interfaces. C# 8 allows ref structs to implement IDisposable. Use ‘using’ with stack-only types.
π Disposable Ref Struct
public ref struct FileHandle
{
private IntPtr _handle;
public FileHandle(string path)
{
_handle = OpenFile(path);
}
public void Dispose()
{
if (_handle != IntPtr.Zero)
{
CloseFile(_handle);
_handle = IntPtr.Zero;
}
}
}
// Usage
using var handle = new FileHandle("data.bin");
// handle automatically disposed at end of scope
π― Using with Span
public ref struct BufferScope
{
private Span<byte> _buffer;
private bool _disposed;
public BufferScope(int size)
{
_buffer = new Span<byte>(new byte[size]);
}
public Span<byte> Buffer => _buffer;
public void Dispose()
{
if (!_disposed)
{
// Clear sensitive data
_buffer.Clear();
_disposed = true;
}
}
}
// Usage
using var buffer = new BufferScope(1024);
ProcessData(buffer.Buffer);
// Buffer cleared automatically
π‘ Benefits
- Stack-only allocation (no heap)
- Deterministic cleanup with using
- Zero GC pressure
- Perfect for native resources, temporary buffers
“Disposable ref structs = stack allocation + deterministic cleanup. Perfect for high-performance code. Used in my parser, allocations dropped to zero.”
