Skip to content

Instantly share code, notes, and snippets.

@Sangrail
Created June 3, 2016 18:09
Show Gist options
  • Save Sangrail/b1c5280ece9b7f43054892e6f4a7d67d to your computer and use it in GitHub Desktop.
Save Sangrail/b1c5280ece9b7f43054892e6f4a7d67d to your computer and use it in GitHub Desktop.
Smart Disposal pattern
public static class Disposable
{
///Create a higher order function (HOF) - accept a Functor as a parameter
public static TResult Using<TDisposable, TResult>(
Func<TDisposable> factory,
Func<TDisposable, TResult> map)
where TDisposable : IDisposable
{
using (var disposable = factory())
{
return map(disposable);
}
}
}
//Usage 1
var firstLine =
Disposable.Using(
() => new StreamReader(file),
reader => reader.ReadLine()).Dump("Clean using");
//Usage 2
var time =
Disposable
.Using(
() => new System.Net.WebClient(),
client => XDocument.Parse(client.DownloadString("http://time.gov/actualtime.cgi")))
.Root
.Attribute("time")
.Value;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment