<PackageReference Include="NUnit" Version="4.3.2" />

ImmutableStack<T>

A minimalistic implementation of an immutable stack. Add members as needed.
using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; namespace NUnit.Framework.Internal { [System.Runtime.CompilerServices.NullableContext(1)] [System.Runtime.CompilerServices.Nullable(0)] internal struct ImmutableStack<[System.Runtime.CompilerServices.Nullable(2)] T> : IEnumerable<T>, IEnumerable { [System.Runtime.CompilerServices.Nullable(0)] private sealed class Node { public T Value { get; } [System.Runtime.CompilerServices.Nullable(new byte[] { 1, 0 })] [field: System.Runtime.CompilerServices.Nullable(new byte[] { 1, 0 })] public Node Next { [return: System.Runtime.CompilerServices.Nullable(new byte[] { 1, 0 })] get; } public Node(T value, [System.Runtime.CompilerServices.Nullable(new byte[] { 1, 0 })] Node next) { Value = value; Next = next; } } [System.Runtime.CompilerServices.Nullable(new byte[] { 1, 0 })] private readonly Node _head; [System.Runtime.CompilerServices.Nullable(new byte[] { 0, 1 })] public static ImmutableStack<T> Empty { [return: System.Runtime.CompilerServices.Nullable(new byte[] { 0, 1 })] get { return default(ImmutableStack<T>); } } private ImmutableStack([System.Runtime.CompilerServices.Nullable(new byte[] { 1, 0 })] Node head) { _head = head; } [return: System.Runtime.CompilerServices.Nullable(new byte[] { 0, 1 })] public ImmutableStack<T> Push(T value) { return new ImmutableStack<T>(new Node(value, _head)); } public IEnumerator<T> GetEnumerator() { for (Node current = this._head; current != null; current = current.Next) { yield return current.Value; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }