Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
56 lines (38 sloc) 1.2 KB

RCS1227: Validate arguments correctly

Property Value
Id RCS1227
Category Design
Severity Info

Summary

  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).

Example

Code with Diagnostic

IEnumerable<object> Foo(IEnumerable<object> items)
{
    if (items == null)
        throw new ArgumentNullException(nameof(items));

    foreach (object item in items) // RCS1227
        yield return item;
}

Code with Fix

IEnumerable<object> Foo(IEnumerable<object> items)
{
    if (items == null)
        throw new ArgumentNullException(nameof(items));

    return FooIterator();

    IEnumerable<object> FooIterator()
    {
        foreach (object item in items)
            yield return item;    
    }
}

See Also

(Generated with DotMarkdown)

You can’t perform that action at this time.