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 acc
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:
protected void ValidateExportDirectoryExists()
{
using (GetNetworkAccess(username, password, domain))
{
CheckExportDirectoryExists();
}
}
protected IDisposable GetNetworkAccess(string username, string password, string domain)
{
return useNetworkAccess ? new Core.NetworkAccess(username, password, domain) : new NullNetworkAccess(username, password, domain);
}
internal class NullNetworkAccess : IDisposable
{
internal NullNetworkAccess(string username, string password, string domain)
{
}
public void Dispose()
{
}
}
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!