Why are Enumerable Min or Max incompatible between sets of reference and value types?

When working with empty sequences, I was surprised to learn that the behavior of min or max differs depending on whether the elements of the source collection are a value type or a reference type :

var refCollection = new object[0]; var valCollection = new int[0]; var nullableCollection = new int?[0]; var refMin = refCollection.Min(x => x); // null var valMin = valCollection.Min(); // InvalidOperationException var nullableMin = nullableCollection.Min(); // null 

This difference in behavior is clearly visible in the .NET Framework for Enumerable extensions .

This, however, is not the case when looking at the Jon Skeet MinBy extension , for example, which throws anyway, as I expected.

Isn't the difference in behavior confusing? Is there any use to return null for collections of link types?

+5
source share
1 answer

Keep in mind that types with a null value (both types with null values ​​and reference types) behave differently for types of values ​​that are not null, in the general case when it comes to Min : null considered as "absent" in general, therefore it is unreasonable for the result of "a minimum of only missing values" to be a "missing value".

For instance:

 int?[] nullableInts = new int?[5]; // All values null int? min = nullableInts.Min(); // No exception, min is null nullableInts[3] = 2; min = nullableInts.Min(); // No exception, min is 2 

For types with null values, there really is no way to specify a "missing value" (unless the return type has been changed so that there is always a type with a null value), so the exception ... but this is quite simple in any case, as for a type with zero value, the only situation where there is no minimum is that the source is empty.

(It is possible that MinBy should behave the same :)

This is also consistent with conversions to LINQ to XML:

 XElement element = null; int? x = (int?) element; // null int y = (int) element; // Bang 

In principle, this makes a certain sense - not a single option will fit all.

+8
source

All Articles