Return an IDisposable helper object for cleaning up

59 views Asked by At

I'm currently designing a class Device that has two states: Opened and Closed.

In closed state, only basic readonly operations are allowed, like GetName() or GetID(). In opened state, the user can modify the device, e.g. with SetPropertyX(int value).

The Device can be opened with the function Open() and closed with the function Close(), which should be called by the user in any case once he is done with configuration.

I'm thinking of a nice way to use the IDisposable interface in this case. The goal is that the Device is automatically closed when a using block is left.

Basically I see 2 options:

1) Device implements the IDisposable interface

Device class:

class Device : IDisposable
{
    public void Open();
    public void Close();
    public string GetName();
    public void SetPropertyX(int value);
    public void Dispose(); // will call Close() if device is open
}

User app:

using (Device device = new Device())
{
    device.Open();
    device.SetPropertyX(42);
} // implicit device.Close() 

In this case, the device object is of type IDisposable, but the Dispose() function is only effective when the user has called Open() before. I feel like this is not a proper usage of the IDisposable interface, because usually objects of type IDisposable are ready to use right away, without the need for further initalization (in this case calling Open()).

2) Open() returns a helper object of type IDisposable

Helper class:

internal class DisposeHelper : IDisposable
{
    private Device m_dev;
    public DisposeHelper(Device d)
    {
        m_dev = d;
    }
    public void Dispose()
    {
        m_dev.Close();
    }
}

Device class:

class Device
{
    public IDisposable Open();
    public void Close();
    public string GetName();
    public void SetPropertyX(int value);
}

User app:

Device device = new Device();
using (device.Open()) // no need to store the returned object in a variable
{
    device.SetPropertyX(42);
} // implicit Close() by helper

In this case, the IDisposable object is only used for making sure that Close() is called at the end of the using scope and thus we don't need to store the object in a variable. But again, I have a feeling that this isn't a proper usage of the IDisposable interface either.

Any ideas how I can achive my goal (use using to make sure that the device is closed)?

0

There are 0 answers