---
title: "When to use .First and when to use .FirstOrDefault with LINQ?"  
description: "When to use .First and when to use .FirstOrDefault with LINQ?"  
author: "Steilla Mitchel"  
published: 2023-08-17  
updated: 2023-08-18  
canonical: https://www.mindstick.com/forum/159561/when-to-use-first-and-when-to-use-firstordefault-with-linq  
category: "c#"  
tags: ["c#", "linq"]  
reading_time: 2 minutes  

---

# When to use .First and when to use .FirstOrDefault with LINQ?

When to use .First and when to use .FirstOrDefault with [LINQ](https://www.mindstick.com/articles/12007/language-integrated-query-linq-queries)?

## Replies

### Reply by Aryan Kumar

The `First()` and `FirstOrDefault()` methods in LINQ are both used to return the first element of a sequence. The difference between the two methods is that `First()` will throw an exception if the sequence is empty, while `FirstOrDefault()` will return the default value of the sequence's type if the sequence is empty.

Here is an example of how to use the `First()` method:

C#

```plaintext
var numbers = new List<int>();
numbers.Add(10);
numbers.Add(20);
numbers.Add(30);

var firstNumber = numbers.First();
```

In this code, the `First()` method returns the first element of the `numbers` list, which is 10.

Here is an example of how to use the `FirstOrDefault()` method:

C#

```plaintext
var numbers = new List<int>();

var firstNumber = numbers.FirstOrDefault();
```

In this code, the `FirstOrDefault()` method returns the first element of the `numbers` list, which is `null` because the list is empty.

So, when should you use `First()` and when should you use `FirstOrDefault()`?

- Use `First()` when you are sure that the sequence will not be empty.
- Use `FirstOrDefault()` when you are not sure whether the sequence will be empty.

In general, it is better to use `FirstOrDefault()` because it is more robust. If you use `First()` and the sequence is empty, your code will throw an exception. This can cause your program to crash.

However, if you use `FirstOrDefault()` and the sequence is empty, your code will simply return the default value of the sequence's type. This is usually a harmless outcome.


---

Original Source: https://www.mindstick.com/forum/159561/when-to-use-first-and-when-to-use-firstordefault-with-linq

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
