Search code examples
c#yield-return

RCS1227 - What validation is performed by an iterator function?


I was reading about code analyser RCS1227 and it says this:

An iterator method (a method that contains yield) will not validate arguments until the caller begins to enumerate the result items. To ensure that arguments are validated immediately (when the method is called), move the iterator to a separate method (local function).

I don't understand what validation this refers to. It sounds to me like it refers to type checking, but the below code sample correctly gives a build error, despite not using a separate function for the iterator.

public IEnumerable<int> GetIntegers()
{
  var strings = new List<string> { "1", "2", "3" };
  foreach(var s in strings)
  {
    yield return s; // <-- CS0029 Cannot implicitly convert type 'string' to 'int'
  }
}

What validation does the quoted explanation refer to?


Solution

  • The link in the question contains two code samples, one of which is copied below:

    IEnumerable<object> Foo(IEnumerable<object> items)
    {
        if (items == null)
            throw new ArgumentNullException(nameof(items));
    
        foreach (object item in items)
            yield return item;
    }
    

    The validation being referred to is the validation within this method (checking if items is null), not C# type checking. Strictly speaking, the difference that an iterator function makes isn't specific to validation - it applies equally to any code in the the Foo method before the yield return.