13 lines
1.7 KiB
Plaintext
13 lines
1.7 KiB
Plaintext
When working with collections that are known to be non-empty, using https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.first[First] or https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.single[Single] is generally preferred over https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.firstordefault[FirstOrDefault] or https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.singleordefault[SingleOrDefault].
|
|
|
|
== Why is this an issue?
|
|
|
|
Using `FirstOrDefault` or `SingleOrDefault` on collections that are known to be non-empty is an issue due to:
|
|
|
|
* Code Clarity and intent: When you use `FirstOrDefault` or `SingleOrDefault`, it implies that the collection might be empty, which can be misleading if you know it is not. It can be confusing for other developers who read your code, making it harder for them to understand the actual constraints and behavior of the collection. This leads to confusion and harder-to-maintain code.
|
|
|
|
* Error handling: If the developer's intend is for the collection not to be empty, using `FirstOrDefault` and `SingleOrDefault` can lead to subtle bugs. These methods return a default value (`null` for reference types and `default` for value types) when the collection is empty, potentially causing issues like `NullReferenceException` later in the code. In contrast, `First` or `Single` will throw an `InvalidOperationException` immediately if the collection is empty, making it easier to detect and address issues early in the development process.
|
|
|
|
* Code coverage: Potentially, having to check if the result is `null`, you introduces a condition that cannot be fully tested, impacting the code coverage.
|
|
|