Search code examples
c#ienumerableenumeration

Is it safe to use IEnumerable for something that may be enumerated multiple times?


For example let's say I have the following:

public class StringTester
{
    IEnumerable<IStringConditional> Conditionals { get; }

    public StringTester(IEnumerable<IStringConditional> conditionals)
    {
        conditionals = Conditionals;
    }

    public bool TestString(string testString)
    {
        foreach (var conditional in Conditionals)
        {
            if (!conditional.Test(testString))
            {
                return false;
            }
        }

        return true;
    }
}

Is this regarded as safe, or are IEnumerable types only safe for a single enumeration? If not what type would be best to use in a case like this?


Solution

  • It is undefined as to whether IEnumerable<T> is repeatable in the general case. Often (usually): it is. However, examples exist that either:

    • can only ever be iterated once (think "data from a socket")
    • can be iterated many times, but give completely different data each time (without any corresponding obvious state mutation)

    So: in general I wouldn't advise ever iterating it more than once unless you know the scenario is a repeatable one. Things like arrays and lists are repeatable (if the data changes, of course, they may change to show those changes).