Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>To respond directly to your specific question (why use <code>First</code> if you can always use <code>FirstOrDefault</code>), there are instances where you cannot use <code>FirstOrDefault</code>, because it loses information! The "default value" is likely a valid element type in the source list. You have no way to distinguish between the first element in the enumeration being null/default vs. there being no elements in the list unless you use <code>First</code> or first check if there are <code>Any</code> elements, which requires double-enumeration.</p> <p>This is especially true for value-typed enumerables, such as <code>int[]</code>. <code>default(int)</code> is <code>0</code>, which is also most likely a valid value of the array.</p> <p>In general, the two methods represent different logical flows. <code>First</code> would be used if not having any elements is "exceptional" (an error), which then want to handle out-of-band in your application. In this scenario, you "expect" to have at least one element. <code>FirstOrDefault</code> returns null on an empty set, which means you need to do additional processing with the returned value. This is similar logic to the <code>Parse</code> vs <code>TryParse</code> methods on <code>int</code>/<code>double</code>/etc. In fact, your question in some ways leads itself to the more general question of why to ever use exceptions.</p> <p>Since <code>First</code> throws an exception, it lends itself to all of the code-reuse opportunities that exceptions provide. For example, you could do:</p> <pre><code>try { x = arr1.First(); y = arr2.First(); z = arr3.First(); } catch { throw new ArgumentException(); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload