Skip to content

Enumerable.Sum<Nullable<T>> has bad implementation #240

@Azure3bt

Description

@Azure3bt

Describe the bug

When Enumerable.Sum<Nullable<T>> is called with an IEnumerable<Nullable<T>> where all elements are null, the method currently returns 0.

Expected behavior

It is expected that Enumerable.Sum<Nullable<T>> should return null in this scenario, as there are no non-null values to sum. Returning 0 can be ambiguous, as 0 is also a valid sum for inputs like [0, 0].

Minimal repro code

// Test case 1: All nulls
IEnumerable<int?> allNulls = new int?[] { null, null, null };
int? sumAllNulls = allNulls.Sum();
Console.WriteLine($"Sum of all nulls: {sumAllNulls}"); // Currently outputs: Sum of all nulls: 0

// Test case 2: Mixed nulls and zeros
IEnumerable<int?> mixedNullsAndZeros = new int?[] { null, 0, null, 0 };
int? sumMixed = mixedNullsAndZeros.Sum();
Console.WriteLine($"Sum of mixed nulls and zeros: {sumMixed}"); // Currently outputs: Sum of mixed nulls and zeros: 0

// Test case 3: All zeros
IEnumerable<int?> allZeros = new int?[] { 0, 0, 0 };
int? sumAllZeros = allZeros.Sum();
Console.WriteLine($"Sum of all zeros: {sumAllZeros}"); // Currently outputs: Sum of all zeros: 0

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions