c# – Checking for null before GetValueOrDefault

Question:

Linq, Sum method for nullable types :

public static int? Sum(this IEnumerable<int?> source) {
    if (source == null) throw Error.ArgumentNull("source");
    int sum = 0;
    checked {
        foreach (int? v in source) {
            if (v != null) sum += v.GetValueOrDefault();
        }
    }
    return sum;
}

What is the meaning of the design

if (v != null) sum += v.GetValueOrDefault();

As far as I understand, it would be possible to write simply without changing the result

sum += v.GetValueOrDefault();

So why if ?

Answer:

From the point of view of the resulting value, nothing really changes, however, the more null values ​​in the provided source , the faster the specified method will work.

Scroll to Top
AllEscort