Can someone explain me why I'm getting an error on the null-coalescing on the following method:
private readonly Product[] products = new Product[];
[HttpGet("{id}")]
public ActionResult<Product> GetById(int id)
{
var product = products.FirstOrDefault(p => p.Id == id);
if (product == null)
return NotFound(); // No errors here
return product; // No errors here
//I want to replace the above code with this single line
return products.FirstOrDefault(p => p.Id == id) ?? NotFound(); // Getting an error here: Operator '??' cannot be applied to operands of type 'Product' and 'NotFoundResult'
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
What I don't understand is why the first returns are working without needs of any cast while the seconde single line null-coalescing doesn't works!
I'm targeting ASP.NET Core 2.1
Edit:
Thanks @Hasan and @dcastro for the explanations, but I don't recommend to use the null-coalescing here as the NotFound()
will not return the correct error code after the cast!
return (ActionResult<Product>)products?.FirstOrDefault(p => p.Id == id) ?? NotFound();