RCS1227: Validate arguments correctly
Properties
Property | Value |
---|---|
Default Severity | Info |
Minimum language version | - |
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).
Examples
Example #1
diagnostic.cs
IEnumerable<object> Foo(IEnumerable<object> items)
{
if (items == null)
throw new ArgumentNullException(nameof(items));
foreach (object item in items)
yield return item;
}
fix.cs
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;
}
}