Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
C#

C#: Fix an IDisposable Struct That Gets Silently Boxed and Never Disposed Because It Was Passed Through an Interface Reference

- 11.10.26 - ErcanOPAK

🔧 The IDisposable Struct That Never Got Disposed

A struct implementing IDisposable is often chosen specifically to avoid a heap allocation, and that works fine as long as every piece of code touching it knows its concrete type. The moment it’s stored in a variable typed as the interface, or passed into a method whose parameter type is IDisposable rather than the struct itself, the runtime boxes it: a brand-new heap object is created to hold a copy of the struct’s value. Disposing through that interface reference disposes the boxed copy, not the original struct sitting in whatever variable you actually care about, so a using block that looks perfectly correct can leave the real resource – a rented buffer, a pooled handle – never released at all.

🔎 The Problem

public struct PooledBuffer : IDisposable
{
    private byte[] _buffer;
    public PooledBuffer(int size) { _buffer = ArrayPool<byte>.Shared.Rent(size); }

    public void Dispose()
    {
        if (_buffer != null) { ArrayPool<byte>.Shared.Return(_buffer); _buffer = null; }
    }
}

void ReleaseResource(IDisposable resource)
{
    // 'resource' is a BOXED COPY of whatever struct was passed in -
    // disposing it releases that copy's buffer field, not necessarily
    // the caller's original struct's buffer, once boxing has happened.
    resource.Dispose();
}

var buffer = new PooledBuffer(1024);
ReleaseResource(buffer); // 'buffer' got boxed to satisfy IDisposable here
// The original local 'buffer' variable was never disposed by this call.

✅ Fix: Never Let the Struct Cross an Interface Boundary

  • Never pass a disposable struct through a parameter or variable typed as the interface; keep the signature using the concrete struct type (or a generic method constrained to IDisposable), so the compiler calls Dispose directly on the struct value without ever boxing it.
  • If a struct genuinely needs to flow through code that only knows about IDisposable, treat that as a sign it should probably be a class instead – the boxing here isn’t a minor performance detail, it’s a correctness bug, because the boxed copy and the original stop being the same storage the instant the box is created.
  • Audit specifically for pooled-resource structs (ArrayPool-backed buffers and similar), since the entire point of making them structs was usually avoiding an allocation in the first place, and any boxing path quietly reintroduces that exact allocation on top of disposing the wrong copy.

⚠️ Why This Is Easy to Miss

  • The boxing happens at a call site that looks completely ordinary – passing a struct into a method parameter – with no explicit cast, no visible new, nothing in the source that signals an allocation or a copy is being made at that line.
  • using (var buffer = new PooledBuffer(…)) still compiles and still calls Dispose() on something, so the code gives every outward sign of handling cleanup correctly, while the pooled array is quietly never returned until garbage collection eventually also collects the leaked rented array, long after this method has already returned.

A struct avoids the heap exactly until the first interface reference touches it – after that, you’re disposing a copy.

— C# Best Practice

Related posts:

C#: Use Exception Filtering to Catch Specific Exceptions

C#: Use Exception Filtering to Catch Specific Exceptions

C#: Enable Nullable Reference Types to Eliminate Null Reference Exceptions

C#: Enable Nullable Reference Types to Eliminate Null Reference Exceptions

Use IAsyncEnumerable for Streaming Data in .NET

Use IAsyncEnumerable for Streaming Data in .NET

Views: 7

Post navigation

SQL Server: Fix a LEFT JOIN That Silently Behaves Like an INNER JOIN Because a WHERE Clause Filtered the Right-Side Table
Photoshop: Fix a Puppet Warp Mesh That Resets to Flat After You Resize the Canvas Because the Pins Were Never Re-Anchored

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (981)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (858)
  • How to select distinct rows in a datatable in C# (854)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (653)
  • Add Constraint to SQL Table to ensure email contains @ (609)
  • Average of all values in a column that are not zero in SQL (570)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (547)
  • Find numbers with more than two decimal places in SQL (475)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit
  • SQL Server: Fix ROW_NUMBER Ties Reordering Between Identical Runs
  • C#: Fix an Enum HasFlag Returning True for the Zero Value
  • WordPress: Fix Featured Images Vanishing After a CDN Migration
  • Photoshop: Fix Content-Aware Fill Smearing a Repeating Pattern
  • Asp.Net Core: Fix Antiforgery Tokens Rejected Behind a Reverse Proxy

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (981)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (858)
  • How to select distinct rows in a datatable in C# (854)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com