Join Nostr
2026-10-18 12:08:01 UTC

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