Skip to content

Instantly share code, notes, and snippets.

@Hafthor
Created January 13, 2013 02:11
Show Gist options
  • Save Hafthor/4521878 to your computer and use it in GitHub Desktop.
Save Hafthor/4521878 to your computer and use it in GitHub Desktop.
Comparing guarded ctor for IDisposables
public RethrowingCatch() {
this.dependency = new Dependency();
try {
this.dependency.SomeProperty = "Blah";
} catch (Exception) {
dependency.Dispose();
throw;
}
}
public ConditionalFinally() {
bool needscleanup = true;
this.dependency = new Dependency();
try {
this.dependency.SomeProperty = "Blah";
needscleanup = false;
} finally {
if(needscleanup) {
dependency.Dispose();
}
}
}
public CleanupListFinally() {
var cleanup = new List<IDisposable>();
this.dependency = new Dependency();
cleanup.Add(this.dependency);
try {
this.dependency.SomeProperty = "Blah";
cleanup.Clear();
} finally {
foreach(var i in cleanup) {
i.Dispose();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment