C
C#10mo ago
goated

I'm confused what IDisposable is used for

So I was expecting once the code run out of the using {} the class would be destroyed (and if we try to access it will throw a null ref exception)therefore helping the system, but it turns out if I keep a reference to it it wouldn't be destroyed, which means it's going to check is there any reference to the object anyways, it's not going to optimize the code right? Using a normal class and disposable feels the same
4 Replies
TheBoxyBear
TheBoxyBear10mo ago
IDiposable: "Provides a mechanism for releasing unmanaged resources." Most resources you allocate are tracked and handled by the garbage collector but sometimes an object will make use of external (unmanaged) resources that also need freeing. For instance an active network connection or file handle It's not uncommon for disposable classes to dispose of themselves in their finalizer but you should still dispose manually when you're done with it rather than wait for the garbage collector to kick in as tends to keep objects around a bit longer and batch collections
Thinker
Thinker10mo ago
You can actually get the behavior you're describing btw, if you use the using keyword when declaring the variable it'll automatically be disposed when it leaves the current scope.
{
using var x = new DisposableThing();
Console.WriteLine(x);
} // x is disposed here
{
using var x = new DisposableThing();
Console.WriteLine(x);
} // x is disposed here
TheBoxyBear
TheBoxyBear10mo ago
^ Actually tied to the scope or implicitely disposes whenever it's not referenced for hte rest of the scope? If the former, then there could tehroically be advantes to the old syntax creeating a scope for the disposable
Thinker
Thinker10mo ago
Scope And yeah the old using block syntax still has its uses
Want results from more Discord servers?
Add your server