Home > Software engineering >  Return an empty enumerable instead of getting nullReferenceException still throwing exception
Return an empty enumerable instead of getting nullReferenceException still throwing exception

Time:08-04

I see the GetById function is returning null in this forEach which is throwing an exception, to prevent this I tried returning an empty Enumerable of that same type however I still get the System.NullReferenceException: Object reference not set to an instance of an object.

foreach (var categoryEntry in menus.GetById(options.OnlineOrdering.MenuId).Categories.OrderBy(i => i.Position) ?? Enumerable.Empty<MenuMenuCategory>())

CodePudding user response:

You're accounting for the wrong null checking. If this is returning null:

menus.GetById(options.OnlineOrdering.MenuId)

Then this is throwing the error:

menus.GetById(options.OnlineOrdering.MenuId).Categories

Since you already have a null-coalescing check, you can use a null-conditional check on the expression that's failing:

menus.GetById(options.OnlineOrdering.MenuId)?.Categories

This would cause the entire expression to evaluate to null (never even trying to dereference the Categories property) is GetById() returns null. The result of that expression would then trigger the null-coalescing check you've added, and the loop should successfully iterate zero times as you intend.

  • Related