Skip to content

Instantly share code, notes, and snippets.

@Choonster
Last active October 9, 2015 15:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Choonster/ecf20cd88bc853740ac4 to your computer and use it in GitHub Desktop.
Save Choonster/ecf20cd88bc853740ac4 to your computer and use it in GitHub Desktop.
A quick demo of the using statement re-implemented as a method. Not to be used in real code. https://what.thedailywtf.com/t/because-not-enough-of-the-people-here-think-about-my-fantastic-weenie-lips-yet/51548/77
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
/// <summary>
/// A quick demo of the using statement re-implemented as a method. Not to be used in real code. With fixes suggested by Magus.
///
/// https://what.thedailywtf.com/t/because-not-enough-of-the-people-here-think-about-my-fantastic-weenie-lips-yet/51548/77
/// </summary>
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Using Foo:");
Using(foo => foo.DoStuff(), new Foo());
Console.WriteLine();
Console.WriteLine("Using multiple Foos");
Using(
usingArgs =>
{
Console.WriteLine("Count of usingArgs:");
Console.WriteLine(usingArgs.Count());
},
new Foo(),
new Foo()
);
Console.WriteLine();
Console.WriteLine("Using Foos and Bars");
Using<IDisposable>(
usingArgs => Console.WriteLine("usingArgs: {0}", string.Join(", ", usingArgs)),
new Foo(),
new Bar(),
new Foo(),
new Bar()
);
Console.ReadKey();
}
private static void Using<T>(Action<T> body, T disposable) where T : IDisposable
{
try
{
body.Invoke(disposable);
}
finally
{
if (disposable != null)
{
disposable.Dispose();
}
}
}
private static void Using<T>(Action<IEnumerable<T>> body, params T[] disposables) where T : IDisposable
{
try
{
body.Invoke(disposables);
}
finally
{
foreach (var disposable in disposables)
{
if (disposable != null)
{
disposable.Dispose();
}
}
}
}
}
class Foo : IDisposable
{
public Foo()
{
Console.WriteLine("Constructing Foo!");
}
public void Dispose()
{
Console.WriteLine("Disposing Foo!");
}
public void DoStuff()
{
Console.WriteLine("Doing stuff with Foo!");
}
}
class Bar : IDisposable
{
public Bar()
{
Console.WriteLine("Constructing Bar!");
}
public void Dispose()
{
Console.WriteLine("Disposing Bar!");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment