Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return an empty enumerable instead of getting nullReferenceException still throwing exception

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading