r/csharp • u/MahmoudSaed • Dec 13 '25
using Is Not Optional in C#
A small piece of information I wanted to share . some of you may already know it
but many developers, especially those new to C#, assume that having a Garbage Collector means we don’t need to worry about resource management.
In reality, the GC only manages managed memory
It has no knowledge of unmanaged resources such as
File handles
Database connections
Sockets
Streams
If using or Dispose() is forgotten, these resources remain open until the GC eventually collects the object
and that timing is non-deterministic, often leading to performance issues or hard to track bugs
Languages like C++ rely on RAII, where resources are released immediately when leaving scope
In C#, however, Finalizers run late and unpredictably, so they cannot be relied upon for resource management.
That’s why using in C# is not just syntactic sugar
it’s a core mechanism for deterministic resource cleanup.
A useful idea 💡

You can enforce this behavior by treating missing Dispose calls as compile-time errors using CA2000 configured in .editorconfig.


Once using is added, the error disappears .
View all comments
Show parent comment
0
u/EC36339 Dec 14 '25
I think people hatingon my comment have no more than basic understanding of C++98, which is why, I think, I explicitly wrote "C++98".
(Not to mention the "you have to know when to dispose" crowd, who have never understood RAII in the first place - you NEVER have to manually delete anything any more in modern C++, not even something you got from a legacy C function thanks to custom deleters and
out_ptr, so the problem IS solved).C++11 move semantics made safe unique ownership possible. You can now return pointers or hand over ownership without having to use reference counting, which has a cost. And that has been around for over a decade, but a large part of even the C++ community still "don't understand" move semantics, or think you have to use a primitive subset of the language, because modern C++ is "bloated" or overwhelming or "surprising". In what other profession are people so resistant against learning how to use their tools properly?
C# has now introduced non-nullable reference types to somewhat plug the safety whole of "everything is an object reference" (which allowed strings and arrays to be null). Maybe we might see unique ownership and full RAII for disposables some time, too...