using System.Collections.Generic;
using System.Collections;
public static void Test()
var list1 = new int[] { };
var list2 = new int[] { 1, 2, 3 };
TestNoDoubleEvaluate(list2);
Console.WriteLine("Done");
private static void TestNoDoubleEvaluate(int[] list)
Action<IEnumerable<int>> action = (e) =>
catch (InvalidOperationException ex)
Console.WriteLine("Caught expected exception {0}", ex.Message);
private static void Test(int[] list)
Action<IEnumerable<int>> action = (e) =>
Console.WriteLine("Called, count = {0}", count);
var oldCallCount = callCount;
var oldTotalCount = totalCount;
Assert.IsTrue(callCount == (list.Length == 0 ? oldCallCount : oldCallCount + 1));
Assert.IsTrue(totalCount == oldTotalCount + list.Length);
if (oldCallCount == callCount)
Console.WriteLine("Not called, length = {0}", list.Length);
public static partial class EnumerableExtensions
public static bool IfNonEmpty<T>(this IEnumerable<T> source, Action<IEnumerable<T>> func)
if (source == null|| func == null)
throw new ArgumentNullException();
using (var enumerator = source.GetEnumerator())
if (!enumerator.MoveNext())
func(new UsedEnumerator<T>(enumerator));
class UsedEnumerator<T> : IEnumerable<T>
IEnumerator<T> usedEnumerator;
public UsedEnumerator(IEnumerator<T> usedEnumerator)
if (usedEnumerator == null)
throw new ArgumentNullException();
this.usedEnumerator = usedEnumerator;
public IEnumerator<T> GetEnumerator()
var localEnumerator = System.Threading.Interlocked.Exchange(ref usedEnumerator, null);
if (localEnumerator == null)
throw new InvalidOperationException();
yield return localEnumerator.Current;
while (localEnumerator.MoveNext())
yield return localEnumerator.Current;
IEnumerator IEnumerable.GetEnumerator()
public static void Main()
Console.WriteLine("Roslyn 2.0 Compiler; Environment version: " + Environment.Version);
Console.WriteLine("Uncaught exception: ");