C
C#2mo ago
Vortac

Using IDisposable in private field

I have an an IDisposable object that I would like to turn into a private field:
using var audioEngine = new MiniAudioEngine(44100, Capability.Playback);
using var audioEngine = new MiniAudioEngine(44100, Capability.Playback);
eg:
class SoundEngine {
private MiniAudioEngine _soundEngine;

public SoundEngine() {
_soundEngine = new MiniAudioEngine(44100, Capability.Playback);
}
class SoundEngine {
private MiniAudioEngine _soundEngine;

public SoundEngine() {
_soundEngine = new MiniAudioEngine(44100, Capability.Playback);
}
How can I ensure that the private field uses the using statement?
6 Replies
sibber
sibber2mo ago
you dont, you implement IDisposable thats what its for
Jimmacle
Jimmacle2mo ago
yeah, a using statement only makes sense within executable code where it's known when the object is no longer used objects containing disposable objects should also implement IDisposable to dispose their members, then you can use using with your object
Vortac
VortacOP2mo ago
It's because I'm developing a music player, and I control it via a TUI interface. I pass an instance of the SoundEngine class to the TUI class and then want to control the player from there. I have it working using a Windows-only sound library, but when I try to use a newer cross-platform library I don't get any playback
Mayor McCheese
Mayor McCheese2mo ago
That doesn't sound related to IDisposable. Can you make a simpler implementation that works as a proof of concept?
FusedQyou
FusedQyou2mo ago
Whatever the case, you can just store it in a variable and you don't use a using statement in any way You should make the containing class implement IDisposable itself so you can use a using statement on that instead, or dispose if needed. Then, in the dispose method dispose your field correctly.

Did you find this page helpful?