Rule Definition
Yield methods are rewritten by the compiler (to be lazily evaluated), code that causes wrong input might be in completely different place.
Remediation
Split the method in two if it contains both ArgumentNullException and yield
Violation Code Sample
public static IEnumerable<TFoo> TakeWhile<TFoo>(this IEnumerable<TFoo> foo)
{
if (foo == null) { throw new ArgumentNullException(nameof(foo)); }
foreach (var bar in foo)
{
if (!doSomething(bar)) { break; }
yield return bar; // VIOLATION
}
}
Fixed Code Sample
public static IEnumerable<TFoo> TakeWhile<TFoo>(this IEnumerable<TFoo> foo)
{
if (foo == null) { throw new ArgumentNullException(nameof(foo)); }
return checkThisFoo<TFoo>(foo);
}
private static IEnumerable<TFoo> checkThisFoo<TFoo>(IEnumerable<TFoo> foo)
{
foreach (var bar in foo)
{
if (!doSomething(bar)) { break; }
yield return bar; // NO VIOLATION
}
}
Reference
https://docs.microsoft.com/dotnet/csharp/language-reference/keywords/yield
Related Technologies
Technical Criterion
Programming Practices - Error and Exception Handling
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.