dotnet / dotnet/dotnet-api-docs
First example results in a null reference exception if really used with an empty sequence
- Dominant language
- C#
- Stars
- 949
- Forks
- 1.7k
- Avg merge
- 3d 27m
- Merged PRs (30d)
- 49
Description
### Type of issue
Typo
### Description
The code accesses the property `Name` of the object `pet` which, in case of an empty sequence is the default value for the type `Pet` - a class, therefore null. Personally, I think for loops that do nothing on empty sequences are fine, but for the sake of the example, let's encode an empty sequence handling in the for loop body and examine why this approach is problematic:
```csharp
class Pet
{
public string Name { get; set; }
public int Age { get; set; }
}
public static void DefaultIfEmptyEx1()
{
List pets =
new List{ new Pet { Name="Barley", Age=8 },
new Pet { Name="Boots", Age=4 },
new Pet { Name="Whiskers", Age=1 } };
foreach (Pet pet in pets.DefaultIfEmpty())
{
**if (pet == null) Console.WriteLine("No pets");
else** Console.WriteLine(pet.Name);
}
}
/*
This code produces the following output:
Barley
Boots
Whiskers
*/
```
As can be seen, the condition `pet == null` is not a good indicator on whether the sequence is actually empty, because it might just contain null instances.
An overall better example would be to use a method that would normally throw when called on an empty sequence, e.g.:
```
List numbers = new List() { 1, 2, 3, 4, 5, 6 };
int maximum = numbers.DefaultIfEmpty().Max();
Console.WriteLine(maximum);
numbers = new List();
maximum = numbers.DefaultIfEmpty().Max();
Console.WriteLine(maximum);
/*
This code produces the following output:
6
0
*/
```
Max from an `IEnumerable` would throw on an empty sequence, whereas a foreach-loop handles empty sequences just fine.
### Page URL
https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.defaultifempty?view=net-10.0
### Content source URL
https://github.com/dotnet/dotnet-api-docs/blob/main/xml/System.Linq/Enumerable.xml
### Document Version Independent Id
8578c8e5-adad-0739-35a4-7d18b7dd3b55
### Platform Id
ee397038-ddf6-6808-04ee-0f612db7c91c
### Article author
@dotnet-bot
Contributor guide
Assessment
This issue has not been assessed yet.