Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sonar issues with null check C#

After enabling Sonar in my project I get the following message

myEntities is null on at least one execution path.

public static IEnumerable<KeyValuePair<MyDto,long>> PrepareClientResponses(this IEnumerable<MyServiceCnt> myEntities)
{
    if (myEntities == null || !myEntities.Any())
    {
        yield return default;
    }         
    foreach (var myEntities in myEntities)
    {
        var client = myEntities.PrepareClientResponse();
        yield return new KeyValuePair<MyDto, long>(client, myEntities.MyId.Value);
    }
}

The message is on the "myEntities" on the foreach (var myEntities in myEntities) line.

Can someone suggest me on how to solve this message. I am checking null condition but it still gives this warning.

like image 977
coder11 b Avatar asked Jun 09 '26 14:06

coder11 b


1 Answers

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

like image 67
dan1st Avatar answered Jun 11 '26 04:06

dan1st