Skip to content

Instantly share code, notes, and snippets.

@borland
Created November 13, 2018 10:05
Show Gist options
  • Save borland/0cf2ab0c0ddcb94a5c7f298bba34563c to your computer and use it in GitHub Desktop.
Save borland/0cf2ab0c0ddcb94a5c7f298bba34563c to your computer and use it in GitHub Desktop.
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