First() vs FirstOrDefault() in C# | How to Use Methods that Return Default Values

watch_later 27 April, 2021

Which method should you use to get the first collection's element that meets a certain condition - 'First' or 'FirstOrDefault'? What should you choose to get the last element - 'Last' or 'LastOrDefault'? At first glance, the choice may not be obvious. Hopefully, this article will answer these questions and help you decide what to choose.

First() vs FirstOrDefault() in C# | How to Use Methods that Return Default Values

Potential NullReferenceException 

Let's start with a quick recap what methods return: FirstOrDefault, LastOrDefault, SingleOrDefault and ElementAtOrDefault. Note they all end in 'OrDefault'. They return the first element of the sequence that satisfies the passed search predicate. Also for the FirstOrDefault, LastOrDefault, SingleOrDefault methods, there are parameter-less overloads that return the first, last, or only element of the sequence, respectively. Here is an important reminder. Let's say, there is more than one element in the sequence that meets the passed predicate. If so, the SingleOrDefault method throws an exception. The same will happen if the SingleOrDefault method is called without a predicate on a sequence containing more than one element. Example of using the FirstOrDefault method:

public static void ProcessFirstOrder(List<Order> orders)
{
    DateTime firstDay = new DateTime(2021, 1, 1);
    Order firstOrder = orders.FirstOrDefault(o => o.OrderDate >= firstDay);
    decimal tax = GetTaxes(firstOrder.Cost);
}

Let's see what happens if at least one order made in 2021 is found in the orders list. The firstOrder variable will get a reference to an object of the Order type. If an element that meets the condition is not found, the method returns the default value for the type contained in the collection. The reference type returns null.

It often happens that developers forget to check the return value for null. This fragment occasionally triggers NullReferenceException that doesn't get you to the the roots of the problem. Check out this list of similar examples. Therefore, you should always check the return value for null.

Methods that return null (in case if there is no a suitable element) might seem to be more reliable analogs compared to their related counterparts: First, Last, Single, ElementAt. After all, methods that do not have the 'Default' suffix in their name will throw the InvalidOperationException type exception if a suitable element was not found in the collection. No one likes when exceptions appear. So why potentially provoke an exceptional situation by using the First, Last, and other methods?

In fact, it is not right to use FirstOrDefault, LastOrDefault type methods in all possible cases. Programmers shouldn't ignore the First and Last methods anyway. As a rule of thumb, you can use the following approach:

  1. use the First method for cases when you are sure that there is at least one suitable element in the collection (or only one in the case of the Single method). Let's say, something went wrong - for example, the array turned out to be empty. Then you face an exceptional case that should be handled. In addition, even if the exception is not handled, the InvalidOperationException type indicates and explains the problem more clearly. By the way, the type provides a very informative message, for example, "Sequence contains no elements". Suppose one of the 'OrDefault'-like methods returned null. You might access a field, property, or method not right away but after a certain number of operations. In this case, the place in the code with the NullReferenceException type exception specified by the stack trace can lead us far from the root of the problem when we see a null reference;
  2. use the FirstOrDefault method for those cases when you know that the collection may not contain the element you need. So you should do another check.

Example of using the FirstOrDefault method with an additional check of the return value for null.

public static void ProcessFirstOrder(List<Order> orders)
{
    DateTime firstDay = new DateTime(2021, 1, 1);
    Order firstOrder = orders.FirstOrDefault(o => o.OrderDate >= firstDay);
    if (firstOrder != null)
    {
        decimal tax = GetTaxes(firstOrder.Cost);
        ....
    }
}

Let's recap. Don't forget to check the value returned by methods of the 'OrDefault' type for null. When you are sure that the method will not return a default value, use methods' counterparts without 'OrDefault' in the name.

Additional links:

  1. StackOverflow. When to use .First and when to use .FirstOrDefault with LINQ?
  2. First, FirstOrDefault, Last, LastOrDefault, Single, and SingleOrDefault.

Summary

In this article we learned when we should use methods FirstOrDefault, LastOrDefault, SingleOrDefault and when it's preferable to use First, Last, Single.

Author Credit

Article Type : Guest Article
Author : Ilya Gainulin
Tags : CSharp, Knowledge
Article Date : 29-03-2021
Article Publish Date : 27-04-2021
Note : All content of this article are copyright of their author.

Codingvila provides articles and blogs on web and software development for beginners as well as free Academic projects for final year students in Asp.Net, MVC, C#, Vb.Net, SQL Server, Angular Js, Android, PHP, Java, Python, Desktop Software Application and etc.



sentiment_satisfied Emoticon