Created
June 3, 2016 18:09
-
-
Save Sangrail/b1c5280ece9b7f43054892e6f4a7d67d to your computer and use it in GitHub Desktop.
Smart Disposal pattern
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
| 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