XOrDefault Methods with Defaults

Learn how to use safe defaults when FirstOrDefault doesn't find any elements.

How to use an alternative default value with FirstOrDefault

One mistake when working with FirstOrDefault, LastOrDefault, and SingleOrDefault is using their result without checking if the returned value is different from null. Remember, when working with a collection of objects, these three methods return null when they don’t find any matching elements in the collection.

One alternative to working with FirstOrDefault and similar methods is to always check for null before using its results.

Get hands-on with 1000+ tech skills courses.