© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
13 replies
DaVinki

❔ ✅ Using a foreach loop on a custom enumerator

I created my own enumerator using the IEnumerator<T> interface but refactored it into a ref struct which can't implement interfaces. How can I use foreach with it? I noticed that Span<T>.Enumerator does this but probably because it's a part of .NET

using System.Numerics;

namespace common_vector_ops;

public ref struct VectorIterator<T> where T : struct
{
    public int Index { get; private set; }
    public int Increment { get; }
    public Span<T> VectorizedSpan { get; }

    public VectorIterator() : this(Span<T>.Empty)
    {
    }

    public VectorIterator(T[] array)
    {
        VectorizedSpan = array.AsSpan();
        Increment = Vector<T>.Count;
        Index = -Increment;
    }

    public VectorIterator(Span<T> span)
    {
        VectorizedSpan = span;
        Increment = Vector<T>.Count;
        Index = -Increment;
    }

    public bool MoveNext()
    {
        Index += Increment;
        return Index <= VectorizedSpan.Length - Increment;
    }

    public void Reset()
    {
        Index = -Increment;
    }

    public Vector<T> Current => new Vector<T>(VectorizedSpan[Index..]);
}
using System.Numerics;

namespace common_vector_ops;

public ref struct VectorIterator<T> where T : struct
{
    public int Index { get; private set; }
    public int Increment { get; }
    public Span<T> VectorizedSpan { get; }

    public VectorIterator() : this(Span<T>.Empty)
    {
    }

    public VectorIterator(T[] array)
    {
        VectorizedSpan = array.AsSpan();
        Increment = Vector<T>.Count;
        Index = -Increment;
    }

    public VectorIterator(Span<T> span)
    {
        VectorizedSpan = span;
        Increment = Vector<T>.Count;
        Index = -Increment;
    }

    public bool MoveNext()
    {
        Index += Increment;
        return Index <= VectorizedSpan.Length - Increment;
    }

    public void Reset()
    {
        Index = -Increment;
    }

    public Vector<T> Current => new Vector<T>(VectorizedSpan[Index..]);
}
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

❔ Foreach loop
C#CC# / help
4y ago
foreach loop index error
C#CC# / help
2y ago
❔ problems with foreach loop
C#CC# / help
3y ago