Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix "TrySingle" signature with honest nullable annotations #801

Merged
merged 1 commit into from
Mar 18, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 6 additions & 10 deletions MoreLinq/Experimental/TrySingle.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ partial class ExperimentalEnumerable
/// than two elements from the sequence.
/// </remarks>

public static (TCardinality Cardinality, T Value)
public static (TCardinality Cardinality, T? Value)
TrySingle<T, TCardinality>(this IEnumerable<T> source,
TCardinality zero, TCardinality one, TCardinality many) =>
TrySingle(source, zero, one, many, ValueTuple.Create);
Expand Down Expand Up @@ -96,19 +96,15 @@ public static (TCardinality Cardinality, T Value)

public static TResult TrySingle<T, TCardinality, TResult>(this IEnumerable<T> source,
TCardinality zero, TCardinality one, TCardinality many,
// TODO review second argument of resultSelector
// ...that can be defaulted to null for nullable references
// so the signature is not quite accurate, but can we do
// something about that?
Func<TCardinality, T, TResult> resultSelector)
Func<TCardinality, T?, TResult> resultSelector)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector));

switch (source.TryGetCollectionCount())
{
case 0:
return resultSelector(zero, default!);
return resultSelector(zero, default);
case 1:
{
var item = source switch
Expand All @@ -120,15 +116,15 @@ public static TResult TrySingle<T, TCardinality, TResult>(this IEnumerable<T> so
return resultSelector(one, item);
}
case {}:
return resultSelector(many, default!);
return resultSelector(many, default);
default:
{
using var e = source.GetEnumerator();
if (!e.MoveNext())
return resultSelector(zero, default!);
return resultSelector(zero, default);
var current = e.Current;
return !e.MoveNext() ? resultSelector(one, current)
: resultSelector(many, default!);
: resultSelector(many, default);
}
}
}
Expand Down