Created
November 13, 2018 10:05
-
-
Save borland/0cf2ab0c0ddcb94a5c7f298bba34563c 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 SingletonList<T> : IEnumerable<T>, IEnumerator<T> | |
{ | |
[ThreadStatic] | |
static readonly SingletonList<T> TransientInstance = new SingletonList<T>(); | |
public static SingletonList<T> Create(T value) => new SingletonList<T> { Value = value }; | |
public static SingletonList<T> Transient(T value) | |
{ | |
TransientInstance.Value = value; | |
return TransientInstance; // dirty hacks to avoid allocating lists every time | |
} | |
T Value { get; set; } | |
public IEnumerator<T> GetEnumerator() { | |
Reset(); | |
return this; // it's it's own enumerator! | |
} | |
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); | |
public T Current => Value; | |
object IEnumerator.Current => Current; | |
public void Dispose() { } | |
private bool m_moveNextResult = true; | |
public bool MoveNext() | |
{ | |
var result = m_moveNextResult; | |
m_moveNextResult = false; // the next time someone calls us we will return false; | |
return result; | |
} | |
public void Reset() => m_moveNextResult = true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment