2 ms·
Not really. There's the IDisposable interface you can implement, and some language features around making it easy to use[2], however there's nothing preventing
by magicalhippo 3y ago
Not really. There's the IDisposable interface you can implement, and some language features around making it easy to use[2], however there's nothing preventing you from not using those language features and forgetting to call Dispose.
In case you forget the GC will call Dispose but it's entirely up to the GC when that happens, so personally I wouldn't say it's similar.
[1]: https://learn.microsoft.com/en-us/dotnet/fundamentals/runtime-libraries/system-idisposable https://learn.microsoft.com/en-us/dotnet/fundamentals/runtim...
[2]: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/using https://learn.microsoft.com/en-us/dotnet/csharp/language-ref...
- SigmundA 3y ago>In case you forget the GC will call Dispose but it's entirely up to the GC when that happens, so personally I wouldn't say it's similar. This actually has to be implement in the classes finalizer its not done automatically. The finalizer is called by the GC which if the designer chooses can call Dispose. This is usually done in well designed classes that use unmanaged resources. Dispose and using give you the determinism if you want it and the finalizer gives you the backstop to prevent leaks if it makes sense.
- magicalhippo 3y agoGood point, I forgot about that little, but crucial, detail. So it's flexible, but there are footguns about, especially if you're wrapping a handle to something external.
- cerved 3y agoDoesn't the compiler complain if you don't use using or try? I forget