IEnumberable.Max and Nullable types

Came across an interesting little snippet of code today.

var max = list.Max(i => i.Value)

This simply returns the maximum value of the “Value” property in the list. However there is a possible problem with this code, depending on the type of Value and the number of elements in the list.

If there are NO elements in the list and Value is NOT nullable (e.g. it is an Integer) then the above will throw an exception.

If there are NO elements in the list and Value IS nullable then it will return NULL.

var max = list.Max(i => i.Value ?? 0)

If the list is empty and Value IS nullable then the above will also throw an exception.

var max = list.Max(i => i.Value) ?? 0

If the list is empty and Value IS nullable then the above will return 0.

Leave a Reply