codementor on Nostr: Learn: IDisposable and using Some objects hold things the garbage collector doesn't ...
Learn: IDisposable and using
Some objects hold things the garbage collector doesn't manage well: files, network connections, database connections. They implement IDisposable, and you must call Dispose when done.
using does it for you, even if an exception is thrown:
```csharp
using (var r = new Resource()) Console.WriteLine("working");
Console.WriteLine("after");
class Resource : IDisposable { public void Dispose() => Console.WriteLine("cleaned up"); }
```
It prints working, cleaned up, after.
Shorter form: using var file = File.OpenRead(path); disposes at the end of the method or block.
Read more:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/using#tip · TIP-101
Published at
2026-10-18 12:08:01 UTCEvent JSON
{
"id": "987735a3c671e311e0c58d26cf6fc4e0013ef6b9006feae5c7c8a9b2486d9585",
"pubkey": "e68a0856e90d9997b1f721e905249896412dd570399a987b2e8fd5e7fcfe2279",
"created_at": 1792325281,
"kind": 1,
"tags": [
[
"t",
"tip"
]
],
"content": "Learn: IDisposable and using\n\nSome objects hold things the garbage collector doesn't manage well: files, network connections, database connections. They implement IDisposable, and you must call Dispose when done.\nusing does it for you, even if an exception is thrown:\n\n```csharp\nusing (var r = new Resource()) Console.WriteLine(\"working\");\nConsole.WriteLine(\"after\");\n\nclass Resource : IDisposable { public void Dispose() =\u003e Console.WriteLine(\"cleaned up\"); }\n```\n\nIt prints working, cleaned up, after.\nShorter form: using var file = File.OpenRead(path); disposes at the end of the method or block.\n\nRead more: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/using\n\n#tip · TIP-101",
"sig": "dc03771a1f525a051a97781dd51805e8f4f63492b9bded40bbcb56b00c5464c05de7b3ab4da34bcbb1f978cfbbb7c8ef42a9974e242f2ea5530a138a37f623ec"
}