← Foundations path
.NETFoundations 15 / 37

Dispose and garbage collection

“What is the difference between Dispose and garbage collection?”

The garbage collector frees memory later. Dispose gives back connections and files now.

See it

requestsConnection poolMax Pool Size 100 (3 shown)Before the fixinside your appconn 1 · in useconn 2 · free⋮conn 100 · freerequest 1request 2⋮request 100request 101waits… 15 s timeoutGC · runs later
1 / 9Before the fix. Request 1 runs . borrows conn 1 from the pool.

In plain words

The garbage collector (GC) cleans up memory, but only when it decides to; you can't predict when. Some objects hold something scarcer than memory: a database connection, an open file. SqlClient keeps a pool: a few open connections it lends out and takes back. hands yours back now. using calls for you at the end of the block, even if an error is thrown. Forget it, and under load the app runs out of connections while memory looks fine.

Say it in the interview

In the lending API

The same repository before and after the fix. It is slice 3 code (the database), shown early because this is the classic leak. Press Next line to walk through it.

Lending.sln · where these 2 files sit
  • src/Infrastructure/Servicing/
Diagram · step 1Before the fix. Request 1 runs . borrows conn 1 from the pool.
requestsConnection poolMax Pool Size 100 (3 shown)Before the fixinside your appconn 1 · in useconn 2 · free⋮conn 100 · freerequest 1request 2⋮request 100request 101waits… 15 s timeoutGC · runs later
LoanRepository.old.cs · line 5 · 1 of 8A primary constructor: the connection string comes in once, when the builds the repository. In slice 3 this class uses instead; raw ADO.NET like this is where teams forget to dispose.

What they ask next

Interviewers check that you can explain every line. Tap a question to open it.

Traps

With AI tools

The interview rubric of Karat, an interview-outsourcing company, flags accepting AI output without checking it. A missing using is easy to miss in generated code, because it works fine on your machine with one user. Read every generated of a connection, stream or file and ask: who disposes this? A worked answer from this app's research: an AI suggested making a singleton to fix an ; the real fix was a correct .

Read more: Microsoft Learn: using IDisposable objects · Microsoft Learn: implement a Dispose method · Microsoft Learn: fundamentals of garbage collection · SQL Server connection pooling (ADO.NET) · Event counters in SqlClient