I have a connection class that is disposable
public class Connection : IDisposable { ... }
and a class that has a dependency on it
public class UsesConnection : IDisposable {
UsesConnection (Connection c) {...}
public void Dispose() {
c.Dispose();
...
}
...
}
How do I create and return a UsesConnection
class without getting a CA2000
error?
The following code gets a CA2000
error on the line c = new Connection();
Connection c = null;
UsesConnection u = null;
try {
c = new Connection()
u = new UsesConnection(c);
return u;
} catch {
if (u != null) u.Dispose();
else if (c != null) c.Dispose();
throw;
}
Use a using
block instead.
using (var c = new Connection())
using (var u = new UsesConnection(c))
{
// Do your work here
}
But don't return
as that will dispose both objects. Don't let UsesConnection
to dispose Connection
.
You should be in charge of maintaining the life-cycles of your disposable references, not some caller - ask yourself "what if they never dispose of my object?"