Home > Software design >  Prettier foreach - Range extensions cannot operate on enumerators or in async
Prettier foreach - Range extensions cannot operate on enumerators or in async

Time:11-16

I tried to replace foreach (var i in Enumerable.Range(0, _gridCount)) with foreach (var i in 0.._gridCount) because it looks prettier and it has good performance as well.

When I attempted to do so, the foreach showed the following error:

'foreach' statement cannot operate on enumerators of type 'RangeEnumerator' in 'async' or iterator methods because 'RangeEnumerator' is a 'ref' struct

How do I fix it?

public IEnumerable<double> GridLevels()
{
    var step = (_upperLimit - _lowerLimit) / _gridCount;

    foreach (var i in Enumerable.Range(0, _gridCount))
    {
        var price = _lowerLimit   step * i;
        yield return price;
    }
}
public static class RangeExtensions
{
    public static RangeEnumerator GetEnumerator(this Range range) => new(range);

    public ref struct RangeEnumerator
    {
        private readonly int _start;
        private readonly int _length;
        private int _count;
        public RangeEnumerator(Range range)
        {
            var (offset, length) = range.GetOffsetAndLength(int.MaxValue);
            (Current, _start, _length, _count) = (offset - 1, offset - 1, length, 0);
        }

        public bool MoveNext()
        {
            (var result, _count, Current) = (_count < _length, _count   1, Current   1);
            return result;
        }

        public void Reset() => (Current, _count) = (_start, 0);

        public int Current { get; private set; }

        public void Dispose() { }
    }
}

CodePudding user response:

The error says "because 'RangeEnumerator' is a 'ref' struct", so removing the ref keyword should fix it.

public struct RangeEnumerator
{
}
  • Related