Created
October 30, 2014 08:33
-
-
Save jamescrowley/802cbec1594b6b31b3af to your computer and use it in GitHub Desktop.
Passes in C# fails in Mono - looks like different behaviour in Linq rather than Iterator blocks
This file contains 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 IEnumerable<T> HandleExceptions<T>(this IEnumerable<T> values, Func<Exception, T> onException) | |
{ | |
using (var enumerator = values.GetEnumerator()) | |
{ | |
bool next = true; | |
Exception lastException = null; | |
while (next) | |
{ | |
try | |
{ | |
next = enumerator.MoveNext(); | |
} | |
catch (Exception ex) | |
{ | |
lastException = ex; | |
} | |
if (lastException != null) | |
{ | |
yield return onException(lastException); | |
lastException = null; | |
} | |
else if (next) | |
{ | |
yield return enumerator.Current; | |
} | |
} | |
} | |
} |
This file contains 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
[Test] | |
public void HandleExceptions() | |
{ | |
IList<Exception> exceptions = new List<Exception>(); | |
Func<Exception, int?> callback = (ex) => { exceptions.Add(ex); return (int?)0; }; | |
var result = Enumerable.Range(0, 5).Select(x => { | |
if (x%2 == 0) | |
throw new Exception("Exception" + x); | |
return (int?)x; | |
}).HandleExceptions(callback).ToList(); | |
Assert.AreEqual(5,result.Count); | |
Assert.AreEqual(3,exceptions.Count); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment