I have the follow code but it is awkward. How could I better structure it? Do I have to make my consuming class implement IDisposable and conditionally construct the network access class and dispose it when I am done?
protected void ValidateExportDirectoryExists()
{
if (useNetworkAccess)
{
using (new Core.NetworkAccess(username, password, domain))
{
CheckExportDirectoryExists();
}
}
else
{
CheckExportDirectoryExists();
}
}
If you repeat this pattern in many methods you can break out the pattern
using scope will only dispose a object if the class implements IDisposible interface so yes you need to implement dispose method.
I don't know if it is "better", but you could use the null object pattern and have a "null" disposable network access object. Something like this:
This is probably too cute for its own good.
[EDIT] Just saw in Jon's answer that null can be used in a using statement. I had no idea!
Whatever is enclosed within the using statement will have it's
IDispoable.Dispose
called as dictated by theIDisposable
interface. As seen on MSDN forusing
...Therefore if you put a custom type within the
using
statement it should clean up its resources appropriately via theIDisposable
interface.The using statement is a shortcut to avoid "finally" blocks and should only be used when it makes the code easier to follow. In your case I would write the following code. It may not be as brief as some of the other versions, but is much more straight forward.