using System; using System.IO; using Rhino.Mocks; namespace PlayingWithDisposableActions.Test { public class LetsPlay { public void DemoWithUsingBlock() { using (MemoryStream stream = new MemoryStream()) { // do something with the stream } } public void DemoOfUsingBlockExpanded() { MemoryStream stream = null; try { stream = new MemoryStream(); // do something with the stream } finally { if (stream != null) stream.Dispose(); } } public void DemoAction() { Do(Console.Out.WriteLine); Do(MyMethodThatMatchesTheActionDelegateSignature); } public void Do(Action action) { } private void MyMethodThatMatchesTheActionDelegateSignature(Type type) { } private void DemoDisposableAction() { string myMessage = "Hello World"; using (new DisposableAction(Console.Out.WriteLine, myMessage)) { // do something } using (new DisposableConsoleLogger("Finished running...")) { // do something } } private void WhatIsRhinoDoingUnderTheHood() { MockRepository mockery = new MockRepository(); using (mockery.Record()) { // ReplayAll() } using (mockery.Playback()) { // VerifyAll() } } } public class DisposableAction : IDisposableAction { public DisposableAction(Action _action, T _itemToActOn) { this._action = _action; this._itemToActOn = _itemToActOn; } public void Dispose() { _action(_itemToActOn); } private Action _action; private T _itemToActOn; } public class DisposableConsoleLogger : DisposableAction { public DisposableConsoleLogger(string completionMessage) : base(Console.Out.WriteLine, completionMessage) { } public DisposableConsoleLogger() : base(Console.Out.WriteLine, "completed action") { } } public interface IDisposableAction : IDisposable { } }