Home > Software engineering >  Returning a bool value inside Try-Catch block in C#
Returning a bool value inside Try-Catch block in C#

Time:08-27

 public bool RemoveProduct(int id)
        {
            // code to remove product by the id provided as parameter
            try 
            {
                var prod = productlist.Where(s => s.ProductId == id).FirstOrDefault();
                productlist.Remove(prod);
            }
            catch (Exception) 
            {
                return false;
            }
            return true;
            

        }

I tried to call the function RemoveProduct(id) with parameter Id which is not present in the productlist, it should return false but it is always returning true no matter what. How to solve this problem and return false when the product with the given id isn't in the list?

CodePudding user response:

This is because neither FirstOrDefault() or Remove() will throw an exception when not finding a value in your list.

You could either return false if you didn't find your item (prod == null).

Or just return the result of Remove() (though if you have a null item and did not find an item with the provided id, you'd end up removing it and returning true either way)

As it is right now, the only case where your method would return false is when your list is null, resulting in a NullReferenceException

CodePudding user response:

I would do something like this, if you really want a true/false return.

public bool RemoveProduct(int id)
{
    // code to remove product by the id provided as parameter
    var prod = productlist.Where(s => s.ProductId == id).FirstOrDefault();
 
    if (prod == null) return false;        

    productlist.Remove(prod);

    return true;
}
       
  • Related