Last active
December 28, 2015 01:19
-
-
Save martijnhoekstra/7420104 to your computer and use it in GitHub Desktop.
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
class FallbackEnumerable<T> : IEnumerable<T> { | |
private IEnumerable<T> src; | |
private Func<T> fallback; | |
public FallbackEnumerable(IEnumerable<T> src) : this(src, () => default(T)) { } | |
public FallbackEnumerable(IEnumerable<T> src, T fallback) : this(src, () => fallback ) { } | |
public FallbackEnumerable(IEnumerable<T> src, Func<T> fallback) { | |
this.src = src; | |
this.fallback = fallback; | |
} | |
public IEnumerator<T> GetEnumerator() { | |
return new FallbackEnumerator(this); | |
} | |
private class FallbackEnumerator : IEnumerator<T> { | |
private bool disposed = false; | |
private bool hasCurrent = true; | |
private IEnumerator<T> srcenumer; | |
private Func<T> fallback; | |
public FallbackEnumerator(FallbackEnumerable<T> outer){ | |
this.srcenumer = outer.GetEnumerator(); | |
this.fallback = outer.fallback; | |
} | |
public bool MoveNext() { | |
hasCurrent = hasCurrent && srcenumer.MoveNext(); | |
return true; | |
} | |
public T Current { | |
get { | |
return hasCurrent ? srcenumer.Current : fallback(); | |
} | |
} | |
public void Reset () { | |
srcenumer.Reset(); | |
hasCurrent = true; | |
} | |
public void Dispose() { | |
Dispose(true); | |
GC.SuppressFinalize(this); | |
} | |
protected virtual void Dispose(bool disposing){ | |
if (!disposed) { | |
if (disposing) { | |
if (srcenumer != null){ | |
srcenumer.Dispose(); | |
} | |
} | |
srcenumer = null; | |
disposed = true; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment