yield return default;
yield return
roughly means "give back a value and continue once the next value is requested".
So, the loop is executed even if the yield return
is never reached.
For fixing this, you have multiple options.
yield break
Instead of the yield return
in the if
, you can use yield break
in order to terminate the method as explained here.
public static IEnumerable<KeyValuePair<MyDto,long>> PrepareClientResponses(this IEnumerable<MyServiceCnt> myEntities)
{
if (myEntities == null || !myEntities.Any())
{
yield return default;
yield break;
}
foreach (var e in myEntities)
{
var client = e.PrepareClientResponse();
yield return new KeyValuePair<MyDto, long>(client, e.MyId.Value);
}
}
else
You can just put the loop in an else
-block. This way, it won't be executed in case the check evaluates to true:
public static IEnumerable<KeyValuePair<MyDto,long>> PrepareClientResponses(this IEnumerable<MyServiceCnt> myEntities)
{
if (myEntities == null || !myEntities.Any())
{
yield return default;
}
else
{
foreach (var e in myEntities)
{
var client = e.PrepareClientResponse();
yield return new KeyValuePair<MyDto, long>(client, e.MyId.Value);
}
}
}
do nothing
In some cases, it might be a sensible decision to not return any element in case a preconception fails. But note that your code will behave differently if you arr doing that.
public static IEnumerable<KeyValuePair<MyDto,long>> PrepareClientResponses(this IEnumerable<MyServiceCnt> myEntities)
{
if (myEntities != null && myEntities.Any())
{
foreach (var e in myEntities)
{
var client = e.PrepareClientResponse();
yield return new KeyValuePair<MyDto, long>(client, e.MyId.Value);
}
}
}
other problem
Please see this other answer by @Marco for another problem with your code (which I also integrated in this answer).