Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why extensions method call is ambiguous?

I got these extensions:

internal static TResult With<TInput, TResult>
    (this TInput? o, Func<TInput, TResult> selector, TResult defaultResult = null)
    where TInput : struct
    where TResult : class
{
    selector.ThrowIfNull("selector");
    return o.HasValue ? selector(o.Value) : defaultResult;
}
internal static TResult? With<TInput, TResult>
    (this TInput? o, Func<TInput, TResult> selector, TResult? defaultResult = null)
    where TInput : struct
    where TResult : struct
{
    selector.ThrowIfNull("selector");
    return o.HasValue ? selector(o.Value) : defaultResult;
}

The first one is oriented at reference typed result and the second one on the Nullable of a struct.

So now why on the first line I got compilation error and on the second I do not?

1.

TimeSpan? time = ((int?)4).With(T => TimeSpan.FromSeconds(T))
// Error. The call is ambiguous.

2.

TimeSpan? time = ((int?)4).With(T => TimeSpan.FromSeconds(T), null)
// No errors. Normally calls the second extension.

Is not that obvius that TimeSpan (as a TResult) is a struct, which is specified at the very top of each extension?

like image 262
AgentFire Avatar asked Dec 28 '25 04:12

AgentFire


1 Answers

Because Constaints are not part of the signature.

like image 118
Thom Smith Avatar answered Dec 30 '25 18:12

Thom Smith