Created
September 9, 2010 03:06
-
-
Save just3ws/571288 to your computer and use it in GitHub Desktop.
A really crappy implementation of a before/after actions using the Using() keyword in C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//This work licensed under the WTFPL License | |
//WTFPL: http://sam.zoy.org/wtfpl/. | |
using System; | |
namespace EntryExitThing | |
{ | |
internal class Program | |
{ | |
/// <summary> | |
/// Entrypoint for the application. | |
/// </summary> | |
private static void Main() | |
{ | |
//This pattern can be used in .NET 2.0 using this syntax. | |
//using (SimpleEntryExitThing be = new SimpleEntryExitThing(delegate { Console.Out.WriteLine("Entry"); }, | |
// delegate { Console.Out.WriteLine("Exit"); })) | |
using (new SimpleEntryExitThing(() => Console.Out.WriteLine("enter"), | |
() => Console.Out.WriteLine("exit"))) | |
{ | |
for (int i = 0; i < 10; i++) | |
{ | |
Console.Out.WriteLine("doing stuff"); | |
} | |
} | |
Console.In.ReadLine(); | |
} | |
} | |
public delegate void OnEntryDelegate(); | |
public delegate void OnExitDelegate(); | |
internal interface IEntryExitThing : IDisposable | |
{ | |
/// <summary> | |
/// Occurs when the instance is initialized. | |
/// | |
event OnEntryDelegate OnEntry; | |
/// <summary> | |
/// Occurs when the instance is disposed. | |
/// </summary> | |
event OnExitDelegate OnExit; | |
} | |
/// <summary> | |
/// Thing class who's sole purpose in this life | |
/// is to invoke a delegate upon construction | |
/// and a corresponding delegate upon disposal. | |
/// </summary> | |
internal class SimpleEntryExitThing : IEntryExitThing | |
{ | |
/// <summary> | |
/// Initializes a new instance of the <see cref="SimpleEntryExitThing"/> class. | |
/// </summary> | |
/// <param name="onEntry">The delegate method to be executed upon initialization..</param> | |
/// <param name="onExit">The delegate method to be executed upon exit..</param> | |
public SimpleEntryExitThing(OnEntryDelegate onEntry, | |
OnExitDelegate onExit) | |
{ | |
OnEntry = onEntry; | |
OnExit = onExit; | |
if (OnEntry != null) | |
{ | |
OnEntry(); | |
} | |
} | |
/// <summary> | |
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. | |
/// </summary> | |
public void Dispose() | |
{ | |
if (OnExit != null) | |
{ | |
OnExit(); | |
} | |
} | |
public event OnEntryDelegate OnEntry; | |
public event OnExitDelegate OnExit; | |
} | |
} | |
//NOTE: I wrote this, like 3 or 4 years ago but updated to lambda syntax for the demo. YMMV. whatever. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment