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.

Revisions

  1. Sangrail created this gist Jun 3, 2016.
    30 changes: 30 additions & 0 deletions Disposal.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@
    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;