Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# error - "Not all code paths return a value"

Tags:

c#

This is fairly simple method. I use entity framework to get some data and then check some values in a if statement. However right now the method is marked with red.

This is my method:

private bool IsSoleInProduction(long? shoeLastID)
{
    if (shoeLastID == null)
    {
        MessageBox.Show(Resources.ERROR_SAVE, 
                        "Error", 
                        MessageBoxButtons.OK, 
                        MessageBoxIcon.Error);
        return false;
    }

    ISoleService soleService = 
        UnityDependencyResolver.Instance.GetService<ISoleService>();

    List<Sole> entity = 
        soleService.All().Where(s => s.ShoeLastID == shoeLastID).ToList();

    if (entity.Count() != 0)
    {
        foreach (var items in entity)
        {
            if (items.Status == 20)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
    else
    {
        return false;
    }    
}

What am I missing?

like image 436
Leron_says_get_back_Monica Avatar asked Jan 17 '26 07:01

Leron_says_get_back_Monica


1 Answers

You need to take advantage of LINQ with Any, replace your code:

if (entity.Count() != 0)
{
    foreach (var items in entity)
    {
        if (items.Status == 20)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}
else
{
    return false;
}    

with simpler code:

 return entity.Any(item => item.Status == 20);

Or even better performance:

 return soleService.All()
              .Any(s => s.ShoeLastID == shoeLastID
                     && s.Status == 20); 

Edit: With you comment, below code is what you need:

  List<Sole> entity =  soleService.All()
                            .FirstOrDefault(s => s.ShoeLastID == shoeLastID);

  return entity == null ? false : entity.Status == 20;
like image 68
cuongle Avatar answered Jan 19 '26 21:01

cuongle